# Manager UI (part 1): Creating a draggable grid in Gameface

> 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/dnd-grid/

## Manager UI (part 1): Creating a draggable grid in Gameface

ui tutorials

3/7/2025

Martin Bozhilov

1. Prerequisites
2. Overview
3. Source location
4. Project setup
5. Grid component
   1. Setting grid model
   2. Creating a store to hold the grid state
   3. Populating the grid with cells
   4. Displaying grid items on the grid
   5. Dragging grid items
   6. Dropcell component
   7. Swapping grid items
   8. Resizing grid items
6. Conclusion
7. TypeScript types
   1. Model types setup

In this tutorial series we will create a Football simulator game. The game will allow you to take control of a team and be able to rearrange the players, set the tactics, see statistics and more. The base of the game will be a grid where the player will be able to rearrange the game screens and resize them.

We’ve found other manager games having a lot of information in their UI that doesn’t have good accessibility. Using Coherent Gameface we can show you that you are able to have a modular UI that is easy to change and rearrange, mitigating one of the main issues many games of this type have.

## Prerequisites

In this tutorial, we will use the following technologies:

- [Gameface UI](https://gameface-ui.coherent-labs.com/) A set of UI components for rapid UI game development and prototyping.
- [Solid JS](https://docs.solidjs.com/).
- [TypeScript](https://www.typescriptlang.org/).

## Overview

We will create a draggable grid component that will allow us to rearrange the game screens.

The grid will have the following features:

- Drag and drop grid items
- Swap grid items
- Resize grid items
- Load and save grid state (item positions and sizes)

## Source location

Once the whole UI is completed, you will be able to find the complete sample source within the `${Gameface package}/Samples/uiresources/UITutorials/ManagerUI` directory.

## Project setup

To initialize our project, we will follow the guide in the [`Gameface UI` documentation ](https://gameface-ui.coherent-labs.com/getting-started/how-to-use/). Since `Gameface UI` uses `SolidJS` and `TypeScript`, they will come bundled with the project.

Once we have our project set up, we can start creating our UI in the `HUD` component.

## Grid component

The grid component will be the core interaction component of the UI. We will begin by creating a `Grid.tsx` and `Grid.module.css` files in the `custom-components` directory.

```tsx
import { Component } from "solid-js";
import styles from './Grid.module.css';

const Grid: Component = () => {
    return (
        <div class={styles.Grid}></div>
    )
}
```

And import it in the `Hud.tsx` file.

```tsx
import styles from './Hud.module.css';
import Layout from '@components/Layout/Layout/Layout';
import Grid from '@custom-components/Grid/Grid';
import Row from '@components/Layout/Row/Row';
import { Column11, Column1 } from '@components/Layout/Column/Column';

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

export default Hud;
```

The `Layout`, `Row`, and `Column` components are part of the `Gameface UI` library and are used to setup a layout without the need of any CSS.

### Setting grid model

Before adding any logic to our grid, we need to define the state of the grid. We are going to utilize a `model` object to mock game data. Our model will contain a `gridItems` array containing objects with the following properties:

- `id` - a unique identifier for the grid item
- `name` - the name of the grid item
- `x` - the x position of the grid item
- `y` - the y position of the grid item
- `col` - the starting column of the grid item
- `row` - the starting row of the grid item
- `sizeX` - the width of the grid item
- `sizeY` - the height of the grid item
- `minSizeX` - the minimum width of the grid item
- `minSizeY` - the minimum height of the grid item
- `maxSizeX` - the maximum width of the grid item
- `maxSizeY` - the maximum height of the grid item
- `active` - a boolean indicating if the grid item is active and should be displayed

```js
const GridDataModel = {
    gridItems: [
        {
            id: 1,
            name: "Team Roster",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 1,
            sizeY: 1,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: true,
        },
        {
            id: 2,
            name: "Match Tactics",
            x: 0,
            y: 0,
            col: 1,
            row: 1,
            sizeX: 2,
            sizeY: 2,
            minSizeX: 2,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: true,
        },
        {
            id: 3,
            name: "Team Settings",
            x: 0,
            y: 0,
            col: 2,
            row: 0,
            sizeX: 1,
            sizeY: 1,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: true,
        },
        {
            id: 4,
            name: "Player Stats",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 1,
            sizeY: 2,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
        {
            id: 5,
            name: "Match Calendar",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 1,
            sizeY: 2,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
        {
            id: 6,
            name: "Team Morale",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 1,
            sizeY: 2,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
        {
            id: 7,
            name: "Financials",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 2,
            sizeY: 1,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
        {
            id: 8,
            name: "Transfer Market",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 3,
            sizeY: 2,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
        {
            id: 9,
            name: "Match Stats",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 1,
            sizeY: 3,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
        {
            id: 10,
            name: "Team News",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 2,
            sizeY: 3,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
        {
            id: 11,
            name: "Scouting",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 3,
            sizeY: 1,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
        {
            id: 12,
            name: "Manager Stats",
            x: 0,
            y: 0,
            col: 0,
            row: 0,
            sizeX: 2,
            sizeY: 2,
            minSizeX: 1,
            minSizeY: 1,
            maxSizeX: 3,
            maxSizeY: 3,
            active: false,
        },
    ];
}

export default GridDataModel;
```

Storing the grid’s information in a `model` will allow us to preserve the state of the grid. In a real world scenario where the model is not mocked this will allow you to save the player’s ordering of the grid.

Next up, we need to create the model in the `engine.whenReady` event. We will create an `index.js` file in the `models` directory where we are going to initialize all of our models.

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

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

After this in the `index.tsx` in the hud folder we need to import `cohtml.js` (make sure to include it in your project) and the models. We also need to make sure to wrap the `render` function in the `engine.whenReady` event to make sure all our models are loaded before we start rendering the UI.

```tsx
import { render } from 'solid-js/web';
import './index.css';
import Hud from './Hud';
import '../../cohtml.js';
import '../../models/'

const root = document.getElementById('root');

engine.whenReady.then(() => {
    render(() => <Hud />, root!);
});
```

### Creating a store to hold the grid state

To manage the grid state, we will create a [`SolidJS` store ](https://docs.solidjs.com/concepts/stores)that will hold the grid items array and an additional `itemRefs` Map object that will hold a reference to the html element of each grid item.

Let’s initialize our state by create a `GridStore.ts` file in the `stores` directory.

```tsx
import { createStore, produce } from "solid-js/store";
import type { gridState, Item, Position } from "../types/types";
import styles from '@custom-components/Grid/Grid.module.css'

const MAXROWS = 3;
const MAXCOLS = 5;

const [gridState, setGridState] = createStore<gridState>({
    itemRefs: new Map<number, HTMLElement>(),
    items: []
});
```

Initially, we will have an empty array of items and an empty `Map` object. Also, we defined the `MAXROWS` and `MAXCOLS` constants that will be used to limit the grid size.

Now in the `Hud.tsx` we need to populate our store with the data from the `GridData` model.

```tsx
import { setGridState } from '../../store/gridStore';

setGridState('items', GridData.gridItems)

const Hud = () => {
```

With that out of the way, we now can start setting up the logic of the grid component.

*You can refer to the last section for the typescript types*

### Populating the grid with cells

To create the grid, we will use a 2D array of `GridCell` objects. Each cell will have a reference to the html element and a property `occupiedBy` that will hold the id of the grid item that occupies the cell. We will be using the html element of the cell to get their DOM `top` and `left` position and assign them to the grid items.

Let’s define the cells in the `gridStore.ts` file.

```tsx
const cells = initGridCells(MAXROWS, MAXCOLS)
```

We will create a helper function `initGridCells` that will initialize the 2D array of cells.

```tsx
import { GridCell } from "../types/types";

export const initGridCells = (maxRows: number, maxCols: number) => {
    const cells: GridCell[][] = [];

    for (let row = 0; row < maxRows; row++) {
      const rowCells: GridCell[] = []
      for (let col = 0; col < maxCols; col++) {
          rowCells.push({ occupiedBy: undefined, element: undefined });
      }
      cells.push(rowCells);
    }

    return cells;
}
```

Now, we can import the cells `2D array` in the `Grid` component and render all the cells.

```tsx
import { Component, onMount, onCleanup, For, createMemo } from "solid-js";
import styles from './Grid.module.css'
import { Item, GridCell, Position } from "../../../types/types";
import { gridState, removeItem, setGridState, isCellBlockValid, clearCell, occupyCell, MAXCOLS, MAXROWS, cells, updateModel } from "../../store/gridStore";

const Grid: Component = () => {
    let gridRef!: HTMLDivElement;

    const initCell = (cell: GridCell) => {
        return (
            <div
                ref={el => cell.element = el}
                class={styles.Cell}>
            </div>
        )
    }

    return (
        <div ref={gridRef} class={styles.Grid} >
            {cells.flat().map(cell => initCell(cell))}
        </div>
    );
};

export default Grid;
```

Here we loop through all items in the `cells` array and call the helper function `initCell` which will render a div element for each cell and assign the ref to the `element` property.

Let’s add some styles to visualize the grid.

```css
.Grid {
    width: 100%;
    height: 100%;
    display: flex;
    padding: 1%;
    flex-wrap: wrap;
    position: relative;
}

.Cell {
    width: 18%;
    height: 30%;
    margin: 1%;
    border: 1px solid white; /* Add a border to visualize the grid cells */
}
```

The end result should look like this:

### Displaying grid items on the grid

The next step is to populate the grid with items. Each item will consist of:

- A wrapper div element that will be placed absolutely and will have the top and left position set to the item’s `y` and `x` properties.
- A predefined size class that will set the width and height of the item.
- A resize handle that will allow the user to resize the item.
- A close Icon that will allow the user to remove the item from the grid.

Let’s begin by defining the size and icon styles

```css
.CellItem {
    background-color: #004b8c; /* placeholder color for visualization */
    position: absolute;
    transition: opacity 0.5s ease-in-out, left 0.25s ease-in-out, top 0.25s ease-in-out;
}

.Active {
    opacity: 1;
}

.Inactive {
    opacity: 0;
    pointer-events: none;
}

.CellItem-drag {
    opacity: 0;
    border: 10px solid white;
    border-left-color: transparent;
    border-top-color: transparent;
    position: absolute;
    right: 3px;
    bottom: 3px;
    transition: opacity 0.2s ease-in-out;
}

.CellItem-close {
    opacity: 0;
    position: absolute;
    right: 3px;
    top: 3px;
    padding: 0.25vmax 0.5vmax;
    cursor: pointer;
    color: white;
    font-weight: bold;
    transition: opacity 0.2s ease-in-out;
}

.CloseIcon {
    transform: scaleX(1.3);
}

.CellItem-drag:hover,
.CellItem-close:hover {
    opacity: 1;
}

.Dragging {
    opacity: 0.8;
    z-index: 999999;
    box-shadow: 0 2px 6px 1px rgba(0,0,0,0.5);
    transition: none;
}

.Item-1x1 {
    width: 18%;
    height: 30%;
}

.Item-1x2 {
    width: 18%;
    height: 63.5%;
}

.Item-1x3 {
    width: 18%;
    height: 97%;
}

.Item-2x1 {
    width: 38%;
    height: 30%;
}

.Item-2x2 {
    width: 38%;
    height: 63.5%;
}

.Item-2x3 {
    width: 38%;
    height: 97%;
}

.Item-3x1 {
    width: 58%;
    height: 30%;
}

.Item-3x2 {
    width: 58%;
    height: 63.5%;
}

.Item-3x3 {
    width: 58%;
    height: 97%;
}
```

We can now loop through the items in the `gridState` store and render the element for each item. We are going to use the `Active` class to show only the items marked as active.

```tsx
return (
    <div ref={gridRef} class={styles.Grid} >
        {cells.flat().map(cell => initCell(cell))}

        <For each={gridState.items} >
            {(item) => {
                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}`}>
                        <div class={styles['CellItem-drag']} ></div>
                        <div class={styles['CellItem-close']}>
                            <div class={styles.CloseIcon}>X</div>
                        </div>
                    </div>
                )
            }}
        </For>
    </div>
);
```

One final thing to do is to add an `initItems` function which will:

- set the `x` and `y` properties of the items based on the cell position (`row` and `col`) they are occupying in the grid.
- Mark the cell the item is placed at as occupied.

```tsx
const initItems = () => {
    setGridState('items', produce((items) => {
        items.forEach((item) => {
            item.x = cells[item.row][item.col].element?.offsetLeft!;
            item.y = cells[item.row][item.col].element?.offsetTop!;
        })
    }));

    gridState.items.forEach((item) => {
        if (item.active) {
            occupyCell(item.row, item.col, item)
        }
    })
}

