Skip to content

AgoraIO-Usecase/AgoraChat-UIKit-web

Repository files navigation

Get Started with Agora Chat UIKit for Web

Overview

agora-chat-uikit is a UI component library based on the Chat SDK. It provides common UI components, module components containing the chat business logic, and container components, allowing users to customize the UI using the renderX methods. agora-chat-uikit provides a UIKitProvider for data management. The UIKitProvider automatically listens for Chat SDK events to modify data for UI updates. Developers can use the library to quickly build custom instant messaging applications based on actual business requirements.

Technical principles

Agora Chat UIKit consists of three parts: UI components, mobx store for data management, and chat SDK. UI components include container components, compound components module, and pure UI components. These components at different levels are accessible to the public. Users can reference any of these components to build their own applications. UIKit uses mobx to manage global data, and users can reference the rootStore to get all the data and the action methods for data manipulation. UIKit integrates the chat SDK and interacts with the server through the Chat SDK.

Functions

The agora-chat-uikit repository provides the following functions:

  • Implements automatic layout to match the width and height of the container.
  • Sends and receives messages, displays messages, shows the unread message count, and clears messages. The text, image, file, emoji, and audio messages are supported.
  • Searches for and deletes conversations.
  • Customizes UI styles.

The agora-chat-uikit library provides the following functions:

  • Automatic layout to match the width and height of the container;
  • Send and receive messages, message display, message unread count, clear messages, message types include: (text, picture, file, expression, audio, video message);
  • Search for and delete conversation.
  • Customize the UI.
module function description
Conversation List
Display conversation information Display information such as avatars, nicknames, last message, unread message count etc. of the conversation
Delete conversation Deletes the conversation from the conversation list
Chat
Message sender Support to send text, emoji, picture, file, voice
Display message Single or group chat message display, including profile avatar, nickname, message content, time, sent status, and read status. Message types include text, picture, video, file, and voice
Operate on messages Including editing, deleting, replying, recalling, translating, selecting, reacting, threading, and other operations on messages

Prerequisites

In order to follow the procedure in this page, you must have:

Compatible browsers

Browser Supported Version
IE 11 or later
Edge 43 or later
Firefox 10 or later
Chrome 54 or later
Safari 11 or later

Project setup

1. Create a Web Chat UIKit project

# Install a CLI tool.
npm install create-react-app
# Create an my-app project.
npx create-react-app my-app
cd my-app
The project directory.

├── package.json
├── public # The static directory of Webpack.
│ ├── favicon.ico
│ ├── index.html # The default single-page app.
│ └── manifest.json
├── src
│ ├── App.css # The CSS of the app's root component.
│ ├── App.js # The app component code.
│ ├── App.test.js
│ ├── index.css # The style of the startup file.
│ ├── index.js # The startup file.
│ ├── logo.svg
│ └── serviceWorker.js
└── yarn.lock

2. Integrate the Web Chat UIKit

Install the Web Chat UIKit

  • To install the Web Chat UIKit with npm, run the following command:
npm install agora-chat-uikit --save
  • To Install Agora chat UIKit for Web with Yarn, run the following command:
yarn add agora-chat-uikit

Build the application using the agora-chat-uikit component

Import agora-chat-uikit into your code.

// App.js
import React, { Component, useEffect } from "react";
import {
  Provider,
  Chat,
  ConversationList,
  useClient,
  rootStore,
} from "agora-chat-uikit";
import "agora-chat-uikit/style.css";

const appKey = "you app key"; // your appKey
const user = ""; // your user ID
const agoraToken = ""; // agora chat token

const conversation = {
  chatType: "singleChat", // 'singleChat' || 'groupChat'
  conversationId: "agora", // target user id or group id
  name: "Agora", // target user nickname or group name
  lastMessage: {},
};
const ChatApp = () => {
  const client = useClient();
  useEffect(() => {
    client &&
      client
        .open({
          user,
          agoraToken,
        })
        .then((res) => {
          console.log("get token success", res);
          // create a conversation
          rootStore.conversationStore.addConversation(conversation);
        });
  }, [client]);

  return (
    <div>
      <div>
        <ConversationList />
      </div>
      <div>
        <Chat />
      </div>
    </div>
  );
};

class App extends Component {
  render() {
    return (
      <Provider
        initConfig={{
          appKey,
        }}
      >
        <ChatApp />
      </Provider>
    );
  }
}

export default App;

Run the project and send your first message

npm run start

Now, you can see your app in the browser.

In the default App Key situation, for the convenience of quick experience, we support several types of message distribution by default. After clicking to select a member, enter your first message and send it.

Note

If a custom App Key is used, no contact is available by default and you need to first add contacts or join a group.

Agora provides an open source AgoraChat UIKit web project on GitHub, where you can clone and run the project or reference the logic to create a project that integrates agora-chat-uikit.

Component

agora-chat-uikit provides the following components:

  • Container components: UIKitProvider, Chat, and ConversationList.

  • Module components: BaseMessage, AudioMessage, FileMessageVideoMessage, ImageMessage, TextMessage, Header, Empty, MessageList, ConversationItem, MessageEditor, MessageStatus.

  • Pure UI components: Avatar, Badge, Button, Checkbox, Icon, Modal, Tooltip.

  • Container components: ProviderChatConversationList;

  • Module components: BaseMessageAudioMessageFileMessageVideoMessageImageMessageTextMessageHeaderEmptyMessageListConversationItemMessageEditorMessageStatus;

  • Pure UI components: AvatarBadgeButtonCheckboxIconModalTooltip;

Container components introduction:

Component Description Props Props Description
Provider The Provider does not render any UI but only provides global context for components. It automatically listens to SDK events, transmits data downward, and drives component rendering initConfig: { appkey: string } You can configure appKey
local
      
