# Manager UI (part 3): Team roster UI screen

> Learn how to create a draggable grid with Gameface's UI components and SolidJS.

> 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-screen/

## Manager UI (part 3): Team roster UI screen

ui tutorials

3/27/2025

Martin Bozhilov

1. Overview
   1. Main features
2. Model setup
3. UI structure setup
   1. Component Breakdown
   2. Disable grid interactions when scrolling
4. Display player’s data
   1. Displaying player data and controlling the size
   2. Resolving image imports with custom data-bind attribute
5. Sorting the players
   1. Table header structure
   2. Sorting logic
6. Drag and drop player’s row
   1. Attaching the Events
   2. Defining global methods
   3. Displaying the Cloned Row
   4. Swapping rows
7. Scrolling the table while dragging
   1. Creating the ScrollArea Component
   2. Integrating ScrollArea into TeamRoster
8. Conclusion

This is the third tutorial in the Manager UI series. In the previous tutorial, we laid the foundation for the Manager UI.

From now on, we will gradually add various UI screens to the Manager UI sample, starting with the **Team Roster screen**. This screen allows the player to view their team in a table format and rearrange rows either via drag-and-drop or by sorting any of the table columns.

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

One of the key features of the Manager UI is its modularity and flexible screen arrangement. The Team Roster screen can be shrunk to a 1x1 grid, and its contents will adjust accordingly to display only the most important columns.

### Main features

- **Table with drag-and-drop functionality**
- **Data binding**: Data is displayed from a mocked model
- **Responsive UI** - Resizes to fit smaller grid arrangements
- **Scroll support**

## Model setup

First, we need to set up our mocked data using a model. Our model will consist of a `players` array that holds each player’s details—such as name, nationality, and other key statistics. To begin, add the `team-roster-model.js` file to your `models` folder.