onMount(() => {
    delayExecution(() => {
        const firstCellElement = cells[0][0].element;
        if (firstCellElement) {
            initItems();
        }
    })
});
```

We do this in the `onMount` lifecycle event and wrap all the logic with the `delayExecution` helper function to make sure that the model has loaded. The `delayExecution` function will allow us to wait 3 frames before doing anything with the model’s data.

```ts
export const delayExecution = (callback: () => void, delay: number = 3) => {
    if (delay === 0) {
        callback();
        return;
    }

    requestAnimationFrame(() => {
        delayExecution(callback, delay - 1);
    });
}
```

Now let’s implement the `occupyCell` function in the `gridStore.ts` file.

```tsx
const occupyCell = (newRow: number, newCol: number, item: Item) => {
    for (let row = 0; row < item.sizeY; row++) {
        for (let col = 0; col < item.sizeX; col++) {
            const cell = cells[newRow + row][newCol + col];
            cell.occupiedBy = item.id;
        }
    }
}
```

The `occupyCell` function will loop through the cells that the item is occupying and set the `occupiedBy` property to the item’s id.

Now if you save the changes you should see your grid populated with items.

### Dragging grid items

With our grid cells in place, we need to let users click and drag an item around. The core idea is to track:

1. Which item is being dragged - `dragging`
2. Whether we are currently dragging an item - `draggedItem`
3. The initial position of the mouse when the drag starts to calculate the offset from the top left corner of the item - `dropPosition`

First we need to get the width and height of the cells as well as the gap between them. We will use these values to calculate the current row and col of the dragged item.

We’ll create a separate store that will contain the drag state of the grid, and three event handlers— `handleMouseDown`, `handleMouseMove`, and `handleMouseUp` to track the mouse from press, through movement, to release.

Additionally, we will define helper variables to store the initial mouse position and the offset from the top left corner of the item.

Finally, we will add a `DropCell` component which will be used to visualize the drop position of the item while dragging.

Let’s start by defining the helper variables.

```tsx
const DRAG_THRESHOLD: number = 5;
let startLeft: number = 0,
    startTop: number = 0,
    startMouseX: number = 0,
    startMouseY: number = 0,
    offsetX: number = 0,
    offsetY: number = 0;

