# Multiplayer UI - Create leaderboard (Part 3)

> A games leaderboard ranks players based on performance, fostering competition by showing top scores and achievements. It encourages players to improve and climb the ranks, enhancing engagement in the game.

> 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/multiplayer-ui/leaderboard/

## Multiplayer UI - Create leaderboard (Part 3)

ui tutorials

8/29/2024

Kaloyan Geshev

1. Showcase Overview
2. Source location
3. Getting started - Backend
   1. Add additional fields to the user
   2. Creating endpoints to retrieve user stats
   3. Adding mock data to the newly registered users
4. Getting started - Frontend
   1. Refactor friends files structure
   2. Add friends wrapper page
   3. Updating routes and adding leaderboard page
   4. Leaderboard wrapper page
   5. Rankings component
   6. UserRankItem component
   7. Display player stats when user is selected from the leaderboard
   8. useDimensions hook
   9. DonutChart component

A games leaderboard ranks players based on performance, fostering competition by showing top scores and achievements. It encourages players to improve and climb the ranks, enhancing engagement in the game.

You can find the rest Multiplayer UI series here.

## Showcase Overview

In this tutorial, we’ll build upon the previous multiplayer UI by adding a leaderboard feature. To accommodate this addition, we’ll refactor some of the existing pages, making it easier to integrate the new leaderboard.

Additionally, we’ll enhance the Express server by introducing new endpoints that retrieve user stats for display on the frontend.

## Source location

You can find the complete sample source within the `${Gameface package}/Samples/uiresources/UITutorials/MultiplayerUI` directory.

- `src` folder contains the UI source code.
- `api` folder contains the Express server source code.

Ensure to run `npm i` before testing the sample.

Refer to the `README.md` file in this directory for information on running the sample locally or previewing it without building or starting any processes.

## Getting started - Backend

We’ll start by updating the backend to include new endpoints that return relevant user stats for the frontend to display on the leaderboard page.

### Add additional fields to the user

To store user stats, we’ll extend the user schema in our database by adding two new fields:

```js
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    password: String,
    status: Boolean,
    totpSecret: String,
    twoFactorEnabled: Boolean,
    friends: [{ type: String }],
    stats: {
        games: Number,
        wins: Number,
        scores: Number
    }
});

module.exports = mongoose.model('user', schema);
```

The `stats` object will store data such as games played, wins, and scores.

### Creating endpoints to retrieve user stats

When the leaderboard page is accessed, all users’ data will be requested from the server. Additionally, when a user is selected from the table, their specific data will be retrieved.

To facilitate this, we’ll add two new routes to the user routes:

```js
router.get('/users/rankings', auth, UserController.getUsersRankings);
router.get('/users/:id/rankings', auth, idValidator, UserController.getUserRankings);
```

#### getUsersRankings method

This method will return the stats data for all users.

```js
class UserController {
    async getUsersRankings(req, res) {
        const stats = await User.find({}, { 'stats.scores': 1, firstName: 1, lastName: 1 }).sort({ 'stats.scores': -1 });
        if (!stats) return res.status(500).send('Internal server error');
        res.json(stats);
    }
}
```

#### getUserRankings method

This method will return the stats for a specific user by passing their `id` in the route params.

```js
class UserController {
    async getUserRankings(req, res) {
        const userStats = await User.findById(req.params.id, { stats: 1, firstName: 1, lastName: 1 });
        if (!userStats) return res.status(500).send('Internal server error');
        res.json(userStats);
    }
}
```

### Adding mock data to the newly registered users

Since our UI isn’t connected to a live game, we need to generate mock user stats when a new user registers. This can be done at the point of registration by adding mock data to our public database, which is used by the sample application.

```js
class UserController {
    async register(req, res) {
        ...
        try {
            const user = new User({ ...req.body, status: false });
            const totalGames = parseInt(Math.random() * 500);
            // Generate mock stats data for the new user
            user.stats = {
                games: totalGames,
                wins: parseInt(Math.random() * totalGames),
                scores: parseInt(Math.random() * 50000)
            };
            await user.save();
        ...
    }
}
```

## Getting started - Frontend

On the frontend, we’ll add a new leaderboard page to display user stats fetched from the server. Additionally, we’ll reorganize our friends page from the previous tutorial for better structure.

### Refactor friends files structure

To improve organization, we’ll move the `AddFriends` and `Friends` pages into a new `Friends` folder.

