# Manager UI (part 2): Cross component interactions and utility components (Toast, Tooltip)

> 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/navigation-and-utility/

## Manager UI (part 2): Cross component interactions and utility components (Toast, Tooltip)

ui tutorials

3/8/2025

Martin Bozhilov

1. Side navigation component
   1. Displaying the icons
   2. Adding items to the grid
   3. Displaying a Toast component
   4. Adding tooltip to the icons
2. Removing items from the grid
3. Displaying components in the grid items
4. Conclusion

This is the second tutorial in the Manager UI series. In the last tutorial, we created the layout of the sample and a grid component with drag and drop functionality.

In this tutorial, we will add a side navigation component and some utility components like a toast and a tooltip. The side navigation will allow us to add and remove items from the grid. Additionally, we will add a `toast` component which we will use to display an error message to the user if the grid is full and a `tooltip` component which will show a tooltip when hovering over the grid items to tell the user which screen they are hovering on.

## Side navigation component

The navigation component will allow us to add items to the grid. Let’s first build the layout of the component.

### Displaying the icons

To display the icons, we will create a `map` that will hold the icons paths. We will then iterate over the items in the grid and display the icons by getting the icon’s reference in the map with the item’s `ID`.

```tsx
import GameLogo from '@assets/logo.png';
import teamRosterIcon from '@assets/icons/team-roster.png';
import matchTacticsIcon from '@assets/icons/match-tactics.png';
import teamSettingsIcon from '@assets/icons/team-settings.png';
import playerStatsIcon from '@assets/icons/player-stats.png';
import matchCalendarIcon from '@assets/icons/match-calendar.png';
import teamMoraleIcon from '@assets/icons/team-morale.png';
import financialsIcon from '@assets/icons/financials.png';
import transferMarketIcon from '@assets/icons/transfer-market.png';
import matchStatsIcon from '@assets/icons/match-stats.png';
import teamNewsIcon from '@assets/icons/team-news.png';
import scoutingIcon from '@assets/icons/scouting.png';
import managerStats from '@assets/icons/manager-stats.png';
import cancelIcon from '@assets/icons/cancel.png';
import styles from './SideNav.module.css';
import { Component, createSignal, For } from 'solid-js';
import { addItem, gridState } from "../../store/gridStore";
import NavIcon from './NavIcon';
import Toast from "../Util/Toast";
import { Item } from '../../../types/types';
import Block from "@components/Layout/Block/Block";
import Flex from "@components/Layout/Flex/Flex";
import TextBlock from "@components/Basic/TextBlock/TextBlock";
import Image from "@components/Media/Image/Image";

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

    return (
        <Flex direction='column' justify-content='start' align-items='center' class={styles.SideBar}>
            <Block class={styles.Logo}>
                <Image src={GameLogo} class={styles.LogoImage} />
            </Block>
            <Flex direction='column'>
                <For each={gridState.items}>
                    {(item) => <Image class={styles.Icon} src={imageMap.get(item.id)}/>}
                </For>
            </Flex>
        </Flex>
    )
}

export default SideNav
```

Let’s add the `CSS`

```css
.SideBar {
    width: 100%;
    height: 100%;
    border-right: 3px solid #606067;
}

.Logo {
    max-width: 100%;
    margin: 2vmax;
}

.LogoImage {
    width: 5vmax;
    height: 5vmax;
}

.Icon {
    width: 2.5vmax;
    height: 2.5vmax;
    margin-bottom: 1vmax;
    cursor: pointer;
}
```

And Finally, import it in the `HUD.tsx` file and add it in the `Column1` component.

```tsx
import SideNav from '@custom-components/Navigation/SideNav';

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

### Adding items to the grid

To add items to the grid, we will add an `onClick` event to the icons. When an icon is clicked, we will add the item to the grid.

Since we want to also display a tooltip with the item’s name when hovering over the icon, it is a good idea to separate the icon into a separate component.

Let’s create a `NavIcon` component. Our new component will accept the `item`, `imageMap`, and a `click` function as props. The `click` function will be called when the icon is clicked.

```tsx
import { Component, createSignal } from "solid-js";
import styles from './NavIcon.module.css';
import { Item } from "../../../types/types";
import Tooltip from "../Util/Tooltip";
import infoIcon from '@assets/icons/info.png';
import Block from "@components/Layout/Block/Block";
import Flex from "@components/Layout/Flex/Flex";
import TextBlock from "@components/Basic/TextBlock/TextBlock";
import Image from "@components/Media/Image/Image";

type NavIconProps = {
    item: Item,
    imageMap: Map<number, string>,
    click: (item: Item) => void
}

const NavIcon: Component<NavIconProps> = ({item, imageMap, click}) => {
    return (
        <Block class={`${styles.Icon} ${item.active ? styles['Icon-Disabled'] : ''}`} >
            <Image
                class={`${styles['Icon-Image']} ${item.active ? styles['Icon-Image-Disabled'] : ''}`}
                click={() => click(item)}
                src={imageMap.get(item.id)!} />
        </Block>
    )
}

