# Website chat widget SDK

With the Sending.Network chat widget, you can quickly and easily build, integrate, and customize your own high-performance and encrypted group messaging function under P2P mode in your website. You can find the source code [here](https://github.com/Sending-Network/sendingnetwork-widget-js). This tutorial will help you build the widget and customize the UI to fit better into your website.

## Getting Started

### Step 1: Get the code

```bash
git clone https://github.com/Sending-Network/sendingnetwork-widget-js.git
```

### **Step 2: Build widget JavaScript code**

Go into the cloned code repository from Step 1 and run the following commands in order:

```bash
yarn
yarn build
```

After running the commands, you will find the _sdnChatWidget.js_ file in the build directory.

### Step 3: Integrate the widget into your website

1.  Import the dependency files in your HTML page.

    ```html
    <script src="/your url/sdnChatWidget.js"></script>
    ```
2. Import the widget.
   *   If you have started the local P2P service in Step 2:

       ```html
       <chat-component />
       ```
   *   Feel free to establish a connection with _https://portal0101.sending.network/_ as the node URL and substitute the `SERVER URL` in the provided code.

       ```html
       <chat-component baseUrl="SERVER URL" />
       ```

### Step 4 (optional): Start the local P2P service

{% hint style="info" %}
Please note that, if you have configured the node URL in [step 3](#step-3-integrate-the-widget-into-your-website), you can safely skip this step. However, if you prefer to create your own local P2P node rather than connecting to a third-party one, please follow the instructions below.
{% endhint %}

1. Inside the SDK, copy the following files to the root directory of your website project. These files contain the implementations of the local P2P service.
   * _olm.wasm_
   * _server.wasm_
   * _sql-wasm.wasm_
   * _sw.js_
2.  Register the local P2P _serviceWorker_ service.

    ```html
    <script>
        if (navigator.serviceWorker) {
          navigator.serviceWorker.register("sw.js");
        }
    </script>
    ```
3.  ​Check whether the _serviceWorker_ is activated or not.

    ```javascript
    navigator.serviceWorker.controller?.state == 'activated'
    ```

### Step 5: Configure the developer key

You will need a developer key to access the Edge Network. For further insight into the mechanism and to request a developer key, please consult the provided guide [here](developer-key).

Kindly establish a secure key server for the proper management of your developer key. Additionally, it is necessary to outline the following API, which enables the widget to send a challenge to be signed by the key server.

To successfully complete the key verification, you need to provide a function called `signWithDevKey`. This function should be attached to the `window` object and will be called during widget login. Here is a snippet of code for your reference:

```javascript
// Input Parameters: { message: string }
// Output Parameters: signature string
window.signWithDevKey = async ({ message }: any) => {
  if (!message) return;
  // Make a request to your backend API to sign the message and retrieve the signature.
  // Note: This example demonstrates the concept; implement this API in your backend.
  const response = await fetch(
  	'https://YOUR_KEY_SERVER/_api/appservice/sign',
    {
      method: 'POST',
      body: JSON.stringify({ message }),
    },
  );
  const { signature } = await response.json();
  return signature;
};
```

## Floating Button

The widget provides a floating button configuration that includes three functionalities:

* When enabled, you can drag and move the widget and the floating button to different positions.
* Clicking the floating button allows you to show/hide the widget.
* The floating button will display the real-time count of unread messages.

Please see the [Floating Button](other#floating-button) for more information.

## Inject Login Status

You can pass the web app login status to the widget if users have previously connected their wallets to your app. If you want to use this feature, you need to configure the `useThirdLogin` property as true in the widget component. After configuring it, the default Metamask login button in the widget will be hidden. You need to use the `window.chatWidgetApi.thirdDIDLogin` method to complete the login action. For specific usage, please refer to the detailed documentation of the [`window.chatWidgetApi.thirdDIDLogin`](customization#third-party-login) API.

```javascript
<chat-component useThirdLogin={true} />
```

## Guest Mode

You can enable tourist mode by configuring the `useTouristMode` property with the room ID of the desired room. In this mode, users can view room messages without connecting wallets, but they cannot participate in the conversation. To switch to normal mode, users can click the wallet button and log in. Use the following code snippet:

```javascript
<chat-component useTouristMode={'Desired Room ID'} />
```

## **Keyword Filtering**

The widget provides methods to set keyword filtering. If you need to use this feature, you can pass the keywords that need to be filtered as an array to the component. The matched keywords will be displayed with '\*' on the interface. The specific configuration is shown below:

```javascript
<chat-component filterWords={['keyword1', 'keyword2']} />
```

## Click-to-Chat

Feel free to use this API for sending messages to any wallet address, whether the recipients are SendingNetwork users or not. It's a handy feature, especially when you want to place a button on a user's profile page or right next to their wallet address. When that button is clicked, the widget will pop up and smoothly take you to a direct messaging room with that particular user. If no private chat room exists with that user, one will be created automatically.

When the recipient, using the specified wallet, logs in to any app integrated with SendingNetwork, they will see the messages you have sent. Please refer to [`window.chatWidgetApi.chatToAddress(address, callback)`](message#quick-chat) for detailed information.

## UI Configuration

The widget provides a way to build a customizable user interface. You can define your own user interface by tweaking the following values.

| topicProps Properties        | Description                                                                |
| ---------------------------- | -------------------------------------------------------------------------- |
| widgetWidth                  | Width of the widget                                                        |
| widgetHeight                 | Height of the widget                                                       |
| widgetBoxShadow              | Shadow effect                                                              |
| primaryColor                 | Button and message bubble color                                            |
| bgColor                      | Background color                                                           |
| mainTextColor                | Main text color including the title, name, etc.                            |
| contactLastMessageTimeColor  | Time of the last message color on the list page                            |
| contactRoomBageColor         | Unread message background color on the list page                           |
| leftMessageColor             | Text color of the left message box in the chat window                      |
| leftMessageBgColor           | Background color of the left message box in the chat window                |
| leftMessageTsColor           | Text color for the time display of the left message box in the chat window |
| rightMessageColor            | Text color of the right message box in the chat window                     |
| rightMessageBgColor          | Background color of the right message box in the chat window               |
| sendMessageBgColor           | Input field background color                                               |
| messageSenderColor           | Text color in the input field                                              |
| sendMessageBorderColor       | Text color in the input field                                              |
| dropMenuBgColor              | Main drop-down menu background color                                       |
| dropMenuItemHoverColor       | Main drop-down menu item hover background color                            |
| userSettingsInputNameBgColor | Personal settings page "Display Name" input box background color           |
| roomViewBgUrl                |  Chat room background image                                                |
