Options
All
  • Public
  • Public/Protected
  • All
Menu

Main ChatUI application class

description

The core class for managing the ChatUI SDK, providing methods for initialization, configuration, and interaction with the IM system

example
import { NCChatUIApplication, ChatUIInitParams, ChatUIEvents } from '@nexconn/chatui';

// Initialize the application
const app = NCChatUIApplication.initialize({
hooks: {
reqUserProfiles: async (userIds) => {
// Fetch user profiles
return await fetchUsersFromBackend(userIds);
},
reqGroupProfiles: async (groupIds) => {
// Fetch group profiles
return await fetchGroupsFromBackend(groupIds);
},
reqSystemProfiles: async (targetIds) => {
// Fetch system profiles
return await fetchSystemsFromBackend(targetIds);
},
reqGroupMembers: async (groupId) => {
// Fetch group members
return await fetchGroupMembersFromBackend(groupId);
}
},
language: 'en_US',
logLevel: LogL.INFO
});

if (!app) {
console.error('Failed to initialize ChatUI');
return;
}

// Configure before ready
app.setCommandSwitch(ChatUICommand.SHOW_MESSAGE_STATE, true);
app.setMessageBubbleCfg({
layout: BubbleLayout.LEFT_RIGHT,
showMyProfileInGroupChannel: true
});

// Listen to events
app.addEventListener(ChatUIEvents.RECV_NEW_MESSAGES, (event) => {
console.log('New messages received:', event.data);
});

// Mark as ready
app.ready();

// Open a channel after ready
await app.openChannel({ channelType: ChannelType.PRIVATE, targetId: 'user123' });

Hierarchy

  • EventDispatcher<EventDefined>
    • NCChatUIApplication

Index