export default NavIcon
```

We can use the `item.active` property to disable the icon if it is already in the grid. Let’s add the styles for our `NavIcon` component.

```css
.Icon {
    width: 2.5vmax;
    height: 2.5vmax;
    margin-bottom: 1vmax;
    position: relative;
    cursor: pointer;
    transition: opacity 0.25s ease-in-out;
}

.Icon-Image {
    max-width: 100%;
    max-height: 100%;
    opacity: 0.8;
}

.Icon-Image:hover {
    opacity: 1;
}

.Icon-Disabled {
    opacity: 0.5;
    cursor: auto;
    pointer-events: none;
}
```

Now, let’s import the `NavIcon` component in the `SideNav.tsx` file and use it to display the icons.

```tsx
<For each={gridState.items}>
    {(item) => <Image class={styles.Icon} src={imageMap.get(item.id)}/>}
</For>
<For each={gridState.items}>
    {(item) => <NavIcon item={item} imageMap={imageMap} click={clickHandler} />}
</For>
```

What’s left is to add the logic for adding an item to the grid. In our `gridStore.ts` file, we will add a new function `addItem` that will handle the logic.

The logic for adding an item is simple. We will create a helper function - `findAvailablePosition` which will loop through all cells and try to find an empty cell and the adjecent cells that can fit the item we are trying to add. If we find a suitable position, we will add the item to the grid and update our `model`. This way the next time the user loads the game, the item will be in the same position. Finally, we will return `true` to indicate a successful addition.

```tsx
function addItem(id: number) {
    let hasAdded = false;
    setGridState('items', item => item.id === id, produce(item => {
        const cellPosition = findAvailablePosition(item, item.sizeX, item.sizeY);

        if (cellPosition) {
            const { row, col } = cellPosition;
            item.row = row;
            item.col = col;
            item.x = cells[row][col].element?.offsetLeft!;
            item.y = cells[row][col].element?.offsetTop!;
            item.active = true;

            occupyCell(row, col, item);

            hasAdded = true;

            updateGridDataModel();
        }
    }))

    return hasAdded
}

const findAvailablePosition = (item: Item, sizeX: number, sizeY: number): Position | undefined => {
    for (let row = 0; row < MAXROWS; row++) {
        for (let col = 0; col < MAXCOLS; col++) {
            if (isCellBlockValid(row, col, item, sizeX, sizeY)) {
                return { row, col }
            }
        }
    }
}
```

The only thing left is to implement the `clickHandler` function in the `sideNav`. This function will call the `addItem` function and display a `toast` message if the grid is full.

### Displaying a Toast component

To display a toast message, we will create a `Toast` component. Our `Toast` will accept

- a `show` prop that will determine if the toast should show or not,
- an optional `duration` prop that will determine how long the toast should be displayed,
- an optional `onHide` function that can be called before the toast hides.

```tsx
import { createEffect, createSignal, ParentComponent, Show } from "solid-js";
import styles from './Toast.module.css';
import { Portal } from "solid-js/web";
import Block from "@components/Layout/Block/Block";

type ToastProps = {
    show: boolean,
    duration?: number,
    onHide?: () => void,
}

const Toast: ParentComponent<ToastProps> = (props) => {
    const [isOpen, setIsOpen] = createSignal(false);

    const displayDuration = props.duration ?? 2000;

    let timer: number | undefined;

    createEffect(() => {
        if (!props.show) return setIsOpen(false);

        setIsOpen(true)

        if (timer) window.clearTimeout(timer);

        timer = window.setTimeout(() => {
            setIsOpen(false);
            props.onHide?.();
        }, displayDuration)
    })

    onCleanup(() => {
        if (timer) clearTimeout(timer);
    });

    return (
        <Portal>
            <Block class={`${styles.Toast} ${isOpen() && styles.Show}`}>{props.children}</Block>
        </Portal>
    )
}

export default Toast;
```

The Toast will have an `isOpen` signal which will help us control the visibility of the toast. Additionally, we will use a `timer` to hide the toast after a certain duration.

Lastly, the Toast will be rendered with the help of the [Portal ](https://docs.solidjs.com/concepts/control-flow/portal#portal)component. This will allow us to render the toast directly as a child of the `body` element.

Let’s add the `CSS` for the `Toast` component.

```css
.Toast {
    padding: 1.25vmax 1.5vmax;
    background-color: #ED1054;
    color: #FFF;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    position: absolute;
    left: 50%;
    opacity: 0;
    transition: transform 0.35s ease-in-out, opacity 0.35s ease-in-out;
    transform: translate(-50%, -100%)
}