const Grid: Component = () => {
    let cellWidth: number;
    let cellHeight: number;
    let gapX: number;
    let gapY: number;
```

Now let’s implement the interactions store:

```ts
import { createMutable, modifyMutable, produce } from "solid-js/store";
import { gridInteractionType, Item, Position } from "src/types/types";

export const gridInteractionState = createMutable<gridInteractionType>({
    dragging: false,
    draggedItem: null as Item | null,
    dropPosition: null as Position | null,
    shouldDrag: true,
});
```

Notice how for this store we are using [Solid’s createMutable ](https://docs.solidjs.com/reference/store-utilities/create-mutable)function. The reason we do this is to ensure that we’ll trigger a state update even if objects such as `dropPosition` change. Because if done with a normal `createStore`, updating the properties of the object won’t trigger a state update. Another benefit that comes from this is that we don’t need a setter function with `createMutable` and we can update properties like we normally do.

With that out of the way, the last thing to do is to get the cells width and height and the gap between them in the `onMount` event. As well as add the event handlers.

```tsx
onMount(() => {
    delayExecution(() => {
        const firstCellElement = cells[0][0].element;
        if (firstCellElement) {
            cellWidth = firstCellElement.clientWidth;
            cellHeight = firstCellElement.clientHeight;
            gapX = firstCellElement.offsetLeft;
            gapY = firstCellElement.offsetTop;
            initItems();
        }
    })

    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("mouseup", handleMouseUp);
});
```

And remove the event handlers in the `onCleanup` event.

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

Now let’s define the event handlers.

#### Mouse down event

On the `mousedown` event we are going to check if the user clicked on an item and if so we are going to set the `dragging` state to `true` and store the initial mouse position and the offset from the top left corner of the item.

This way we will keep the item’s position relative to where the user clicked.

```tsx
const startDragging = (item: Item) => {
    startLeft = item.x;
    startTop = item.y;
    offsetX = startMouseX - startLeft;
    offsetY = startMouseY - startTop;
    gridInteractionState.dragging = true;
}

// Start dragging when mousedown occurs on an item
const handleMouseDown = (e: MouseEvent, item: Item) => {
    if (!gridRef || !gridInteractionState.shouldDrag) return;

    gridInteractionState.draggedItem = item
    const currentItemElement = gridState.itemRefs.get(item.id)

    // Store the initial mouse position
    startMouseX = e.clientX;
    startMouseY = e.clientY;

    const clickedElement = e.target as HTMLElement;
    if (clickedElement.closest(`.${styles.CellItem}`)) startDragging(item)

    e.preventDefault();
};
```

One thing to note is the flag `shouldDrag` we defined in our store earlier. This flag enables us to have control from the outside over whether an interaction with the grid should trigger. This will be useful to have in the future if we want to have interactions inside the components of the grid items.

#### Mouse move event

On the `mousemove` event we are going to:

- Calculate the new position of the item based on the mouse position and the offset from the top left corner of the item.
- Get the `row` and `col` the item is currently hovering on.
- Check if the new `row` and `col` are valid and if not we are going to return the item to its previous position.

Additionally we will attach a `dragging` class to visualize the interaction and set a safety check and check if the mouse has moved more than the `DRAG_THRESHOLD`. This is done to prevent accidental drags if the user holds their mouse and drags a little.

```tsx
// Update drop target based on mouse position
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) {
        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()) {
            gridInteractionState.dropPosition = { col: currentItemCol, row: currentItemRow } // fallback
        }
    }
};
```

To achieve the following we will need a couple of helper functions.

- `getGridPosition` - calculates the `row` and `col` based on the mouse position and the grid cells.
- `changeItemPosition` - continuously updates the item’s `x` and `y` based on the current mouse position.
- `memoizedCellValidation` - checks if the new position of the item is valid. It triggers only when the row or col changes decreasing the executions of the function and improving performance.

```tsx
function getGridPosition(itemLeft: number, itemTop: number, maxCol: number, maxRow: number) {
    const adjustedColWidth = cellWidth + gapX;
    const adjustedRowHeight = cellHeight + gapY;

    return {
        col: clamp(Math.floor((itemLeft - (gapX / 2)) / adjustedColWidth), maxCol, 0),
        row: clamp(Math.floor((itemTop - (gapY / 2)) / adjustedRowHeight), maxRow, 0)
    };
}
```

As you can notice, we are using a `clamp` function to limit the row and col values between the max grid size or 0. This will ensure that the item will not go out of bounds. Let’s define the `clamp` function in our ‘utils’ folder.

```tsx
export const clamp = (value: number, maxValue: number, minValue: number) => {
    return Math.max(minValue, Math.min(value, maxValue))
}
```

Now to update the item’s position:

```tsx
const changeItemPosition = (item: Item, mouseX: number, mouseY: number) => {
    if (item) {
        // Compute the new position while keeping the original offset
        const deltaX = mouseX - startMouseX;
        const deltaY = mouseY - startMouseY;

        // New position should maintain the original top-left corner offset
        const newLeft = startLeft + deltaX;
        const newTop = startTop + deltaY;

        setGridState('items', currItem => currItem.id === item.id, {
            x: newLeft,
            y: newTop,
        });
    }
}
```

And finally the `memoizedCellValidation` function. For this one we are going to utilize the [createMemo ](https://docs.solidjs.com/reference/basic-reactivity/create-memo#creatememo)function from `Solid JS` to wrap the `isCellBlockValid` function which will be responsible for veryfying if the cell we are trying to place an item in is valid by checking whether the cells `occupiedBy` field is true and different from the passed item’s id.

Let’s first define the `isCellBlockValid` function in the `gridStore.ts` file.

```tsx
const isCellBlockValid = (newRow: number, newCol: number, item: Item, sizeX: number, sizeY: number) => {
    for (let row = 0; row < sizeY; row++) {
        for (let col = 0; col < sizeX; col++) {
            const resultRow = newRow + row;
            const resultCol = newCol + col;
            if (resultRow >= MAXROWS || resultCol >= MAXCOLS) return false

            const cell = cells[resultRow][resultCol];
            if (cell.occupiedBy && cell.occupiedBy !== item.id ) {
                return false;
            }
        }
    }

    return true
}
```

And since we don’t wish to run ths `2D array` loop on every mouse move event when we haven’t even moved the item out of its own cell, we are going to `memoize` the function and make it run only if the cell (drop position) has changed.

```tsx
const memoizedCellValidation = createMemo(() => {
    const item = draggedItem();
    const position = dropPosition();

    if(!item || !position) return false

    return isCellBlockValid(position.row, position.col, item, item.sizeX, item.sizeY)
})
```

#### Mouse up event

What’s left from the dragging logic is to handle the `mouseup` event. After we’ve verified that the new position of the item we are dragging is valid, we are going to:

- Update the item’s `row` and `col` properties and mark the new cells as occupied by the item.
- Remove the `dragging` class from the item.
- Assign the `offeSetLeft` and `offSetTop` properties to the item’s `x` and `y` properties (in order to make the item appear as being ‘slotted’ into its new position).
- Update our `GridData` model with the new item’s properties.
- Reset all drag states.

```tsx
const dropitem = () => {
    const currentItem = gridInteractionState.draggedItem;

    if (!gridInteractionState.dropPosition || !currentItem) return

    gridState.itemRefs.get(currentItem!.id)!.classList.remove(styles.Dragging)
    resetItemElement(currentItem)

    const newCol = gridInteractionState.dropPosition!.col;
    const newRow = gridInteractionState.dropPosition!.row;
    const newX = cells[newRow][newCol].element?.offsetLeft!;
    const newY = cells[newRow][newCol].element?.offsetTop!;

    setGridState('items', item => item.id === currentItem.id, {
        x: newX,
        y: newY,
        col: newCol,
        row: newRow,
    });

    clearCell(currentItem)
    occupyCell(newRow, newCol, currentItem)
    updateModel(GridData);
}