```diff
pages
│   Friends
│   └───FriendsList
|       |   FriendsList.jsx
|       |   FriendsList.scss
│   └───AddFriends
|       |   AddFriends.jsx
|       |   AddFriends.scss
└───Friends
│   │   Friends.jsx
│   │   Friends.scss
└───AddFriends
    │   AddFriends.jsx
    │   AddFriends.scss
```

### Add friends wrapper page

We’ll create a wrapper component in `pages/Friends/FriendsPageWrapper` to display both the friends list and add friends pages.

```jsx
import React from 'react';
import './FriendsPageWrapper.scss';
import { NavLink, Outlet } from 'react-router-dom';

const FriendsPageWrapper = () => {
    return (
        <div className="friends">
            <div className='app-wrapper-sub-navigation'>
                <NavLink className='sub-nav-btn' to="/friends" end>Friends list</NavLink >
                <NavLink className='sub-nav-btn' to="/friends/add-friends">Add friends</NavLink >
            </div>
            <div className="app-wrapper-container">
                <gameface-scrollable-container automatic className="scrollable-container-component">
                    <component-slot data-name="scrollable-content">
                        <Outlet />
                    </component-slot>
                </gameface-scrollable-container>
            </div>
        </div>
    )
}

export default FriendsPageWrapper;
```

Here, `NavLink` elements are set up for easy navigation between the friends list and add friends pages. The `gameface-scrollable-container` has been moved from both individual pages to this wrapper for simplicity.

**Note: Use the `end` attribute on the main route (`/friends`) to ensure the correct `NavLink` is highlighted when navigating between subroutes.**

The `Outlet` will render the component for the active subroute. Next, we’ll adjust the routing in `App.jsx`.

### Updating routes and adding leaderboard page

In `App.jsx`, we’ll refactor our existing routes into subroutes and include a route for the leaderboard page.

```jsx
<Routes>
    <Route path='/' element={<ProtectedRoute><Home /></ProtectedRoute>} >
        <Route index element={<Friends />} />
        <Route path="/add-friends" element={<AddFriends />} />
        <Route element={<LeaderboardPageWrapper />} >
            <Route index element={<Rankings />} />
        </Route>
        <Route path="friends" element={<FriendsPageWrapper />} >
            <Route index element={<FriendsList />} />
            <Route path="add-friends" element={<AddFriends />} />
        </Route>
    </Route>
    <Route path='/register' element={<Register />} />
    <Route path='/login' element={<Login />} />
    <Route path='/totp' element={<Totp />} />
</Routes>
```

We’ve set the default home route to lead to the rankings subpage within the leaderboard page.

### Leaderboard wrapper page

We’ll apply a similar approach to the leaderboard page wrapper as we did with the `FriendsPageWrapper`.

```jsx
import React, { useState } from 'react';
import './LeaderboardPageWrapper.scss';
import { NavLink, Outlet } from 'react-router-dom';
import PlayerStats from '../../../components/PlayerStats';

const LeaderboardPageWrapper = () => {
    const [selectedPlayerId, setSelectedPlayerId] = useState('');

    return (
        <div className="leader-board">
            <div className='app-wrapper-sub-navigation'>
                <NavLink className='sub-nav-btn' to="/">Rankings</NavLink >
            </div>
            <div className="leader-board-container">
                <div className="app-wrapper-container leader-board-container-outlet">
                    <Outlet context={[selectedPlayerId, setSelectedPlayerId]} />
                </div>
                <PlayerStats id={selectedPlayerId} />
            </div>
        </div>
    )
}

export default LeaderboardPageWrapper;
```

This wrapper contains the rankings table, displayed in the `Outlet` via the `Rankings` component that we set up earlier in the router. It also includes the `PlayerStats` component, which appears on the right when a user is selected from the table. The `PlayerStats` component shows additional details about the selected player, such as their games, wins, losses, and win rate.

#### State Sharing

To ensure the `PlayerStats` component correctly displays data for the selected player, we define a state in the leaderboard page wrapper using `const [selectedPlayerId, setSelectedPlayerId] = useState('');` and pass it as context to the `Outlet`, which is then used by the `Rankings` component. In `Rankings`, you can access this context as follows:

```jsx
import { useOutletContext } from 'react-router-dom';
...
const [selectedPlayerId, setSelectedPlayerId] = useOutletContext();
```

Using `setSelectedPlayerId` updates the `selectedPlayerId`, which reflects in both the `LeaderboardPageWrapper` state and the `PlayerStats` component, enabling shared state between components in React. While you could use other state management approaches like redux, this method keeps things simple.

### Rankings component

To display the rankings table, we’ll create a new `Rankings` page that renders within the `LeaderboardPageWrapper`’s `Outlet`.