.Show {
    opacity: 1;
    transform: translate(-50%, 20%);
}
```

Now, let’s import the `Toast` component in the `SideNav.tsx` file and implement the `clickHandler` function to display items in the grid.

```tsx
const SideNav: Component = () => {
    const [toastMessage, setToastMessage] = createSignal("");
    const [showError, setShowError] = createSignal<boolean>(false);

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

    const clickHandler = (item: Item) => {
        const isAdded = addItem(item.id);
        if (!isAdded) {
            setToastMessage(`Unable to show ${item.name} window`);
            setShowError(false);  // Reset first
            setTimeout(() => setShowError(true), 0);
        } else {
            setShowError(false);
        }
    }

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

Here, we defined a `toastMessage` signal that will hold the message we want to display in the toast. We also defined a `showError` signal that will determine if the toast should be displayed or not.

When an icon is clicked, we call the `clickHandler` function. If the item is successfully added to the grid, we hide the toast. If the grid is full, we set the `toastMessage` signal and show the toast.

And since we made our `Toast` render its children, we can pass the massage and add an error icon to the toast.

```css
.Error-Icon {
    width: 2vmax;
    height: 2vmax;
    margin-right: 0.5vmax;
}
```

If you save the changes and click on an icon, you should now be able to add new items to the grid and display the toast if there is no space.

### Adding tooltip to the icons

One little improvement we can add is a tooltip to the icons. The tooltip will show the name of the item when we hover over the icon.

The `Tooltip` component will be very similar to the `Toast` as it will accept a `show` prop that will determine if it should be shown. The `Tooltip` will also render its children.

```tsx
import { ParentComponent, Show } from "solid-js";
import styles from './Tooltip.module.css';
import Block from "@components/Layout/Block/Block";


type TooltipProps = {
    show: boolean,
}

const Tooltip: ParentComponent<TooltipProps> = (props) => {
    return (
        <Show when={props.show} >
            <Block class={styles.Tooltip}>{props.children}</Block>
        </Show>
    )
}

export default Tooltip;
```

Styles:

```css
.Tooltip {
    padding: 0.75vmax;
    background-color: #3F404A;
    opacity: 1;
    border: 1px solid white;
    border-radius: 5px;
    z-index: 1000;
    position: absolute;
    top: 0;
    left: 0;
    transform: translateY(100%);
    white-space: nowrap;
}
```

Now, let’s import the `Tooltip` component in the `NavIcon.tsx` file and use it to display the item’s name when hovering over the icon.

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

We added a `showTooltip` signal that will determine if the tooltip should be shown. We then added the `mouseenter` and `mouseleave` events to show and hide the tooltip when hovering over the icon.

And just like with the `Toast`, we added an icon next to the message.

```css
.InfoIcon {
    width: 1vmax;
    height: 1vmax;
    margin-right: 0.5vmax;
}
```

And that’s it! We can now see the item’s name when hovering over the icon.

## Removing items from the grid

With our current setup, implementing item removal will be very easy. We can add a `removeItem` function in the `gridStore.ts` file that will:

- set the `active` property of the item to `false`.
- clear the cell where the item is located.
- update the grid data model.

```tsx
const removeItem = (id: number) => {
    setGridState('items', item => item.id === id, produce(item => {
        item.active = false
        clearCell(item)
    }))

    updateGridDataModel();
}
```

Now, we can add this function to the `onClick` event on the grid items.

```tsx
<div class={styles['CellItem-drag']} ></div>
<div class={styles['CellItem-close']} onClick={() => removeItem(item.id)}>
    <div class={styles.CloseIcon}>X</div>
</div>
```

And that’s it! We can now remove items from the grid.

## Displaying components in the grid items

Since the grid items are screens within our Football Manager game, there is one final thing we have to add to the `Grid` component - the ability to display components in the grid items.

We are going to achieve this by creating a `screens-registry.ts` file where we will match the `name` property of each item to a component it should render.

```tsx
import Test from "@custom-components/Util/Test";
import { JSX } from "solid-js";

export const screenRegistry: Record<string, (props: any) => JSX.Element> = {
    "Team Roster": Test,
    "Match Tactics": Test,
    "Team Settings": Test,
    "Player Stats": Test,
    "Match Calendar": Test,
    "Team Morale": Test,
    "Financials": Test,
    "Transfer Market": Test,
    "Match Stats": Test,
    "Team News": Test,
    "Scouting": Test,
    "Manager Stats": Test,
}
```

Later, when we have build actual components for each screen, we can replace the `Test` component with the actual component.

Now, in the `GridItem` component, we will import the `screenRegistry` and use it to render the component based on the `name` property of the item. We are going to use the [Dynamic ](https://docs.solidjs.com/concepts/control-flow/dynamic#dynamic)`SolidJS` component to render the item’s component.

```tsx
import { screenRegistry } from "../../../utils/screens-registry";
import { Dynamic } from "solid-js/web";

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

We have implemented a placeholder `Test` component that will display the name of the screen. We will remove the `Test` component after we have built the actual components for each screen.

```tsx
const Test = (props: any) => {
    return <div>{props.name}</div>
}

export default Test
```


## Conclusion

With these changes implemented, our grid is almost fully functional and we can soon proceed by adding the game screens for the Football Manager game!

## On this page