// On mouse up, update the item's position if there is a valid drop target
const handleMouseUp = () => {
    dropitem();
    resetInteractionState()
};
```

```ts
export const resetInteractionState = () => {
    modifyMutable(
        gridInteractionState,
        produce((gridInteractionState) => {
            gridInteractionState.dragging = false;
            gridInteractionState.draggedItem = null;
            gridInteractionState.dropPosition = null;
        })
    )
}
```

The `clearCell` function will remove the `occupiedBy` property from the cells the item is currently occupying.

```tsx
// Frees cell or cells spot
const clearCell = (item: Item) => {
    for (let row = 0; row < MAXROWS; row++) {
        for (let col = 0; col < MAXCOLS; col++) {
            const cell = cells[row][col];
            if (cell.occupiedBy === item.id) cell.occupiedBy = undefined;
        }
    }
}
```

And of course we need to update our model. We will define a helper function for this - `updateModel`

```tsx
export const updateModel = (model: object) => {
    engine.updateWholeModel(model);
    engine.synchronizeModels();
}
```

Now if you save the changes you should be able to drag the items around the grid.

### Dropcell component

To help better visualize the grid’s interactions we are going to add a `DropCell` component which will be used to visualize the drop position of the item while dragging it.

```tsx
import { Component, Show } from "solid-js";
import {cells} from '../../store/gridStore';
import styles from './Grid.module.css';
import { gridInteractionState } from "../../store/gridInteractionStore";