This page includes a loader, a table with headers, the current user’s scores at the top, and a `gameface-scrollable-container` for the list of other users.

We begin by setting up component states, hooks, and the outlet context:

```jsx
const [user] = useLocalStorage('user');
const [selectedPlayerId, setSelectedPlayerId] = useOutletContext();
const [loadingData, setLoadingData] = useState(true);
const [rankingsData, setRankingsData] = useState([]);
const fetch = useFetch();
```

Upon mounting, this component fetches user rankings to display:

```jsx
useEffect(() => {
    updateRankingsList();
}, []);

const updateRankingsList = useCallback(async () => {
    const [xhr, error] = await fetch('GET', `${process.env.SERVER_URL}/api/users/rankings`);
    if (error) return setLoadingData(false);
    if (error) {
        setLoadingData(false);
        return console.error(error);
    }
    const rankings = JSON.parse(xhr.responseText);
    setLoadingData(false);
    setRankingsData(rankings);
});
```

As mentioned earlier, shared state allows the player stats panel to open when a user is selected from the table.

```jsx
const openPlayerStats = useCallback((event) => {
    const next = event.currentTarget.dataset.id;
    setSelectedPlayerId((prev) => {
        if (prev === next) return '';
        return next;
    });
}, []);
```

To simplify the code, we create memoized variables for the current user’s index and data:

```jsx
const [currentUserIndex, currentUserData] = useMemo(() => {
    const userIndex = rankingsData.findIndex((userData) => userData._id === user.id);
    return [userIndex, rankingsData[userIndex]];
}, [rankingsData, user]);
```

Finally, we render the UI:

```jsx
return (
    <>
        <Loader className="loader-container" visible={loadingData}></Loader>
        {!loadingData && <UserRankItem
            className="header"
            rank="Rank"
            userName="Name"
            scores="Score" />
        }

        {!loadingData && currentUserData && <UserRankItem
            className={`player player-current ${selectedPlayerId === currentUserData._id ? 'player-selected' : ''}`}
            userName={`${currentUserData.firstName} ${currentUserData.lastName}`}
            scores={currentUserData.stats.scores}
            rank={currentUserIndex + 1}
            userId={currentUserData._id}
            onClick={openPlayerStats}
        />}

        <gameface-scrollable-container automatic class="players-container">
            <component-slot data-name="scrollable-content">
                {!rankingsData.length && !loadingData && 'No data'}
                {rankingsData.map((user, index) => {
                    if (user._id === currentUserData?._id) return null;

                    return <UserRankItem key={user._id}
                        className={`player ${selectedPlayerId === user._id ? 'player-selected' : ''}`}
                        userName={`${user.firstName} ${user.lastName}`}
                        scores={user.stats.scores}
                        rank={index + 1}
                        userId={user._id}
                        onClick={openPlayerStats}
                    />
                })}
            </component-slot>
        </gameface-scrollable-container>
    </>
)
```

### UserRankItem component

The `UserRankItem` component is used to create the table preview on the `Rankings` page. It accepts the following props:

- `rank`: The user’s rank to be displayed in the table.
- `userName`: The name of the user.
- `userId`: The user’s unique ID.
- `scores`: The user’s scores.
- `className`: Additional classes for the component’s wrapper div.
- `onClick`: Event handler triggered when the component is clicked, typically used to open the player’s stats.

```jsx
import React from "react";

const UserRankItem = ({ rank, userName, userId, scores, className, onClick }) => {
    return <div className={`guic-row ${className}`} data-id={userId} onClick={onClick}>
        <div className='guic-col-1 player-rank'>
            {rank}
        </div>
        <div className='guic-col-8 player-name'>
            {userName}
        </div>
        <div className='guic-col-2 player-score'>
            {scores}
        </div>
    </div>
}

export default UserRankItem;
```

