# Making chat with emojis in Gameface

> Creating a chat in Gameface is a straightforward process, thanks to the built-in support for websockets. This is especially true when utilizing a library likesocket.io.

> 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/chat-emojis/

## Making chat with emojis in Gameface

ui tutorials

5/30/2024

Kaloyan Geshev

1. 1/28/2025 Update
2. Showcase overview
   1. Source location
3. Sample specifics
   1. Chat messages container and buttons
   2. Sending messages
   3. Receiving messages
   4. Server
   5. Chat emojis - Model
   6. Chat emojis (FE) - Emojis panel
   7. Chat emojis (BE) - Resolving emojis
   8. Chat user connected and disconnected
4. Styles

Creating a chat in Gameface is a straightforward process, thanks to the built-in support for websockets. This is especially true when utilizing a library like [socket.io ](https://socket.io/). We have a [topic ](https://docs.coherent-labs.com/cpp-gameface/content_development/pages_guides/chatsocketio/)in our documentation that explains how the official socket.io [chat sample ](https://socket.io/get-started/chat/)works seamlessly in Gameface.

### 1/28/2025 Update

**In version 1.61, Gameface adds support for certain types of emoji fonts. As this tutorial shows how to do chat emojis with `SVG` you may also want to know how to do it with an emoji font instead. You can check the guide inside the Emoji support news page for further information.**

## Showcase overview

In this showcase, we have enhanced the socket.io chat sample by adding several features:

- A scrollable container for messages, using the Gameface scrollable-container [component ](https://coherentlabs.github.io/GameUIComponents/en/components/scrollable-container/), as Gameface does not natively support a scroll slider.
- Connect and disconnect user messages displayed in the chat.
- Timestamps for all messages.
- Displaying the user ID for incoming messages.
- A panel for sending emojis in the chat.

This sample focuses on how to send and show emojis in the chat, as Gameface does not currently support OS emojis natively. And it has the added bonus of allowing you to use your own custom emojis. One straightforward method is to use SVG emojis. For this sample, we used a small set of SVG emojis from [OpenMoji ](https://openmoji.org/)to demonstrate the simplest way of adding emoji support to a chat in Gameface.

### Source location

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

To run the sample, follow these steps:

1. Do `npm i` in this directory.
2. Run the chat server by executing `node server.js` in this directory.
3. Open two or more instances of Gameface and chat between them.

## Sample specifics

### Chat messages container and buttons

We followed the socket.io sample to create the messages container and the send button. We then enhanced it by adding scroll functionality to the messages container using the `gameface-scrollable-container` and included a button for toggling the emoji panel.

```html
<gameface-scrollable-container
    automatic
    class="messages-container"
>
    <component-slot data-name="scrollable-content">
        <ul id="messages"></ul>
    </component-slot>
</gameface-scrollable-container>
<form
    id="form"
    action=""
>
    <input
        id="input"
        autocomplete="off"
    />
    <div class="chat-buttons">
        <button class="open-emojis-panel-btn"></button>
        <button class="send-btn">Send</button>
    </div>
</form>
```

### Sending messages

To send the text typed in the chat input to the server, an event is emitted when the `Send` button is clicked or when the `Enter` key is pressed while the input is focused.

```javascript
const socket = io();

document.querySelector('.send-btn').addEventListener('click', () => {
    if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
    }
});

input.addEventListener('keydown', (event) => {
    if (event.keyCode === 13 && input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
    }
});
```

After the server processes the message, it emits an event to all connected users, updating their chat UI. Check the next section for details.

### Receiving messages

Receiving messages from the server on the front end involves subscribing to a `socket` event:

```javascript
socket.on('chat message', ({ msg, id }) => {
    const item = document.createElement('li');
    if (id === socket.id) item.classList.add('right');

    item.innerHTML = (id !== socket.id ? `<div class="user-id">${id}</div>` : '') + msg;
    messages.appendChild(item);

    if (id === socket.id) {
        waitForFrames(() => messagesContainer.onScrollSlider({ detail: { handlePosition: 100 } }), 7);
    }
});
```

This code creates a new `list` element to hold the message from the server, including the user ID if the message is from another user. The element is appended to the messages container, and if the message is from the current user, the scrollable container scrolls to the bottom.

```javascript
if (id === socket.id) {
    waitForFrames(() => messagesContainer.onScrollSlider({ detail: { handlePosition: 100 } }), 7); // Scrolls the slider and container to 100% where the last message is
}
```

`Know issue:` **There is a need to wait for 7 frames to ensure the scrollable container correctly scrolls to the last message. The scrollable container automatically resizes when a new `list` element is appended, which takes about 6 frames. Without waiting, the container might not scroll properly.**

The `waitForFrames` function is defined as follows:

```javascript
function waitForFrames(callback, frames) {
    if (frames === 0) return callback();
    frames--;
    requestAnimationFrame(() => this.waitForFrames(callback, frames));
}
```

### Server

On the server side, messages sent from the front end are processed by listening for `socket` events.

```javascript
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        const d = new Date();
        const timeStamp = [d.getMonth() + 1, d.getDate(), d.getFullYear()].join('/') + ' ' + [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');

        io.emit('chat message', { msg: `<div class="message">${msg}</div><div class="timestamp">${timeStamp}</div>`, id: socket.id });
    });
});
```

A timestamp is generated for each message. The server then emits an event to the front end with the processed message in HTML format, along with the sender’s ID.

### Chat emojis - Model

To simplify the instantiation of all emojis in a panel, we defined an array as a Gameface data binding model. Leveraging Gameface’s [data binding ](https://docs.coherent-labs.com/cpp-gameface/integration/ui_scripting/htmldatabinding/), we can easily iterate over this model and display the emojis in the HTML page.

The model is structured as follows:

```javascript
const emojis = [
    '/assets/emojis/1F600.svg',
    '/assets/emojis/1F601.svg',
    '/assets/emojis/1F602.svg',
    ...
];
```

### Chat emojis (FE) - Emojis panel

We added a button to the right of the chat input that opens a panel with all supported chat emojis, allowing users to add emojis to their messages before sending them. Selecting an emoji from the panel inserts its code into the message input, surrounded by colons. For example, `:1:`.

The panel was created using the [gameface-tooltip ](https://coherentlabs.github.io/GameUIComponents/en/components/tooltip/)component to wrap the emojis in a panel, and the [gameface-scrollable-container ](https://coherentlabs.github.io/GameUIComponents/en/components/scrollable-container/)component to enable scrolling if the emojis overflow the panel.

```html
<gameface-tooltip
    class="emojis-panel"
    target=".open-emojis-panel-btn"
    on="click"
    off="click"
    position="top"
>
    <div slot="message">
        <gameface-scrollable-container
            class="emojis-container"
            automatic
        >
            <component-slot data-name="scrollable-content">
                <div
                    class="emoji emoji-btn"
                    data-bind-for="index,iter:{{emojis}}"
                >
                    <div
                        data-bind-click="addEmoji({{index}})"
                        class="emoji-svg"
                        data-bind-style-background-image-url="{{iter}}"
                    ></div>
                </div>
            </component-slot>
        </gameface-scrollable-container>
    </div>
</gameface-tooltip>
```

Here, we use data binding to render the emoji SVGs in the panel with `data-bind-style-background-image-url="{{iter}}"`, which sets the background of the div to the emoji URLs from the model.

**Note: The tooltip might not be positioned correctly as its target is at the bottom right of the page. To fix this, override the tooltip’s `transform` property:**

```css
.emojis-panel {
    ...
    transform: translateX(-70%) translateY(-105%) !important;
    ...
}
```

### Chat emojis (BE) - Resolving emojis

When a message is received on the server, any emoji codes in the message should be resolved. To achieve this, extend the source in the Server section.

```javascript
const emojis = require('./src/emojisMapServer');

io.on('connection', (socket) => {
    socket.on('chat message', (msg) => {
        const newMessage = msg.replace(/:[0-9]*:/g, (match) => {
            const emojiCode = match.replace(/:/g, ''); // Retrieve the emoji code between the : symbols. For example, :1: corresponds to the emoji with index 1 in our array of emoji URLs.
            return `<img class="emoji" src="${emojis[emojiCode]}"/>`;
        });

        const d = new Date();
        const timeStamp = [d.getMonth() + 1, d.getDate(), d.getFullYear()].join('/') + ' ' + [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');

        io.emit('chat message', { msg: `<div class="message">${newMessage}</div><div class="timestamp">${timeStamp}</div>`, id: socket.id });
    });
});
```

Here, `newMessage` contains the processed message with all emoji codes replaced by `img` elements with the corresponding emoji SVG URLs from the emojis map.

### Chat user connected and disconnected

Additionally, we added messages indicating when a user connects or disconnects from the chat.

This is easily handled on the server side:

```javascript
io.on('connection', (socket) => {
    io.emit('user connected', socket.id);

    ...

    socket.on('disconnect', () => {
        io.emit('user disconnected', socket.id);
    });
});
```

On the front end, we handle the emitted events by subscribing to the `user connected` and `user disconnected` events and reading the user ID:

```javascript
function setUserState(id, connected) {
    const item = document.createElement('li');
    item.textContent = `User ${id} ${connected ? 'connected' : 'disconnected'}!`;
    messages.appendChild(item);
}

socket.on('user connected', (id) => setUserState(id, true));
socket.on('user disconnected', (id) => setUserState(id, false));
```

For each connection or disconnection, we append a `list` item to the messages container.

## Styles

To check the chat styles, refer to the `${Gameface package}/Samples/uiresources/UITutorials/ChatEmojis/styles.css` file.

## On this page