const DropCell: Component = () => {

    return (
        <div class={styles.DropCellContainer}>
            <Show when={gridInteractionState.dropPosition} keyed>
                {(position) => {
                    const { col, row } = position;
                    const cellToShow = cells[row][col]
                    const currentItem = gridInteractionState.draggedItem;
                    return (<div
                        style={{ top: `${cellToShow?.element?.offsetTop}px`, left: `${cellToShow?.element?.offsetLeft}px` }}
                        class={`${styles[`Item-${currentItem?.sizeX}x${currentItem?.sizeY}`]} ${styles.DropCell}`}>
                    </div>)
                }}
            </Show>
        </div>
    )
}

export default DropCell
```

Add some styles

```css
.DropCell {
    position: absolute;
    top: 0;
    left: 0;
    background-color: #d9d9d979;
    pointer-events: none;
}

.DropCellContainer {
    position: absolute;
    width: 100%;
    height: 100%;
}
```

The `DropCell` component will use the `dropPosition` and `draggedItem` states from our `gridInteractionStore` and will render a div element with the same size as the dragged item and position it on the cell the item is currently hovering on. If the position is invalid the `DropCell` will show on the initial position of the item. And since we have access to the current item we can use its size to set the size of the `DropCell`.

To make it all work we are utilizng the [Show ](https://docs.solidjs.com/reference/components/show)SolidJS component that lets us conditionally render components. In our case `Show` will render the `DropCell` only if the `dropPosition` state is not null.

Now let’s import the `DropCell` component in the `Grid.tsx` file and render it.

```tsx
import DropCell from "./DropCell";