This component uses classes from the [gameface-grid ](https://coherentlabs.github.io/GameUIComponents/en/components/grid/)component to correctly align its contents.

You can use the `UserRankItem` component in different layouts within the table:

#### Table header

To create a table header, set the `UserRankItem` props like this:

```jsx
<UserRankItem className="header" rank="Rank" userName="Name" scores="Score" />
```

#### User items

To display the current user at the top of the list, use `UserRankItem` as follows:

```jsx
<UserRankItem
    className={`player player-current ${selectedPlayerId === currentUserData._id ? 'player-selected' : ''}`}
    userName={`${currentUserData.firstName} ${currentUserData.lastName}`}
    scores={currentUserData.stats.scores}
    rank={currentUserIndex + 1}
    userId={currentUserData._id}
    onClick={openPlayerStats}
/>
```

For other users, generate the items from the `rankingsData` array:

```jsx
{rankingsData.map((user, index) => {
    if (user._id === currentUserData?._id) return null;

    return <UserRankItem key={user._id}
        className={`player ${selectedPlayerId === user._id ? 'player-selected' : ''}`}
        userName={`${user.firstName} ${user.lastName}`}
        scores={user.stats.scores}
        rank={index + 1}
        userId={user._id}
        onClick={openPlayerStats}
    />
})}
```

If the user in the data matches the current user, skip rendering their `UserRankItem` since it has already been displayed.

### Display player stats when user is selected from the leaderboard

When a user is chosen from the leaderboard table, their stats will appear to the right of the table. To accomplish this, we’ll create a `PlayerStats` component. This component will show a loading indicator while fetching the user’s data from the server and, once ready, will display the number of games played, wins, losses, and win rate. Additionally, a donut chart will visualize the win/loss ratio.

We’ll start by defining a `StatItem` component, which will be responsible for displaying each individual stat and its corresponding value:

```jsx
const StatItem = ({ title, value }) => {
    return <div className='player-stats-container-item'>
        <div className='player-stats-container-item-title'>{title}</div>
        <div className='player-stats-container-item-data'>{value}</div>
    </div>
}
```

Then we can continue with the `PlayerStats` component. First we setup the states that the component will use and other things such as using the `useDimensions` hook that will be needed for making the chart responsive.

Next, we’ll build the `PlayerStats` component. This involves setting up the necessary state variables and using the `useDimensions` hook to make the donut chart responsive.

```jsx
const fetch = useFetch();
const [loading, setLoading] = useState(false);
const [userData, setUserData] = useState(null);
const loadingTimeoutRef = useRef(null);
const [{ width: chartWidth, height: chartHeight }, chartWrapperRef] = useDimensions(chartWrapperRef);

const setLoadingWithTimeout = useCallback((value) => {
    loadingTimeoutRef.current = setTimeout(() => {
        setLoading(value);
        loadingTimeoutRef.current = null;
    }, 300);
}, []);
```

We then fetch the player’s data from the server when the component mounts:

```jsx
useEffect(() => {
    async function getUserData() {
        setLoading(true);
        if (!id) {
            setLoadingWithTimeout(false)
            return setUserData(null);
        }

        const [userStatsXhr, error] = await fetch('GET', `${process.env.SERVER_URL}/api/users/${id}/rankings`);
        if (error) return setLoadingWithTimeout(false);
        setUserData(JSON.parse(userStatsXhr.responseText));
        setLoadingWithTimeout(false);
    }
    getUserData();

    return () => {
        if (loadingTimeoutRef.current) clearTimeout(loadingTimeoutRef.current);
    }
}, [id]);
```

To simplify rendering, we define two memoized variables:

```jsx
const userStats = useMemo(() => {
    if (!userData) return { games: 0, wins: 0, loses: 0, winRate: 0 };

    return {
        games: userData.stats.games,
        wins: userData.stats.wins,
        loses: userData.stats.games - userData.stats.wins,
        winRate: (userData.stats.wins / userData.stats.games * 100).toFixed(1)
    };
}, [userData]);

const chartData = useMemo(() => {
    return [
        { name: 'Wins', value: userStats.wins },
        { name: 'Loses', value: userStats.loses }
    ]
}, [userStats])
```

Finally, we’re ready to render the `PlayerStats` component:

```jsx
return <div className={`leader-board-player ${id ? 'leader-board-player-visible' : ''}`}>
    <Loader className="leader-board-player-loader" visible={loading}></Loader>
    <div className={`player-stats ${!id || loading ? 'player-stats-invisible' : ''}`}>
        <div ref={chartWrapperRef} className='player-stats-graph'>
            <DonutChart width={chartWidth} height={chartHeight} data={chartData} />
        </div>
        {!userData && 'Unable for fetch user data.'}
        {userData && <>
            <div className='player-stats-name'>{userData.firstName} {userData.lastName}</div>
            <div className='player-stats-container'>
                <StatItem title="Games" value={userStats.games} />
                <StatItem title="Wins" value={userStats.wins} />
                <StatItem title="Loses" value={userStats.loses} />
                <StatItem title="Win rate" value={userStats.winRate} />
            </div>
        </>
        }
    </div>
</div>
```

#### StatItem component

The `StatItem` component is stateless and serves to display data fetched from the server.

#### Loading indicator timeout

A loading indicator with a timeout is added to give the donut chart enough time to render and load the data.

### useDimensions hook

To make the donut chart responsive, a `useDimensions` hook is used. This hook observes the dimensions of the chart’s parent element, updating the chart’s dimensions whenever the parent’s size changes.

```jsx
import React, { useEffect, useRef, useState } from 'react';

export const useDimensions = () => {
    const ref = useRef(null);
    const resizeObserverRef = useRef(null);

    const getDimensions = () => {
        return {
            width: ref.current ? ref.current.offsetWidth : 0,
            height: ref.current ? ref.current.offsetHeight : 0
        };
    };

    const [dimensions, setDimensions] = useState(getDimensions);

    const handleResize = () => {
        const parentDimensions = getDimensions();
        if (parentDimensions.width !== dimensions.width || parentDimensions.height !== dimensions.height) {
            setDimensions(parentDimensions);
        }
    };

    useEffect(() => {
        resizeObserverRef.current = new ResizeObserver(handleResize);
        if (ref.current) resizeObserverRef.current.observe(ref.current);

        return () => {
            if (resizeObserverRef.current) resizeObserverRef.current.disconnect();
        };
    }, [ref]);

    return [dimensions, ref];
}
```

Instead of watching for document resize, we use `ResizeObserver` to monitor changes to the dimensions of the chart’s parent element.

### DonutChart component

We’ll use the [d3 ](https://d3js.org/)library to create a donut chart in React. A post describing how to use this library in Gameface with plain JavaScript can be found here.

```jsx
import React, { useEffect, useMemo } from "react";
import * as d3 from "d3";
import './DounutChart.scss';

const colors = [
    { fill: '#009B2C80', stroke: '#15FF00' },
    { fill: '#81000080', stroke: '#FF000080' },
]

const STOKE_WIDTH = 3;

const getArcsConfig = (radius, arcData) => {
    return {
        innerRadius: parseInt(radius * 0.80),
        outerRadius: radius,
        startAngle: arcData.startAngle,
        endAngle: arcData.endAngle,
    }
}

export const DonutChart = ({ width, height, data }) => {
    const radius = useMemo(() => {
        return (Math.min(width, height) / 2) - STOKE_WIDTH - 20;
    }, [width, height]);

    const pie = useMemo(() => {
        const pieGenerator = d3.pie().value((d) => d.value).sort(null);
        return pieGenerator(data);
    }, [data]);

    const arcs = useMemo(() => {
        const arcPathGenerator = d3.arc().padAngle(0.08);
        return pie.map((p) => arcPathGenerator(getArcsConfig(radius, p)));
    }, [radius, pie]);

    useEffect(() => {
        d3.selectAll('.pie-group-arc').transition().duration(500).delay(250)
            .attrTween('d', (d, i) => {
                const interpolate = d3.interpolate({ startAngle: 0, endAngle: 0 }, pie[i]);

                return (t) => {
                    const arcPathGenerator = d3.arc().padAngle(0.08);
                    return arcPathGenerator(getArcsConfig(radius, interpolate(t)));
                };
            });
    }, [pie]);

    return (
        <svg className="pie" viewBox={`0 0 ${width} ${height}`}>
            <g className="pie-group" style={{ transform: `translate(${(width / 2)}px, ${(height / 2)}px)` }}>
                {arcs.map((arc, i) => {
                    const { fill, stroke } = colors[i];
                    return <path className="pie-group-arc" key={i} d={arc} fill={fill} stroke={stroke} strokeWidth={STOKE_WIDTH} />;
                })}
            </g>
        </svg >
    );
};
```

#### Calculating the chart radius

The outer radius of the chart is recalculated dynamically based on the width and height of the parent element. This ensures the chart is responsive, adjusting each time the parent size changes.

#### Generating the pie

A new pie chart is generated whenever the chart data changes. The data passed from the `PlayerStats` component represents the user’s wins and losses, regenerating the pie whenever a different user is selected.

#### Generating the arcs

The arcs of the chart are generated based on the outer radius and the pie data. They will regenerate if either the radius or the user data changes.

#### Animating the arcs

To animate the arcs when created, the `useEffect` hook is used to handle the animation when the chart is mounted or the pie data changes.

#### Making the chart responsive

To make the chart responsive, the `svg` element needs the `viewBox` attribute set dynamically:

```jsx
<svg className="pie" viewBox={`0 0 ${width} ${height}`}>
```

Additionally, the group holding the arcs should be moved to the center of the svg element:

```jsx
<g className="pie-group" style={{ transform: `translate(${(width / 2)}px, ${(height / 2)}px)` }}>
```

## On this page