```js
const TeamRoster = {
    players: [
        {
            name: "John Anderson",
            nationality: "gb-eng",
            ability: 4.5,
            type: "striker",
            preferred_positions: ["ST", "LW"],
            is_injured: false,
            goals: 20,
            assists: 7,
            clean_sheets: null,
            appearances: 20,
            minutes: 1800,
            image: "players/player-gb-eng.png",
            countryImage: "flags/gb-eng.svg",
            kit_number: 9
        },
        {
            name: "Carlos Pérez",
            nationality: "es",
            ability: 4.2,
            type: "midfielder",
            preferred_positions: ["CM", "CAM"],
            is_injured: true,
            goals: 8,
            assists: 15,
            clean_sheets: null,
            appearances: 15,
            minutes: 1350,
            image: "players/player-es.png",
            countryImage: "flags/es.svg",
            kit_number: 8
        },
        {
            name: "Liam O'Connor",
            nationality: "ie",
            ability: 3.8,
            type: "defender",
            preferred_positions: ["CB", "SW"],
            is_injured: false,
            goals: 3,
            assists: 2,
            clean_sheets: null,
            appearances: 18,
            minutes: 1620,
            image: "players/player-ie.png",
            countryImage: "flags/ie.svg",
            kit_number: 5
        },
        {
            name: "Michael Johnson",
            nationality: "us",
            ability: 4.0,
            type: "goalkeeper",
            preferred_positions: ["GK"],
            is_injured: false,
            goals: 0,
            assists: 1,
            clean_sheets: 12,
            appearances: 22,
            minutes: 1980,
            image: "players/player-us.png",
            countryImage: "flags/us.svg",
            kit_number: 1
        },
        {
            name: "Marco Rossi",
            nationality: "it",
            ability: 4.6,
            type: "striker",
            preferred_positions: ["ST", "RW"],
            is_injured: false,
            goals: 25,
            assists: 9,
            clean_sheets: null,
            appearances: 21,
            minutes: 1890,
            image: "players/player-it.png",
            countryImage: "flags/it.svg",
            kit_number: 10
        },
        {
            name: "Victor Müller",
            nationality: "de",
            ability: 4.3,
            type: "midfielder",
            preferred_positions: ["DM", "CM"],
            is_injured: false,
            goals: 4,
            assists: 10,
            clean_sheets: null,
            appearances: 20,
            minutes: 1800,
            image: "players/player-de.png",
            countryImage: "flags/de.svg",
            kit_number: 6
        },
        {
            name: "Felix Kim",
            nationality: "kr",
            ability: 3.9,
            type: "defender",
            preferred_positions: ["RB", "CB"],
            is_injured: false,
            goals: 1,
            assists: 3,
            clean_sheets: null,
            appearances: 16,
            minutes: 1440,
            image: "players/player-kr.png",
            countryImage: "flags/kr.svg",
            kit_number: 2
        },
        {
            name: "Samuel Dembélé",
            nationality: "fr",
            ability: 4.7,
            type: "striker",
            preferred_positions: ["LW", "FW"],
            is_injured: false,
            goals: 19,
            assists: 12,
            clean_sheets: null,
            appearances: 19,
            minutes: 1710,
            image: "players/player-fr.png",
            countryImage: "flags/fr.svg",
            kit_number: 7
        },
        {
            name: "Alejandro Vargas",
            nationality: "ar",
            ability: 4.4,
            type: "midfielder",
            preferred_positions: ["CAM", "LM"],
            is_injured: false,
            goals: 6,
            assists: 18,
            clean_sheets: null,
            appearances: 18,
            minutes: 1620,
            image: "players/player-unknown.png",
            countryImage: "flags/ar.svg",
            kit_number: 11
        },
        {
            name: "David Silva",
            nationality: "br",
            ability: 4.1,
            type: "goalkeeper",
            preferred_positions: ["GK"],
            is_injured: false,
            goals: 0,
            assists: 0,
            clean_sheets: 10,
            appearances: 20,
            minutes: 1800,
            image: "players/player-br.png",
            countryImage: "flags/br.svg",
            kit_number: 13
        },
        {
            name: "Yusuf Hassan",
            nationality: "eg",
            ability: 3.6,
            type: "defender",
            preferred_positions: ["LB", "LWB"],
            is_injured: false,
            goals: 0,
            assists: 4,
            clean_sheets: null,
            appearances: 17,
            minutes: 1530,
            image: "players/player-eg.png",
            countryImage: "flags/eg.svg",
            kit_number: 3
        },
        {
            name: "Tom Nguyen",
            nationality: "vn",
            ability: 4.0,
            type: "defender",
            preferred_positions: ["RB", "RWB"],
            is_injured: false,
            goals: 1,
            assists: 5,
            clean_sheets: null,
            appearances: 15,
            minutes: 1350,
            image: "players/player-unknown.png",
            countryImage: "flags/vn.svg",
            kit_number: 4
        },
        {
            name: "Ethan White",
            nationality: "ca",
            ability: 3.9,
            type: "midfielder",
            preferred_positions: ["DM", "CM"],
            is_injured: false,
            goals: 3,
            assists: 7,
            clean_sheets: null,
            appearances: 14,
            minutes: 1260,
            image: "players/player-unknown.png",
            countryImage: "flags/ca.svg",
            kit_number: 14
        },
        {
            name: "Ryo Tanaka",
            nationality: "jp",
            ability: 4.2,
            type: "midfielder",
            preferred_positions: ["RM", "CAM"],
            is_injured: false,
            goals: 5,
            assists: 9,
            clean_sheets: null,
            appearances: 19,
            minutes: 1710,
            image: "players/player-jp.png",
            countryImage: "flags/jp.svg",
            kit_number: 16
        },
        {
            name: "Moussa Traoré",
            nationality: "ci",
            ability: 3.8,
            type: "goalkeeper",
            preferred_positions: ["GK"],
            is_injured: true,
            goals: 0,
            assists: 0,
            clean_sheets: 6,
            appearances: 14,
            minutes: 1260,
            image: "players/player-unknown.png",
            countryImage: "flags/ci.svg",
            kit_number: 22
        },
        {
            name: "Emmanuel Okoro",
            nationality: "ng",
            ability: 3.7,
            type: "defender",
            preferred_positions: ["CB", "SW"],
            is_injured: false,
            goals: 0,
            assists: 2,
            clean_sheets: null,
            appearances: 16,
            minutes: 1440,
            image: "players/player-unknown.png",
            countryImage: "flags/ng.svg",
            kit_number: 15
        },
        {
            name: "Lucas Fernandes",
            nationality: "pt",
            ability: 4.0,
            type: "midfielder",
            preferred_positions: ["LM", "CM"],
            is_injured: false,
            goals: 4,
            assists: 6,
            clean_sheets: null,
            appearances: 18,
            minutes: 1620,
            image: "players/player-unknown.png",
            countryImage: "flags/pt.svg",
            kit_number: 12
        },
        {
            name: "Anders Berg",
            nationality: "se",
            ability: 3.9,
            type: "goalkeeper",
            preferred_positions: ["GK"],
            is_injured: false,
            goals: 0,
            assists: 0,
            clean_sheets: 8,
            appearances: 17,
            minutes: 1530,
            image: "players/player-unknown.png",
            countryImage: "flags/se.svg",
            kit_number: 21
        },
        {
            name: "Diego Hernández",
            nationality: "mx",
            ability: 4.5,
            type: "striker",
            preferred_positions: ["FW", "RW"],
            is_injured: false,
            goals: 21,
            assists: 8,
            clean_sheets: null,
            appearances: 20,
            minutes: 1800,
            image: "players/player-unknown.png",
            countryImage: "flags/mx.svg",
            kit_number: 17
        },
        {
            name: "Oscar Schmidt",
            nationality: "dk",
            ability: 3.8,
            type: "defender",
            preferred_positions: ["LB", "CB"],
            is_injured: false,
            goals: 1,
            assists: 3,
            clean_sheets: null,
            appearances: 15,
            minutes: 1350,
            image: "players/player-unknown.png",
            countryImage: "flags/dk.svg",
            kit_number: 18
        },
        {
            name: "Takumi Nakamura",
            nationality: "jp",
            ability: 4.2,
            type: "midfielder",
            preferred_positions: ["RM", "CM"],
            is_injured: true,
            goals: 6,
            assists: 9,
            clean_sheets: null,
            appearances: 19,
            minutes: 1710,
            image: "players/player-jp.png",
            countryImage: "flags/jp.svg",
            kit_number: 19
        },
        {
            name: "Ebrahim Khalid",
            nationality: "eg",
            ability: 4.1,
            type: "midfielder",
            preferred_positions: ["DM", "CM"],
            is_injured: true,
            goals: 2,
            assists: 5,
            clean_sheets: null,
            appearances: 14,
            minutes: 1260,
            image: "players/player-eg.png",
            countryImage: "flags/eg.svg",
            kit_number: 20
        },
        {
            name: "Pablo Alvarez",
            nationality: "cl",
            ability: 3.9,
            type: "defender",
            preferred_positions: ["CB", "SW"],
            is_injured: false,
            goals: 0,
            assists: 2,
            clean_sheets: null,
            appearances: 16,
            minutes: 1440,
            image: "players/player-unknown.png",
            countryImage: "flags/cl.svg",
            kit_number: 24
        },
        {
            name: "Luka Petrovic",
            nationality: "rs",
            ability: 4.0,
            type: "striker",
            preferred_positions: ["ST", "LW"],
            is_injured: false,
            goals: 15,
            assists: 6,
            clean_sheets: null,
            appearances: 18,
            minutes: 1620,
            image: "players/player-unknown.png",
            countryImage: "flags/rs.svg",
            kit_number: 23
        },
        {
            name: "Ahmed Mansour",
            nationality: "jo",
            ability: 3.7,
            type: "goalkeeper",
            preferred_positions: ["GK"],
            is_injured: false,
            goals: 0,
            assists: 0,
            clean_sheets: 5,
            appearances: 12,
            minutes: 1080,
            image: "players/player-unknown.png",
            countryImage: "flags/jo.svg",
            kit_number: 25
        }
    ],
}
export default TeamRoster;
```