return (
    <div ref={gridRef} class={styles.Grid} >
        {cells.flat().map(cell => initCell(cell))}

        <DropCell />

        <For each={gridState.items} >
```


### Swapping grid items

To make the grid’s interactions more intuitive we are going to add the ability to swap items. When the user drags an item over another item we are going to swap their positions, if it’s possible.

Currently if two items on the grid overlap, the dragged item will fallback to its starting position. We are going to extend the `handleMouseMove` function to swap their positions if there is an overlap by calling a `handleOverlap` function.

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

We are going to handle the whole swapping interaction in our `handleOvelrap` function. The process will be as follows:

- Find which item is being overlapped by the dragged item.
- Calculate the new positions of both items based on the direction of the overlap.
- Check if the new positions are valid.
- If the swap is valid, execute the swap, update the item’s state, update the cell’s `occupiedBy` property to match the new positions of the items and set a cooldown flag to avoid rapid swaps on every mouse move.

Add a `isSwapCooldown` state to the store avoid rapid swaps

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

```tsx
const handleOverlap = (row: number, col: number, currentItem: Item) => {
    // Avoids rapid swap if items still overlap
    if (gridInteractionState.isSwapCooldown) return

    const overlappedItem = gridState.items.find(i => i.id === cells[row][col].occupiedBy)
    // Early exit if trying to overlap with itself
    if (!overlappedItem || overlappedItem === currentItem) return

    // Calculate new positions regardless of direction
    let newCurrentRow = currentItem.row;
    let newCurrentCol = currentItem.col;
    let newOverlappedRow = overlappedItem.row;
    let newOverlappedCol = overlappedItem.col;

    // Horizontal movement logic
    if (currentItem.col !== overlappedItem.col) {
        if (currentItem.col < overlappedItem.col) {
            // Current item is coming from left
            const sizeDifferenceX = overlappedItem.sizeX - currentItem.sizeX;
            newOverlappedCol = currentItem.col;
            newCurrentCol = overlappedItem.col + sizeDifferenceX;
        } else {
            // Current item is coming from right
            const sizeDifferenceX = currentItem.sizeX - overlappedItem.sizeX;
            newOverlappedCol = currentItem.col + sizeDifferenceX;
            newCurrentCol = overlappedItem.col;
        }
    }

    // Vertical movement logic
    if (currentItem.row !== overlappedItem.row) {
        if (currentItem.row < overlappedItem.row) {
            // Current item is coming from top
            const sizeDifferenceY = overlappedItem.sizeY - currentItem.sizeY;
            newOverlappedRow = currentItem.row;
            newCurrentRow = overlappedItem.row + sizeDifferenceY;
        } else {
            // Current item is coming from bottom
            const sizeDifferenceY = currentItem.sizeY - overlappedItem.sizeY;
            newOverlappedRow = currentItem.row + sizeDifferenceY;
            newCurrentRow = overlappedItem.row;
        }
    }

    // Check grid boundaries for both items
    if (!isWithinGrid(newOverlappedRow, newOverlappedCol, overlappedItem) ||
        !isWithinGrid(newCurrentRow, newCurrentCol, currentItem)) {
        return;
    }

    // Validate swap for both items in their new positions
    if (!isSwapValid(newOverlappedRow, newOverlappedCol, overlappedItem, currentItem) ||
        !isSwapValid(newCurrentRow, newCurrentCol, currentItem, overlappedItem)) {
        return;
    }

    // Execute the swap
    const hasSwapped = swapItemPositions(
        currentItem, overlappedItem,
        newCurrentRow, newCurrentCol,
        newOverlappedRow, newOverlappedCol
    );

    if (hasSwapped) {
        clearCell(currentItem);
        clearCell(overlappedItem);
        occupyCell(currentItem.row, currentItem.col, currentItem);
        occupyCell(overlappedItem.row, overlappedItem.col, overlappedItem);
        gridInteractionState.isSwapCooldown = true
        setTimeout(() => gridInteractionState.isSwapCooldown = false, 500);
    }
}
```

In addition, we need to implement three helper functions to make the swap possible.

- `isWithinGrid` - checks if the new position of the item is within the grid boundaries.
- `isSwapValid` - checks if the swap is valid by verifying if the new position of the item is not occupied by another item.
- `swapItemPositions` - swaps the positions of the two items by updating their state in the `store`.

```tsx
const isWithinGrid = (row: number, col: number, item: Item) => {
    return row >= 0 && (row + item.sizeY - 1) <= MAXROWS && col >= 0 && (col + item.sizeX - 1) <= MAXCOLS;
}
```

In the `isSwapValid` function we are going to loop through all the grid cells and check if the new position of the item is not occupied by another item. Excluding the overlapped and the dragged items.

```tsx
const isSwapValid = (newRow: number, newCol: number, item: Item, overlappedItem: Item) => {
    for (let row = 0; row < item.sizeY; row++) {
        for (let col = 0; col < item.sizeX; col++) {

            const resultRow = newRow + row;
            const resultCol = newCol + col;
            if (resultRow >= MAXROWS || resultCol >= MAXCOLS) return false

            const cell = cells[resultRow][resultCol];
            if (cell.occupiedBy && cell.occupiedBy !== item.id && cell.occupiedBy !== overlappedItem.id) {
                return false;
            }
        }
    }

    return true
}
```

Finally, in the `swapItemPositions` function we are going to update the items’ state in the `store` and return a boolean indicating if the swap was successful. The function will accept all the new calculated row and cols for both items. We will move the common logic for state updating into its own separate function `setGridItemState` to reduce code repetitiveness

```tsx
const swapItemPositions = (currentItem: Item, overlappedItem: Item, newCurrentRow: number, newCurrentCol: number, newOverlappedRow: number, newOverlappedCol: number) => {
    // Set new locations for overlapped item
    setGridState('items',
        item => item.id === overlappedItem.id,
        produce(setGridItemState(newOverlappedRow, newOverlappedCol))
    );

    // Set new locations for current item
    setGridState('items',
        item => item.id === currentItem.id,
        produce(setGridItemState(newCurrentRow, newCurrentCol))
    );

    return true;
}

const setGridItemState = (newRow: number, newCol: number) => {
    return (item: Item) => {
        item.row = newRow;
        item.col = newCol;
        item.x = cells[item.row][item.col].element!.offsetLeft;
        item.y = cells[item.row][item.col].element!.offsetTop;
    }
}
```

Now if you save the changes you should be able to swap the items on the grid.

### Resizing grid items

The final grid functionality we are going to implement will be the ability to resize the grid items.

The process will be similar to the dragging logic. We are going to create a `resizing` state in our `interaction store` to track if the item is being resized and a couple of helper variables to store:

- initial width and height of the item - `startWidth`, `startHeight`
- the new size of the item - `newSizeX`, `newSizeY`

```tsx
let startLeft: number = 0,
    startTop: number = 0,
    startMouseX: number = 0,
    startMouseY: number = 0,
    startWidth: number = 0,
    startHeight: number = 0,
    newSizeX: number = 0,
    newSizeY: number = 0,
    offsetX: number = 0,
    offsetY: number = 0;
```

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

Next, we are going to extend the `handleMouseDown` function to check whether the user is dragging or resizing. We will check if the clicked element is the resize handle and set the `resizing` state to `true`.

Additionally, we are going to store the `rect` object of the grid element and assign it’s `left` and `top` properties as X and Y offset. We do this to ensure that the coordinates of the mouse are relative to the grid element.

```tsx
const handleMouseDown = (e: MouseEvent, item: Item) => {
    if (!gridRef || !gridInteractionState.shouldDrag) return;

    gridInteractionState.draggedItem = item
    const currentItemElement = gridState.itemRefs.get(item.id)

    // Store the initial mouse position
    startMouseX = e.clientX;
    startMouseY = e.clientY;

    const clickedElement = e.target as HTMLElement;

    if (clickedElement.closest(`.${styles.CellItem}`)) startDragging(item)

    if (clickedElement.closest(`.${styles['CellItem-drag']}`)) startResizing(currentItemElement);
    else if (clickedElement.closest(`.${styles.CellItem}`)) startDragging(item)

    e.preventDefault();
};
```

```tsx
const startDragging = (item: Item) => {
    startLeft = item.x;
    startTop = item.y;
    offsetX = startMouseX - startLeft;
    offsetY = startMouseY - startTop;
    gridInteractionState.dragging = true;
}
```

Next, we are also going to extend the `handleMouseMove` function to handle resizing the item. We are once again going to get the new position of the mouse and return the relevant `row` and `col` of the grid. And then we are going to call the `changeSize` function which will calculate the new size of the item based on the mouse position.

```tsx
const handleMouseMove = (e:MouseEvent) => {
    // Dragging logic

    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 }
    }
}