Methods

  • addEventListener<K>(type: string | K, listener: ((evt: EventDefined[K]) => void), target?: any): void
  • Type Parameters

    • K extends keyof EventDefined

    Parameters

    • type: string | K
    • listener: ((evt: EventDefined[K]) => void)
        • (evt: EventDefined[K]): void
        • Parameters

          • evt: EventDefined[K]

          Returns void

    • Optional target: any

    Returns void

  • onceEventListener<K>(type: string | K, listener: ((evt: EventDefined[K]) => void), target?: any): void
  • Type Parameters

    • K extends keyof EventDefined

    Parameters

    • type: string | K
    • listener: ((evt: EventDefined[K]) => void)
        • (evt: EventDefined[K]): void
        • Parameters

          • evt: EventDefined[K]

          Returns void

    • Optional target: any

    Returns void

  • removeEventListener<K>(type: string | K, listener: ((evt: EventDefined[K]) => void), target?: any): void
  • Type Parameters

    • K extends keyof EventDefined

    Parameters

    • type: string | K
    • listener: ((evt: EventDefined[K]) => void)
        • (evt: EventDefined[K]): void
        • Parameters

          • evt: EventDefined[K]

          Returns void

    • Optional target: any

    Returns void

  • removeEventListeners(type: string): void
  • Parameters

    • type: string

    Returns void

  • removeAllEventListeners(): void
  • Returns void

  • dispatchEvent<K>(event: EventDefined[K], defer?: boolean): void
  • Type Parameters

    • K extends keyof EventDefined

    Parameters

    • event: EventDefined[K]
    • defer: boolean = true

    Returns void

  • Initialize the ChatUI application

    example
    const app = NCChatUIApplication.initialize({
    hooks: {
    reqUserProfiles: async (userIds) => [...],
    reqGroupProfiles: async (groupIds) => [...],
    reqSystemProfiles: async (targetIds) => [...],
    reqGroupMembers: async (groupId) => [...]
    },
    language: 'en_US'
    });

    Parameters

    Returns null | NCChatUIApplication

    ChatUI application instance or null if initialization fails

  • Set feature toggle switches. Must be called before ready().

    example
    // Enable message read status display
    app.setCommandSwitch(ChatUICommand.SHOW_MESSAGE_STATE, true);

    // Enable @all functionality in groups
    app.setCommandSwitch(ChatUICommand.AT_ALL, true);

    Parameters

    • command: ChatUICommand

      Feature command from ChatUICommand enum

    • enable: boolean

      Whether to enable the feature

    Returns void

  • Query feature toggle switch status

    example
    const isEnabled = app.getCommandSwitch(ChatUICommand.SHOW_MESSAGE_STATE);
    console.log('Message state display:', isEnabled);

    Parameters

    Returns boolean

    Whether the feature is enabled

  • setChannelBarSwitch(enable: boolean): void
  • Set channel bar visibility switch (mobile only)

    example
    // Hide channel bar on mobile
    app.setChannelBarSwitch(false);

    Parameters

    • enable: boolean

      Whether to show the channel bar

    Returns void

  • setChannelDetailBackSwitch(enable: boolean): void
  • Set channel detail back button visibility (mobile only)

    example
    // Hide back button in channel detail
    app.setChannelDetailBackSwitch(false);

    Parameters

    • enable: boolean

      Whether to show the back button

    Returns void

  • setChannelBarTitle(value?: string): void
  • Set channel bar title (only works when channel bar is enabled)

    example
    // Set custom title
    app.setChannelBarTitle('My Conversations');

    // Reset to default
    app.setChannelBarTitle(undefined);

    Parameters

    • Optional value: string

      Title text, undefined to use default

    Returns void

  • Register custom message types. Must be called before ready().

    example
    app.registerCustomMessages([
    {
    messageType: 'custom:gift',
    isPersisted: true,
    isCounted: true,
    digest: (message, language) => {
    return language === 'en_US' ? '[Gift]' : '[礼物]';
    },
    component: {
    tag: 'custom-gift-message',
    constructor: CustomGiftMessageElement
    }
    }
    ]);

    Parameters

    Returns RCResult<void>

    Result indicating success or failure

  • cloneLanguageEntries(lang: string): null | {}
  • Get a copy of built-in language pack entries

    example
    const enEntries = app.cloneLanguageEntries('en_US');
    console.log(enEntries['message.menu.item.copy']); // "Copy"

    Parameters

    • lang: string

      Language code to retrieve (e.g., 'en_US', 'zh_CN')

    Returns null | {}

    Language pack entries object or null if not found

  • Register or override language pack. Only effective before ready().

    example
    // Register custom language
    app.registerLanguagePack('fr_FR', {
    'message.menu.item.copy': 'Copier',
    'message.menu.item.delete': 'Supprimer',
    // ... more entries
    }, 'ltr');

    // Override existing entries
    app.registerLanguagePack('en_US', {
    'message.menu.item.copy': 'Copy Message'
    });

    Parameters

    • lang: string

      Language code (e.g., 'en_US', 'zh_CN')

    • entries: LanguagePackEntries | {}

      Language pack entries

    • direction: LanguageDirection = 'ltr'

      Text direction, defaults to 'ltr'. Only effective when registering a new language.

    Returns void

  • setLanguage(lang: string): void
  • Switch language

    example
    // Switch to English
    app.setLanguage('en_US');

    // Switch to Chinese
    app.setLanguage('zh_CN');

    Parameters

    • lang: string

      Target language code

    Returns void

  • getLanguage(): string
  • Get current language

    example
    const currentLang = app.getLanguage();
    console.log('Current language:', currentLang); // "en_US"

    Returns string

    Current language code

  • getSupportedLanguages(): string[]
  • Get list of supported languages

    example
    const languages = app.getSupportedLanguages();
    console.log('Supported languages:', languages); // ["en_US", "zh_CN"]

    Returns string[]

    Array of supported language codes

  • Set custom push notification configuration hook

    example
    app.setPushConfigHook((message) => {
    return {
    pushTitle: `New message from ${message.senderUserId}`,
    pushContent: message.content?.text || '[Message]',
    pushData: JSON.stringify({ messageId: message.messageUId })
    };
    });

    Parameters

    • hook: PushConfigHook

      Function to modify push notification title, content, etc. before sending

    Returns void

  • Update user profile. Must be called after ready().

    example
    app.updateUserProfile({
    userId: 'user123',
    name: 'John Doe',
    portraitUri: 'https://example.com/avatar.png'
    });

    Parameters

    Returns void

  • Update group profile. Must be called after ready().

    example
    app.updateGroupProfile({
    groupId: 'group456',
    name: 'Project Team',
    portraitUri: 'https://example.com/group.png',
    memberCount: 10
    });

    Parameters

    Returns void

  • updateUserOnlineStatus(userId: string, online: boolean): void
  • Update user online status. Must be called after ready().

    example
    // Set user as online
    app.updateUserOnlineStatus('user123', true);

    // Set user as offline
    app.updateUserOnlineStatus('user123', false);

    Parameters

    • userId: string

      User ID

    • online: boolean

      Online status

    Returns void

  • Refresh group member list immediately. This also updates the group's memberCount.

    description

    This operation only affects local cache and UI display, does not send requests to server.

    example
    app.updateGroupMembers('group456', [
    { userId: 'user1', nickname: 'Alice' },
    { userId: 'user2', nickname: 'Bob' },
    { userId: 'user3', nickname: 'Charlie' }
    ]);

    Parameters

    Returns void

  • Add group members. This also updates the group's memberCount.

    description

    This operation only affects local cache and UI display, does not send requests to server.

    example
    app.addGroupMembers('group456', [
    { userId: 'user4', nickname: 'David' },
    { userId: 'user5', nickname: 'Eve' }
    ]);

    Parameters

    Returns void

  • removeGroupMembers(groupId: string, members: string[]): void
  • Remove group members. This also updates the group's memberCount.

    description

    This operation only affects local cache and UI display, does not send requests to server.

    example
    app.removeGroupMembers('group456', ['user4', 'user5']);
    

    Parameters

    • groupId: string

      Group ID

    • members: string[]

      User IDs to remove

    Returns void

  • Get a copy of the channel list context menu

    example
    const menu = app.cloneChannelsMenu();
    console.log('Channel menu items:', menu);

    Returns ChannelsMenuItem[]

    Array of channel menu items

  • Set channel list context menu

    example
    const menu = app.cloneChannelsMenu();
    menu.items.push({
    {
    id: 'custom:archive',
    icon: 'archive-icon.svg'
    }
    ]);
    app.setChannelsMenu(menu);

    Parameters

    Returns void

  • Get a copy of the message context menu

    example
    const menu = app.cloneMessageMenu();
    console.log('Message menu items:', menu);

    Returns MessageMenuItem[]

    Array of message menu items

  • Set message context menu

    example
    const menu = app.cloneMessageMenu();
    menu.items.push({
    {
    id: 'custom:translate',
    icon: 'translate-icon.svg'
    }
    });
    app.setMessageMenu(menu);

    Parameters

    Returns void

  • openChannel(identifier: ChannelIdentifier, focusInput?: boolean): Promise<RCResult<void>>
  • Open a specific channel. If the channel doesn't exist in the current channel list, creates it and places it at the top.

    example
    // Open a private chat
    await app.openChannel(new DirectChannelIdentifier('user123'), true);

    // Open a group chat
    await app.openChannel(new GroupChannelIdentifier('group456'), true);

    Parameters

    • identifier: ChannelIdentifier

      Channel identifier (channelType + targetId)

    • focusInput: boolean = true

      Whether to focus the input box, defaults to true

    Returns Promise<RCResult<void>>

    Result indicating success or failure

  • deleteChannel(channelIdentifier: ChannelIdentifier): Promise<void>
  • Delete a specific channel

    example
    await app.deleteChannel(channelIdentifier);
    

    Parameters

    • channelIdentifier: ChannelIdentifier

      Channel identifier

    Returns Promise<void>

  • Get the currently opened channel. Returns null if no channel is open.

    example
    const channel = app.getOpenedChannel();
    if (channel) {
    console.log('Current channel:', channel.channelIdentifier);
    }

    Returns null | ChatUIChannelModel

    Channel model or null

  • Add feature extensions to the channel detail panel. Only effective before ready().

    description

    When users click an extension, the ChatUIEvents.CHANNEL_PANEL_EXTENSION_TOUCH event will be dispatched.

    example
    app.setChannelPanelExtensions([
    {
    id: 'video-call',
    icon: 'video-icon.svg',
    filter: (model) => model.channelType === ChannelType.PRIVATE
    },
    {
    id: 'group-settings',
    icon: 'settings-icon.svg',
    filter: (model) => model.channelType === ChannelType.GROUP
    }
    ]);

    // Listen to extension clicks
    app.addEventListener(ChatUIEvents.CHANNEL_PANEL_EXTENSION_TOUCH, (event) => {
    console.log('Extension clicked:', event.data.id);
    });

    Parameters

    Returns void

  • Get a copy of the input menu configuration

    example
    const menu = app.cloneInputMenu();
    console.log('Input menu items:', menu.items);

    Returns InputMenu

    Input menu configuration

  • Set new input menu configuration. Must be called before ready().

    example
    const menu = app.cloneInputMenu();
    menu.items.push({
    id: 'custom:location',
    order: 10,
    icon: 'location-icon.svg'
    });
    app.setInputMenu(menu);

    Parameters

    Returns void

  • Get a copy of the message bubble configuration

    example
    const config = app.cloneMessageBubbleConfig();
    console.log('Bubble configuration:', config);

    Returns MessageBubbleConfig

    Message bubble configuration

  • Set message bubble configuration. Must be called before ready().

    example
    app.setMessageBubbleConfig({
    layout: BubbleLayout.LEFT_RIGHT,
    redius: 12,
    backgroundColorForMyself: 0x007AFF,
    backgroundColorForOthers: 0xE5E5EA,
    showMyProfileInGroupChannel: true,
    showOthersNameInGroupChannel: true
    });

    Parameters

    Returns void

  • Get a copy of the channel list item configuration

    example
    const config = app.cloneChannelsItemConfig();
    console.log('Channel item config:', config);

    Returns ChannelsItemConfig

    Channel list item configuration

  • Set channel list item configuration. Must be called before ready().

    example
    const config = app.cloneChannelsItemConfig();
    config.showUnreadBadge = true;
    config.showTimestamp = true;
    app.setChannelsItemConfig(config);

    Parameters

    Returns void

  • Get a copy of existing image emoji libraries

    example
    const libraries = app.cloneImageEmojiLibraries();
    console.log('Emoji libraries:', libraries);

    Returns ImageEmojiLibrary[]

    Array of image emoji libraries

  • Set image emoji libraries

    example
    const libraries = app.cloneImageEmojiLibraries();
    libraries.push({
    id: 'custom-emoji-1',
    icon: 'emoji-lib-icon.svg',
    itemWidth: 60,
    itemHeight: 60,
    order: 0,
    items: [
    {
    thumbnail: 'data:image/png;base64,...',
    thunbnailWidth: 60,
    thunbnailHeight: 60,
    url: 'https://example.com/emoji1.png',
    width: 120,
    height: 120
    }
    ]
    });
    app.setImageEmojiLibraries(libraries);

    Parameters

    Returns void

  • Get a copy of the character emoji library

    example
    const library = app.cloneChatEmojiLibrary();
    console.log('Emoji library:', library);

    Returns ChatUIEmojiLibrary

    Character emoji library

  • Set character emoji library. Must be called before ready().

    example
    const library = app.cloneChatEmojiLibrary();
    library.items.push('😀', '😃', '😄', '😁', '😆');
    app.setChatEmojiLibrary(library);

    Parameters

    Returns void

  • sendMessage<T>(channelIdentifier: ChannelIdentifier, params: SendMessageParams<T>): Promise<RCResult<Message<T>>>
  • Send a message

    example
    // Send a text message
    const result = await app.sendMessage(
    new DirectChannelIdentifier('user123'),
    new SendTextMessageParams({ text: 'Hello, world!' })
    );

    Type Parameters

    • T extends Record<string, any>

    Parameters

    • channelIdentifier: ChannelIdentifier

      Channel identifier

    • params: SendMessageParams<T>

      Send message parameters

    Returns Promise<RCResult<Message<T>>>

    Result containing the sent message or error

  • insertMessage<T>(message: Message<T>): Promise<RCResult<void>>
  • Insert a message into the local cache

    example
    import { Helper, SendTextMessageParams, DirectChannelIdentifier } from '@nexconn/chat';

    const message = Helper.createMessage(
    new DirectChannelIdentifier('user123'),
    new SendTextMessageParams({ text: 'Local message' })
    );
    message.sentTime = Date.now();
    const result = await app.insertMessage(message);

    Type Parameters

    • T extends Record<string, any>

    Parameters

    • message: Message<T>

      Message to insert

    Returns Promise<RCResult<void>>

    Result indicating success or failure

  • ready(): void
  • Notify the SDK that configuration is complete and ready for initialization

    description

    This method registers all custom elements and marks the application as ready. Must be called after all configuration methods.

    example
    const app = NCChatUIApplication.initialize({ ... });

    // Configure before ready
    app.setCommandSwitch(ChatUICommand.SHOW_MESSAGE_STATE, true);
    app.setMessageBubbleCfg({ layout: BubbleLayout.LEFT_RIGHT });

    // Mark as ready
    app.ready();

    // Now you can call after-ready methods
    await app.openChannel(new DirectChannelIdentifier('user123'));

    Returns void

  • ifReady(): boolean
  • Check if the SDK has completed initialization

    example
    if (app.ifReady()) {
    console.log('App is ready');
    await app.openChannel({ ... });
    } else {
    console.log('App is not ready yet');
    }

    Returns boolean

    Whether initialization is complete

  • getCurrenUserId(): string
  • Get the current user ID

    example
    const userId = app.getCurrenUserId();
    console.log('Current user:', userId);

    Returns string

    Current user ID

  • destroy(): void
  • Destroy the application and clean up resources

    description

    Removes all event listeners and destroys internal modules

    example
    // Clean up when unmounting
    app.destroy();

    Returns void

Constructors