Next, create the model in your project by updating your model index file as follows:

```js
import GridDataModel from './grid-data-model';
import TeamRosterModel from './team-roster-model';

engine.whenReady.then(() => {
    engine.createJSModel('GridData', GridDataModel);
    engine.createJSModel('TeamRosterModel', TeamRosterModel);
});
```

From now on, we will refer to this model as `TeamRosterModel`.

## UI structure setup

We’ll organize all UI screens displayed in the grid by placing them in a dedicated `Screens` folder. In this folder, create a new component called `TeamRoster.tsx`, which will serve as the main component for this UI screen.

Below is the code for the `TeamRoster.tsx` component:

```tsx
import styles from './TeamRoster.module.css';
import { Component } from "solid-js";
import Scroll from "@components/Layout/Scroll/Scroll";
import TableHeader from "./TableHeader";
import TableRow from "./TableRow";
import './globalTeamRoster.css'
import Layout from "@components/Layout/Layout/Layout";

const TeamRoster: Component = () => {

    return (
        <Layout class={styles.TeamRoster}>
            <TableHeader  />
            <Scroll>
                <TableRow />
            </Scroll>
        </Layout>
    )
}

export default TeamRoster
```

And here’s the corresponding CSS:

```css
.TeamRoster {
    background-color: #0F0F11;
    display: flex;
    flex-direction: column;
}

.ScrollContainer {
    max-width: 100%;
    flex: 1;
}
```

### Component Breakdown

- `TableHeader` - Handles the table’s header and sorting functionality.
- `TableRow` - Displays the players’ information.

Both components will have the same structure and we are going to acheive this with the help of the `Column` GameFace UI components.

### Disable grid interactions when scrolling

One thing we must do before enabling any interactions within the `TeamRoster` component is to disable the grid drag and drop behavior when the player clicks on the scroll bar of the `Scroll` component.