const changeSize = (item: Item, mouseX: number, mouseY: number, col: number, row: number) => {
    const itemElement = gridState.itemRefs.get(item.id);

    if (item && itemElement) {

        const newWidth = startWidth + (mouseX - startMouseX);
        const newHeight = startHeight + (mouseY - startMouseY);

        itemElement.style.width = `${newWidth}px`;
        itemElement.style.height = `${newHeight}px`;

        newSizeX = clamp((col - item.col) + 1, item.maxSizeX, item.minSizeX);
        newSizeY = clamp((row - item.row) + 1, item.maxSizeY, item.minSizeY)

        if (isCellBlockValid(item.row, item.col, item, newSizeX, newSizeY)) {
            setGridState('items', (currentItem) => currentItem.id === item.id, {
                sizeX: newSizeX,
                sizeY: newSizeY
            })
        }
    }
}
```

In the `changeSize` function on every mouse move we are updating the width and height of the item’s html element so the user can see the resize in real-time. Also, since we want our items to have minimum and maximum size we are using the `clamp` function to limit the new size of the item.

Finally, we will check if the new size of the item is valid and not overlapping with another item by calling the `isCellBlockValid` function. If the new size is valid we are going to update the item’s state.

The last thing to do to complete the resize functionality is to reset the `resizing` state and the html element’s width and height styles we changed during the dragging process.

```tsx
const dropitem = () => {
    const currentItem = gridInteractionState.draggedItem;

    if (!gridInteractionState.dropPosition || !currentItem) return

    gridState.itemRefs.get(currentItem!.id)!.classList.remove(styles.Dragging)
    resetItemElement(currentItem)

    const newCol = gridInteractionState.dropPosition!.col;
    const newRow = gridInteractionState.dropPosition!.row;
    const newX = cells[newRow][newCol].element?.offsetLeft!;
    const newY = cells[newRow][newCol].element?.offsetTop!;

    setGridState('items', item => item.id === currentItem.id, {
        x: newX,
        y: newY,
        col: newCol,
        row: newRow,
    });

    clearCell(currentItem)
    occupyCell(newRow, newCol, currentItem)
    updateModel(GridData);
}