To configure the localized copy, see the parameters of the i18next init method
features Configure the features you need globally. If the required features are also configured in the component, the configuration in the component shall prevail
onError Callback when an error occurs when calling sdk
ConversationList Conversation list component className Component class name
prefix css class name prefix
headerProps Props for the Header component
itemProps Props for the ConversationItem component
renderHeader?: () => React.ReactNode Custom rendering header, which receives a function that returns a react node
renderSearch?: () => React.ReactNode Custom rendering search component, which receives a function that returns a react node
onItemClick?: (data: ConversationData[0]) => void Click on the conversation event to return the data of the current session
onSearch?: (e: React.ChangeEvent) => boolean Search input change event. If the function returns false, it will prevent the default search behavior. Users can search according to their own conditions
Chat Chat component className: string Component CSS class name
prefix: string CSS class name prefix
headerProps: HeaderProps props for Header
messageListProps: MsgListProps Props for the MessageList component
messageEditorProps: MessageEditorProps Props for the MessageEditor component
rtcConfig: ChatProps['rtcConfig'] Parameters required when using audio and video calls
renderHeader: (cvs: CurrentCvs) => React.ReactNode Custom render Header component that takes a function that returns a react node, CurrentCvs is the current conversation
renderMessageList?: () => ReactNode; Custom render message list component
renderMessageEditor?: () => ReactNode; Custom render message sender component
renderEmpty?: () => ReactNode; Custom render empty pages without a conversation

store

UIKit provides a rootStore that contains all the data. rootStore contains:

  • initConfig: UIKit initializes data
  • client: Chat SDK instance
  • conversationStore: Conversation list data
  • messageStore: Message data

For attributes and methods in the rootStore, see the rootStore document.

  • conversationStore: indicates the data related to the conversation list
  • messageStore: indicates message-related data
  • addressStore: indicates the address book data
Store Attribute/Method Description
conversationStore
currentCvs Current conversation
conversationList All conversations
searchList The searched conversations
setCurrentCvs Set the current conversation
setConversation Set all conversations
deleteConversation Delete a conversation
addConversation Add a conversation
topConversation Top a conversation
modifyConversation Modifying a conversation
messageStore
message All conversation messages, including singleChat, groupChat, byId
currentCvsMsgs Set messages for the current conversation
sendMessage Send a message
receiveMessage Receive a message
modifyMessage Edit a message
sendChannelAck Reply with a channel ack to clear unread data from the conversation
updateMessageStatus Update message status
clearMessage Clear a conversation's messages

In this section, the Chat and Button components are used as an example to describe how to modify the component style.

Example how to customize the Chat component

Modify Component Style

You can modify the style by passing className, style, and prefix through the component props

import { Chat, Button } from "agora-chat-uikit";

const ChatApp = () => {
  return (
    <div>
      <Chat className="customClass" prefix="custom" />
      <Button style={{ width: "100px" }}>Button</Button>
    </div>
  );
};

Use custom components

This section uses the CustomHeader component to describe how to use custom components.

Using custom components

Custom components can be rendered through the renderX method of container components

import {Chat, Header} from 'agora-chat-uikit'

const ChatApp = () => {
  const CustomHeader = <Header back content="Custom Header">
  return(
    <div>
      <Chat renderHeader={(cvs) => CustomHeader}>
    </div>
  )
}

Modify Theme

The UIKit style is developed using the scss framework and defines a series of global style variables, including but not limited to global styles (main color, background color, rounded corners, borders, font size).

// need to use hsla
$blue-base: hsla(203, 100%, 60%, 1);
$green-base: hsla(155, 100%, 60%, 1);
$red-base: hsla(350, 100%, 60%, 1);
$gray-base: hsla(203, 8%, 60%, 1);
$special-base: hsla(220, 36%, 60%, 1);

$font-color: $gray-3;
$title-color: $gray-1;
$component-background: #fff;

$height-base: 36px;
$height-lg: 48px;
$height-sm: 28px;

// vertical margins
$margin-lg: 24px;
$margin-md: 16px;
$margin-sm: 12px;
$margin-xs: 8px;
$margin-xss: 4px;

// vertical paddings
$padding-lg: 24px;
$padding-md: 20px;
$padding-sm: 16px;
$padding-s: 12px;
$padding-xs: 8px;
$padding-xss: 4px;
// font
$font-size-base: 14px;
$font-size-lg: $font-size-base + 2px;
$font-size-sm: 12px;
$text-color: fade($black, 85%);

All variables can be viewed here ''

  1. Use webpack for variable coverage:
module.exports = {
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          "style-loader",
          "css-loader",
          {
            loader: "sass-loader",
            options: {
              additionalData: `@import "@/styles/index.scss";`,
            },
          },
        ],
      },
    ],
  },
};
  1. Customize in create-react-app

creating a scss file within variables to override style.scss. Need to ensure the order of importing files

@import "agora-chat-uikit/style.scss"; // agora-chat-uikit theme
@import "your-theme.scss"; // your theme
@import "agora-chat-uikit/components.scss"; // components style

If these cannot meet the customization requirements, you can also find the elements to cover the style of UIKit.

Community Contribution

If you want to add extra functions to agora-chat-uikit to share with others, you can fork our repository on GitHub and create a pull request. For any questions, please also submit it on the repository. Thank you for your contribution!

Feedback

If you have any problems or suggestions regarding the sample projects, feel free to file an issue.

Reference

Related resources

  • Check our FAQ to see if your issue has been recorded.
  • Dive into Agora SDK Samples to see more tutorials
  • Take a look at Agora Use Case for more complicated real use case
  • Repositories managed by developer communities can be found at Agora Community
  • If you encounter problems during integration, feel free to ask questions in Stack Overflow

License

The sample projects are under the MIT license.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published