Since the [Gameface UI](https://gameface-ui.coherent-labs.com/) components are directly imported from the `components` folder, we can go to the implementation of the [Scroll](https://gameface-ui.coherent-labs.com/components/layout/scroll/) component and add what we need there.

Inside the `onHandleMouseDown` and `onHandleMouseUp` we will disable and enable the `shouldDrag` state respectively:

```tsx
function onHandleMouseDown(e: MouseEvent) {
    startY = e.clientY;
    startScrollTop = contentRef!.scrollTop;
    window.addEventListener("mousemove", onHandleMouseMove);
    window.addEventListener("mouseup", onHandleMouseUp);

    // custom modification
    gridInteractionState.shouldDrag = false;
}
```

```tsx
function onHandleMouseUp() {
    window.removeEventListener("mousemove", onHandleMouseMove);
    window.removeEventListener("mouseup", onHandleMouseUp);

    // custom modification
    gridInteractionState.shouldDrag = true;
}
```

Now we can proceed with the main part of the UI.

## Display player’s data

In this section, we’ll create the `TableRow` component, which is responsible for displaying our team data in a row format. The component defines the row structure once and then uses the `data-bind-for` attribute to loop through the players from the model, dynamically displaying each player’s information.

Additionally we utilize both [structural data-bind attributes ](https://docs.coherent-labs.com/cpp-gameface/integration/ui_scripting/htmldatabinding/#structural-data-binding), and a [custom data-bind attribute ](https://docs.coherent-labs.com/cpp-gameface/integration/ui_scripting/htmldatabinding/#custom-data-binding-attributes)to managa `data-binding`.

### Displaying player data and controlling the size

The `TableRow` component uses a prop called `sizeExpression` to determine which columns to show based on the current screen size. When the UI is resized to a 1x1 grid, the `sizeExpression` condition hides less critical columns, ensuring that only the most important player details are visible. The component is built using various GameFace UI components such as [Column1](https://gameface-ui.coherent-labs.com/components/layout/column/), [Column4](https://gameface-ui.coherent-labs.com/components/layout/column/), [Row](https://gameface-ui.coherent-labs.com/components/layout/row/), [Flex](https://gameface-ui.coherent-labs.com/components/layout/flex/), and [Block](https://gameface-ui.coherent-labs.com/components/layout/block/)

```tsx
import { Column1, Column4 } from "@components/Layout/Column/Column";
import Row from "@components/Layout/Row/Row";
import styles from './TeamRoster.module.css';
import Flex from "@components/Layout/Flex/Flex";
import Block from "@components/Layout/Block/Block";
import Relative from "@components/Layout/Relative/Relative";
import Image from "@components/Media/Image/Image";
import InjuredIcon from '@assets/misc/injured.svg';

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)"
            >
            <Column1 data-bind-class-toggle={`Column-Position:${props.sizeExpression}`} class={`${styles.Column}`}>
                <Relative>
                    <Flex align-items="center" justify-content="center" style={{width: '100%', height: '100%'}}>
                        <Block class={styles.PositionTag} data-bind-class="'player-role-'+{{player.type}}"></Block>
                        <Block data-bind-value="{{player.preferred_positions[0]}}"></Block>
                    </Flex>
                </Relative>
            </Column1>
            <Column1 data-bind-class-toggle={`Column-Nationality:${props.sizeExpression}`} class={`${styles.Column}`}>
                <Block class={styles.FlagImage} data-bind-background-image="{{player.countryImage}}"></Block>
            </Column1>
            <Column1 data-bind-class-toggle={`Column-Ability:${props.sizeExpression}`} class={`${styles.Column}`}>
                <Block data-bind-style-background-position-x="100-(20*{{player.ability}}) + '%'" class={styles.Ability}></Block>
            </Column1>
            <Column4 data-bind-class-toggle={`Column-Player:${props.sizeExpression}`} class={`${styles.Column}`}>
                <Flex align-items="center" style={{ width: '100%', height: '100%', "padding-right": '0.4vmax'}}>
                    <Block data-bind-background-image="{{player.image}}" class={styles.PlayerImage}></Block>
                    <Flex style={{flex: '1'}} align-items="center" >
                        <Block class={styles.PlayerName} data-bind-value="{{player.name}}"></Block>
                        <Image data-bind-if="{{player.is_injured}}" src={InjuredIcon} class={styles.InjuredIcon} />
                    </Flex>
                </Flex>
            </Column4>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} data-bind-value="{{player.preferred_positions}}" class={styles.Column}></Column1>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} data-bind-value="{{player.goals}}" class={styles.Column}></Column1>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} data-bind-value="{{player.assists}}" class={styles.Column}></Column1>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} data-bind-value="{{player.appearances}}" class={styles.Column}></Column1>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} data-bind-value="{{player.minutes}}" class={styles.Column}></Column1>
        </Row>
    )
}

export default TableRow
```

Let’s also add the styles:

```css
.PlayerRow {
    align-items: center;
    height: 3vmax;
    margin-bottom: 0.25vmax;
    background-color: #1D1D20;
    flex-wrap: nowrap;
}

.Column {
    font-size: 0.70vmax;
    text-align: center;
}

.PositionTag {
    position: absolute;
    left: 0;
    width: 15%;
    height: 100%;
}

.FlagImage {
    width: 70%;
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: contain;
}

.Ability {
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, #E4AC59 0%, #E4AC59 50%, #646464 50%, #646464 100%);
    mask-image: url('@assets/misc/Stars.svg');
    mask-size: 100% 100%;
    mask-position: 0% 50%;
    mask-repeat: no-repeat;
    background-size: 200% 100%;
    background-position: 50% 0;
}

.PlayerImage {
    min-width: 35%;
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: contain;
}

.PlayerName {
    padding-left: 0.5vmax;
    padding-right: 0.3vmax;
}

.InjuredIcon {
    width: 0.5vmax;
    height: 0.5vmax;
}
```

Here’s a brief overview of what each part of the row does:

- **Player Position**: A column that displays a position tag. It dynamically assigns a CSS class based on the player’s role (e.g., striker, midfielder) to change the tag’s background color.
- **Nationality**: A column that shows the player’s flag. A custom data-bind attribute (`data-bind-player-country-image`) is used to dynamically set the background image to the correct flag icon.
- **Ability**: A column that displays a block with a gradient background. The background’s position is dynamically calculated based on the player’s ability.
- **Player Information**: This section displays the player’s image, name, and an injured icon if the player is injured.
- **Additional Details**: Several columns display extra information such as preferred positions, goals, assists, appearances, and minutes. These columns are conditionally hidden when the screen is in a minimized (1x1) state.

Because CSS modules resolve class names at runtime, we cannot directly use them with our `data-binding` expressions. To work around this, we define an additional global CSS file (`globalTeamRoster.css`) that includes utility classes (like `.hidden`) and classes for conditionally styling columns (such as `.Column-Position`, `.Column-Nationality`, etc.). This global CSS file also defines the color schemes for player roles.

```css
/* utility */
.hidden {
    display: none;
}

/* Column small screen width override */
.Column-Position {
    flex-basis: 12%;
    max-width: 12%;
}

.Column-Nationality {
    flex-basis: 12%;
    max-width: 12%;
}

.Column-Ability {
    flex-basis: 20%;
    max-width: 20%;
}

.Column-Player {
    flex-basis: 55%;
    max-width: 55%;
}

/* Player Tag */
.player-role-striker {
    background-color: var(--main-red);
}

.player-role-midfielder {
    background-color: var(--main-orange);
}

.player-role-defender {
    background-color: var(--main-light-green);
}

.player-role-goalkeeper {
    background-color: var(--main-teal);
}
```

We have also defined some of the main colors that will be used throughout this project as `CSS variables`

```css
:root {
  --main-red: #ED1054;
  --main-orange: #EA8F43;
  --main-light-green: #B6F52E;
  --main-teal: #23E6A1;
}
```

After setting up the `TableRow` component, remember to update the parent `TeamRoster` component to pass the `sizeExpression` prop to both the `TableHeader` and `TableRow` components. This ensures that the table’s layout responds correctly when the screen size changes.

```tsx
const TeamRoster: Component = () => {
    const sizeExpression = "{{GridData.gridItems[0].sizeX}} === 1";

return (
    <Layout class={styles.TeamRoster}>
            <TableHeader />
            <TableHeader sizeExpression={sizeExpression} />
        <Scroll ref={scrollRef} class={styles.ScrollContainer}>
            <TableRow />
            <TableRow sizeExpression={sizeExpression} />
        </Scroll>
    )
}
```

### Resolving image imports with custom data-bind attribute

To easily import images from our model in a `vite` project such as this one, we can leverage a `custom data-bind` attribute. We are going to create a `data-bind-background-image` attribute which will get the string path to the image and resolve the import at runtime.

For this purpose, we will need to add a utility function that will help us resolve static file import paths.

```ts
export function getImageUrl(name: string) {
    return new URL(`../assets/${name}`, import.meta.url).href
}
```

`getImageUrl` will give us the correct path to the assets folder both in development and production.

Now let’s implement the custom `data-binding` class:

```js
import { getImageUrl } from '../index'

class BackgroundImage {

    init(element, value) {
        element.style.backgroundImage = `url(${getImageUrl(value)})`
    }

    deinit(element) {}

    update(element, value) {
        element.style.backgroundImage = `url(${getImageUrl(value)})`
    }
}

engine.whenReady.then(() => {
    engine.registerBindingAttribute("background-image", BackgroundImage);
})
```

The logic is pretty simple - we are just setting the background image url of the element by accepting a `value` argument, which we expect to be a valid path to an image in our assets folder, for example: `players/player-de.png`.

With these changes, the team data from the model is rendered in a table-like format that is both dynamic and responsive.

## Sorting the players

Now that we have displayed our model’s data, it’s time to add interactions. The first interaction we’re implementing is sorting the rows. To achieve this, we need to create **a table header.**

### Table header structure

We create a `TableHeader` component to handle all the sorting logic. This component also utilizes the GameFace UI’s `Column` components as is done for the `TableRow`. It also manages the sorting state using two signals:

- `currentSort` - The column we are currently sorting by (set to **ability** by default)
- `asc` - The order of the sort (set to ascending by default)

```tsx
import { Column1, Column4 } from "@components/Layout/Column/Column";
import Row from "@components/Layout/Row/Row";
import styles from './TeamRoster.module.css';
import HeaderColumn from "./HeaderColumn";
import { createSignal, onMount } from "solid-js";

const TableHeader = (props: {sizeExpression: string}) => {
    const [asc, setAsc] = createSignal(true);
    const [currentSort, setCurrentSort] = createSignal<sortType>('ability')

    return (
        <Row class={styles.Header}>
            <Column1 data-bind-class-toggle={`Column-Position:${props.sizeExpression}`} class={styles.Column}>
                <HeaderColumn sortBy="type" handleSort={handleSort} currentSort={currentSort} asc={asc}>POS</HeaderColumn>
            </Column1>
            <Column1 data-bind-class-toggle={`Column-Nationality:${props.sizeExpression}`} class={styles.Column}>
                <HeaderColumn sortBy="nationality" handleSort={handleSort} currentSort={currentSort} asc={asc}>NAT</HeaderColumn>
            </Column1>
            <Column1 data-bind-class-toggle={`Column-Ability:${props.sizeExpression}`} class={styles.Column}>
                <HeaderColumn sortBy="ability" handleSort={handleSort} currentSort={currentSort} asc={asc}>ABILITY</HeaderColumn>
            </Column1>
            <Column4 data-bind-class-toggle={`Column-Player:${props.sizeExpression}`} class={styles.Column}>
                <HeaderColumn sortBy="name" handleSort={handleSort} currentSort={currentSort} asc={asc}>PLAYER</HeaderColumn>
            </Column4>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} class={styles.Column}>PREF POS</Column1>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} class={styles.Column}>
                <HeaderColumn sortBy="goals" handleSort={handleSort} currentSort={currentSort} asc={asc}>G</HeaderColumn>
            </Column1>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} class={styles.Column}>
                <HeaderColumn sortBy="assists" handleSort={handleSort} currentSort={currentSort} asc={asc}>A</HeaderColumn>
            </Column1>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} class={styles.Column}>
                <HeaderColumn sortBy="appearances" handleSort={handleSort} currentSort={currentSort} asc={asc}>APP</HeaderColumn>
            </Column1>
            <Column1 data-bind-class-toggle={`hidden:${props.sizeExpression}`} class={styles.Column}>
                <HeaderColumn sortBy="minutes" handleSort={handleSort} currentSort={currentSort} asc={asc}>MIN</HeaderColumn>
            </Column1>
        </Row>
    )
}

export default TableHeader
```

We are once again utilizng the `data-bind-class-toggle` to conditionally hide some of the columns when the UI shrinks.

Inside the same component, you’ll notice that each header column leverages the `HeaderColumn` component. This component serves as a wrapper for the column buttons, handling the sort action and displaying an arrow icon to indicate whether the sort order is ascending or descending.

```tsx
import Flex from "@components/Layout/Flex/Flex"
import { Accessor, createEffect, createSignal, ParentComponent, Show } 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,
    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)
    }

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

export default HeaderColumn
```

The `HeaderColumn` component will accept the following props:

- `currentSort` - The column we are currently sorting by
- `asc` - The order of the sort
- `handleSort` - The function to execute the table sort
- `sortBy` - The unique string associated with every column to sort by.

On sort change we are going to check if the current sort is equal to the column’s sort value and if it is we are going to set it as active and applying an `active` class. The active class will also display an arrow pointing up or down depending on the sort order.

```css
.Header {
    font-size: 0.75vmax;
    padding: 0.5vmax 0;
    padding-right: 10px;
    color: #7C7C84;
    background-color: #0F0F11;
    font-weight: bold;
    flex-wrap: nowrap;
    white-space: nowrap;
}

.Header-Button {
    cursor: pointer;
    width: 100%;
}

.Header-Button:hover,
.Header-Button:focus {
    color: white;
}

.ActiveCol {
    color: white;
    padding: 0;
    position: relative;
}

.ActiveCol::after {
    content: '';
    width: 0.75vmax;
    height: 0.75vmax;
    position: absolute;
    right: -0.75vmax;
    background-image: url('@assets/misc/Arrow.svg');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    transition: transform 0.2s ease-in-out;
}

.ActiveCol.asc::after {
    transform: rotate(180deg);
}
```

And lastly, let’s declare the `sortType`:

```ts
export type sortType = 'name' | 'nationality' | 'ability' | 'type' | 'goals' | 'assists' | 'clean_sheets' | 'appearances' | 'minutes';
```

With that we should now be able to see our table header displayed.

### Sorting logic

The sorting functionality is implemented via a `handleSort` function in the `TableHeader` component. Here’s a quick overview of what the function does:

1. **Toggle Sort Order**: If the column clicked is already the active sort column, the sort order toggles (ascending ↔ descending).
2. **Sort Players**: The function then sorts the players array in the `TeamRosterModel`. Because sorting methods differ for strings and numbers, a `numericKeys` array is used to determine if the current sort key should be treated numerically or as a string.
3. **Update Model and State**: After sorting, the model is updated (using the `updateModel` utility function), and the `currentSort` state is set to the newly sorted column for visual feedback.

Since sorting between `string` and `number` values is not performed the same way, we will create a `numericKeys` array to easily check if the sorting will be by numbers or strings

```tsx
import { createSignal, onMount } from "solid-js";
import { updateModel } from "../../../../src/utils";
import { sortType } from "src/types/types";

const numericKeys: sortType[] = ['ability', 'goals', 'assists', 'clean_sheets', 'appearances', 'minutes'];

const TableHeader = (props: {sizeExpression: string}) => {
    const [asc, setAsc] = createSignal(true);
    const [currentSort, setCurrentSort] = createSignal<sortType>('ability')

    const handleSort = (key: sortType) => {
        currentSort() === key ? setAsc(prev => !prev) : '';
        sortPlayers(key);
        setCurrentSort(key);
    }

    const sortPlayers = (key: sortType) => {
        TeamRosterModel.players.sort((a, b) => {
            const aValue = a[key] ?? 0;
            const bValue = b[key] ?? 0;

            if (numericKeys.includes(key)) {
                return asc() ?
                    (aValue as number) - (bValue as number) :
                    (bValue as number) - (aValue as number);
            } else {
                return asc() ?
                    String(aValue).localeCompare(String(bValue)) :
                    String(bValue).localeCompare(String(aValue))
            }
        });
        updateModel(TeamRosterModel);
    }

    return (
        <Row class={styles.Header}>
        {/* Rest of component */}
```

Additionally, we call the `handleSort` function inside an `onMount` hook to ensure the table is initially sorted as soon as the component mounts:

```tsx
onMount(() => {
    // Sort initially
    handleSort(currentSort())
})
```

With these enhancements, the table header now not only displays the appropriate labels but also allows you to sort the table by clicking on the header cells. The active sorting column is highlighted with an arrow indicating the sort direction, and the table rows update accordingly.

## Drag and drop player’s row

The final functionality in our UI is enabling row drag and drop, allowing users to swap rows by dragging them. To accomplish this, we attach `data-bind` events to the row elements and directly manipulate the model.

### Attaching the Events

First, we add three event listeners to the row elements: `data-bind-mousedown`, `data-bind-mouseenter`, and `data-bind-mouseleave`.

```tsx
<Row data-bind-for={'index, player:{{TeamRosterModel.players}}'} class={styles.PlayerRow}>
<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)"
    >
```

### Defining global methods

After attaching the event listeners, we need to implement the actual functions that handle these events. Since these functions must be available at runtime, we declare them in the global scope by attaching them to the `window` object.

#### Handling mousedown

We start by implementing the `playerMouseDown` function. This function will:

1. Disable grid drag and drop by setting a `shouldDrag` flag to false.
2. Clone the dragged row and store it in the `gridInteractionState`.
3. Set the cloned element’s dimensions based on the original row.
4. Capture the initial mouse position and calculate the starting top and left coordinates, so the cloned element appears under the cursor.
5. Attach `mousemove` and `mouseup` event handlers to enable dragging and to finalize the drop.

```ts
import { updateModel, updatePositionStyles } from "./index";
import { gridInteractionState } from "../store/gridInteractionStore";

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 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);
}
```

To ensure the cloned (dragged) row displays correctly, add a CSS class that positions it absolutely, reduces its opacity, and sets a high `z-index`.

```css
/* Team roster rows drag and drop  */
.player-row-dragging {
    position: absolute;
    opacity: 0.8;
    z-index: 999999;
    pointer-events: none;
}
```

We use a utility function to update the cloned element’s style by setting its left and top positions.

```ts
export const updatePositionStyles = (element: HTMLDivElement, x: number, y: number) => {
    element.style.left = `${x}px`;
    element.style.top = `${y}px`;
}
```

To keep track of the cloned row, add a new property called `draggedRow` to the `gridInteractionState` store, and update its type accordingly.

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

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

### Displaying the Cloned Row

Now that we have the cloned row stored in our global state, we need to render it in the UI. We use [Solid’s Portal ](https://docs.solidjs.com/concepts/control-flow/portal#portal)component to render the cloned element as a direct child of the `body`.

```tsx
<Portal>
    {gridInteractionState.draggedRow}
</Portal>
```

With these changes, when you click on a row, an exact copy of it is displayed under the player’s cursor, ready for dragging.

### Swapping rows

Now let’s implement the logic for swapping the player rows. We need to implement a total of four functions:

- `playerMouseMove` - Visually moves the dragged row on every mouse move.
- `playerMouseUp` - Resets the grid interaction state and performs the swapping of the rows.
- `playerMouseEnter` - Adds a `new-row-position` utility class to indicate where the dragged row will be inserted. It also assigns the `dropIndex` based on the hovered row.
- `playerMouseLeave` - Removes the `new-row-position` utility class from the row when the cursor leaves.

```ts
window.playerMouseMove = (element, event) => {
    // distance traveled
    const deltaX = event.clientX - startMouseX;
    const deltaY = event.clientY - startMouseY;

    // new coordinates = initial + distance;
    const newLeft = startLeft + deltaX;
    const newTop = startTop + deltaY;

    // visually move
    updatePositionStyles(element, newLeft, newTop);
}

window.playerMouseUp = (element, index) => {
    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)
}

window.playerMouseEnter = (element: HTMLDivElement, index) => {
    if (gridInteractionState.draggedRow === null) return;

    element.classList.add('new-row-position');
    dropIndex = index;
}

window.playerMouseLeave = (element: HTMLDivElement) => {
    if (gridInteractionState.draggedRow === null) return;

    element.classList.contains('new-row-position') && element.classList.remove('new-row-position');
}
```

Let’s also add the CSS classes. We are going to create an `after` pseudo element on the hovered row, with the exact size of the rows to make it appear as a blank spot for the dragged row to appear at.

```css
/* Team roster rows drag and drop  */
.new-row-position {
    border-top: 0.2vmax solid #23d3e6;
    position: relative;
    margin-top: 3vmax;
    transition: margin 1s ease-in-out;
}

.new-row-position::before {
    content: '';
    position: absolute;
    top: -3.2vmax;
    width: 100%;
    height: 3vmax;
    opacity: 0.5;
    z-index: 1;
}
```

And that’s it! The team roster table now allows players to swap rows through drag and drop. When you click and drag a row, a cloned version of it follows the cursor. As you hover over other rows, a visual cue (the new row position) indicates where the dragged row will be inserted when you release the mouse button.

## Scrolling the table while dragging

Currently, if the player wants to move a row to a position beneath the visible area, the only option is to use the scroll wheel. We can enhance this experience by providing dedicated top and bottom areas. When hovered, these areas trigger the `Scroll` component to scroll up or down automatically.

To achieve this, we use the `ScrollUp` and `ScrollDown` methods available via the `ref` of the GameFace UI’s `Scroll` component.

### Creating the ScrollArea Component

First, we create a `ScrollArea` component. This component renders at either the top or bottom of our team roster table and accepts two functions via props: `handleScroll` and `handleScrollStop`. These functions are attached to the `mouseover` and `mouseleave` events, respectively, to trigger scrolling when the mouse is over the area and stop scrolling when it leaves.

```tsx
import Absolute from "@components/Layout/Absolute/Absolute"
import { gridInteractionState } from "../../../../src/store/gridInteractionStore";
import styles from './TeamRoster.module.css';

interface Props {
    direction: 'up' | 'down';
    handleScroll: (direction: 'up' | 'down') => void;
    handleScrollStop: () => void;
}

const ScrollArea = (props: Props) => {
    return (
        <Absolute
            mouseover={() => props.handleScroll(props.direction)}
            mouseleave={props.handleScrollStop}
            left="0" right="0" top={`${props.direction === 'up' ? '0' : '85%' }`} bottom={`${props.direction === 'up' ? '85%' : '0' }`}
            class={`${gridInteractionState.draggedRow !== null ? styles.ScrollArea : styles['ScrollArea-Disabled']}`}
        />
    )
}

export default ScrollArea;
```

Next, we add styles for the scroll areas. We define styles for the active scroll area and a disabled version that prevents pointer events.

```css
.ScrollArea {
    z-index: 99999;
}

.ScrollArea-Disabled {
    pointer-events: none;
}
```

### Integrating ScrollArea into TeamRoster

Finally, we update the `TeamRoster` component to include the scroll areas. We create a reference for the `Scroll` component and implement the `handleScroll` and `handleScrollStop` functions. When the player hovers over a scroll area while dragging, an interval is set to scroll up or down every 300ms. This interval is cleared when the mouse leaves the area. Note that this behavior only triggers when a row is being dragged.

```tsx
const TeamRoster: Component = () => {
    const sizeExpression = "{{GridData.gridItems[0].sizeX}} === 1";
    let scrollRef!: ScrollComponentRef;
    let scrollInterval: number;

    const handleScroll = (direction: 'up' | 'down') => {
        const scrollFn = direction === 'up' ? scrollRef.scrollUp : scrollRef.scrollDown;
        scrollInterval = setInterval(scrollFn, 300);
    }

    const handleScrollStop = () => {
        clearInterval(scrollInterval);
    }

    return (
        <Layout class={styles.TeamRoster}>

            <TableHeader sizeExpression={sizeExpression} />
=           <Scroll ref={scrollRef} class={styles.ScrollContainer}>
                <TableRow sizeExpression={sizeExpression} />
            </Scroll>

            <ScrollArea direction="up" handleScroll={handleScroll} handleScrollStop={handleScrollStop}  />
            <ScrollArea direction="down" handleScroll={handleScroll} handleScrollStop={handleScrollStop}  />

            <Portal>
                {gridInteractionState.draggedRow}
            </Portal>
        </Layout>
    )
}
```

The logic is straightforward: when the player hovers over the scrollable area, we set an interval to call the appropriate scroll function every 300ms. Once the mouse leaves the area, we clear the interval. This behavior only activates if a row is currently being dragged (due to the `pointer-events: none` style on the `ScrollArea-Disabled` class).

## Conclusion

Our Manager UI now features a responsive Team Roster screen that can be resized, filtered, and rearranged. In addition to displaying and sorting the team data, it supports row drag-and-drop with automatic scrolling.

Stay tuned for the next parts of the series, where we add more UI screens!

## On this page