const resetItemElement = (currentItem: Item) => {
    const itemElement = gridState.itemRefs.get(currentItem!.id)!;

    itemElement.classList.remove(styles.Dragging)
    itemElement.style.width = ''
    itemElement.style.height = ''
}
```

And don’t forget to add the `resizing` state for reset in our store’s helper function - `resetInteractionState`

```ts
export const resetInteractionState = () => {
    modifyMutable(
        gridInteractionState,
        produce((gridInteractionState) => {
           gridInteractionState.resizing = false;
            gridInteractionState.dragging = false;
            gridInteractionState.draggedItem = null;
            gridInteractionState.dropPosition = null;
        })
    )
}
```

Now if you save the changes you should be able to resize the items on the grid.

## Conclusion

We have created a grid component with drag and drop functionality. We have implemented the ability to drag, swap, and resize items on the grid.

In the next part of this tutorial series, we will create a side navigation component to add and remove items from the grid. Additionally, we will implement utility components such as a `toast` and `tooltip`.

## TypeScript types

```tsx
export interface Item {
    id: number;
    name: string;
    x: number;
    y: number;
    row: number;
    col: number;
    sizeX: number;
    sizeY: number;
    minSizeX: number;
    minSizeY: number;
    maxSizeX: number;
    maxSizeY: number;
    element?: HTMLElement;
    active: boolean;
}

export interface Position {
  row: number;
  col: number;
}

export interface GridCell {
  element?: HTMLDivElement;
  occupiedBy?: number;
}

export interface gridState {
  itemRefs: Map<number, HTMLElement>
  items: Item[]
}

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

To setup the types for `cohtml.js` you can follow [this guide](https://docs.coherent-labs.com/cpp-gameface/content_development/typescript/#using-typescript-definitions)

### Model types setup

Since the models are created at runtime, we need to define them as global types. We can do this by creating a `global.d.ts` file in the `src` folder, where we are going to define the types for all our models.

```tsx
import { Item } from "./types/types";

declare global {
    let GridData: {gridItems: Item[]};
}

export {};
```

To make `typescript` recognize it as a global type, we need to add the following code in the `tsconfig.json` file.

```json
{
  "compilerOptions": {
    // other options
  },
  "include": ["src", "src/global.d.ts"],
}
```

## On this page
