UNPKG

@cometchat/chat-uikit-react

Version:

Ready-to-use Chat UI Components for React

1,378 lines (1,353 loc) 359 kB
import { CometChatCardAction, CometChatCardThemeMode, CometChatCardThemeOverride } from '@cometchat/cards-react'; import * as React$1 from 'react'; import React__default, { ReactNode, ButtonHTMLAttributes, InputHTMLAttributes, Ref, CSSProperties, RefObject } from 'react'; import * as react_jsx_runtime from 'react/jsx-runtime'; import { FlagReason } from '@cometchat/chat-sdk-javascript'; type CometChatPresenceSubscription = 'ALL_USERS' | 'FRIENDS' | 'ROLES'; /** * Represents the settings required to initialize the CometChat UIKit. * This class holds various configuration options, such as app credentials, * socket connection settings, and feature toggles. * * @class UIKitSettings */ declare class UIKitSettings { /** * Unique ID for the app, available on the CometChat dashboard. * @type {string} */ readonly appId: string; /** * Region for the app, such as "us" or "eu". * @type {string} */ readonly region: string; /** * Sets the subscription type for presence. * @type {CometChatPresenceSubscription} */ readonly subscriptionType: CometChatPresenceSubscription; /** * Subscribes to user presence for users having the specified roles. * @type {string[]} */ readonly roles: string[]; /** * Configures WebSocket connections. When set to true, establishes connection * automatically on app initialization. * @type {boolean} * @default true */ readonly autoEstablishSocketConnection: boolean; /** * Authentication key for the app, available on the CometChat dashboard. * @type {string} */ readonly authKey?: string; /** * Custom admin URL, used instead of the default admin URL for dedicated deployments. * @type {string} */ readonly adminHost?: string; /** * Custom client URL, used instead of the default client URL for dedicated deployments. * @type {string} */ readonly clientHost?: string; /** * Storage mode for persisting data. * @type {CometChat.StorageMode} */ readonly storageMode: CometChat.StorageMode; /** * Whether calling functionality is enabled. * When true, the Calls SDK is initialized after login. * When false (default), call buttons are hidden across all components. * @type {boolean} * @default false */ readonly callingEnabled: boolean; /** * Custom CallAppSettings to use when initializing the Calls SDK. * If not provided, the UIKit builds default settings from appId and region. * Pass a plain object: `{ appId: 'APP_ID', region: 'us' }`. * @type {any} */ readonly callAppSettings?: any; /** * Private constructor to initialize the settings using the provided builder. * @param {UIKitSettingsBuilder} builder - The builder instance containing the settings configuration. */ private constructor(); /** * Creates an instance of UIKitSettings from the provided builder. * @param {UIKitSettingsBuilder} builder - The builder instance containing the settings configuration. * @returns {UIKitSettings} A new instance of UIKitSettings. */ static fromBuilder(builder: UIKitSettingsBuilder): UIKitSettings; /** * Retrieves the app ID. * @returns {string} The unique ID of the app. */ getAppId(): string; /** * Retrieves the region. * @returns {string} The region of the app. */ getRegion(): string; /** * Retrieves the subscription type for presence. * @returns {CometChatPresenceSubscription} The subscription type. */ getSubscriptionType(): CometChatPresenceSubscription; /** * Retrieves the roles for presence subscription. * @returns {string[]} The list of roles subscribed to presence. */ getRoles(): string[]; /** * Checks if auto-establish socket connection is enabled. * @returns {boolean} True if auto-establish is enabled, otherwise false. */ isAutoEstablishSocketConnection(): boolean; /** * Retrieves the authentication key. * @returns {string | undefined} The authentication key. */ getAuthKey(): string | undefined; /** * Retrieves the custom admin host URL. * @returns {string | undefined} The admin host URL. */ getAdminHost(): string | undefined; /** * Retrieves the custom client host URL. * @returns {string | undefined} The client host URL. */ getClientHost(): string | undefined; /** * Retrieves the storage mode. * @returns {CometChat.StorageMode} The storage mode. */ getStorageMode(): CometChat.StorageMode; /** * Checks if calling functionality is enabled. * @returns {boolean} True if calling is enabled, otherwise false. */ isCallingEnabled(): boolean; /** * Retrieves the custom CallAppSettings for Calls SDK initialization. * @returns {any | undefined} The custom CallAppSettings, or undefined if not set. */ getCallAppSettings(): any; } /** * Builder class for constructing UIKitSettings instances. * Provides a fluent API for configuring the UIKit initialization settings. * * @class UIKitSettingsBuilder */ declare class UIKitSettingsBuilder { /** * Unique ID for the app, available on the CometChat dashboard. * @type {string} */ appId?: string; /** * Region for the app, such as "us" or "eu". * @type {string} */ region?: string; /** * Sets the subscription type for presence. * @type {CometChatPresenceSubscription} */ subscriptionType?: CometChatPresenceSubscription; /** * Subscribes to user presence for users having the specified roles. * @type {string[]} */ roles?: string[]; /** * Configures WebSocket connections. * @type {boolean} */ autoEstablishSocketConnection?: boolean; /** * Authentication key for the app, available on the CometChat dashboard. * @type {string} */ authKey?: string; /** * Custom admin URL, used instead of the default admin URL for dedicated deployments. * @type {string} */ adminHost?: string; /** * Custom client URL, used instead of the default client URL for dedicated deployments. * @type {string} */ clientHost?: string; /** * Storage mode for persisting data. * @type {CometChat.StorageMode} */ storageMode?: CometChat.StorageMode; /** * Whether calling functionality is enabled. * @type {boolean} * @default false */ callingEnabled?: boolean; /** * Custom CallAppSettings for Calls SDK initialization. * @type {any} */ callAppSettings?: any; /** * Builds and returns an instance of UIKitSettings. * @returns {UIKitSettings} A new instance of UIKitSettings with the specified configuration. */ build(): UIKitSettings; /** * Sets the app ID. * @param {string} appId - The unique ID of the app. * @returns {UIKitSettingsBuilder} The builder instance. */ setAppId(appId: string): this; /** * Sets the region. * @param {string} region - The region of the app. * @returns {UIKitSettingsBuilder} The builder instance. */ setRegion(region: string): this; /** * Sets the authentication key. * @param {string} authKey - The authentication key. * @returns {UIKitSettingsBuilder} The builder instance. */ setAuthKey(authKey: string): this; /** * Subscribes to presence updates for all users. * @returns {UIKitSettingsBuilder} The builder instance. */ subscribePresenceForAllUsers(): this; /** * Subscribes to presence updates for friends. * @returns {UIKitSettingsBuilder} The builder instance. */ subscribePresenceForFriends(): this; /** * Subscribes to presence updates for specific roles. * @param {string[]} roles - The roles to subscribe to. * @returns {UIKitSettingsBuilder} The builder instance. */ subscribePresenceForRoles(roles: string[]): this; /** * Sets the roles for presence subscription. * @param {string[]} roles - The roles to subscribe to. * @returns {UIKitSettingsBuilder} The builder instance. */ setRoles(roles: string[]): this; /** * Enables or disables the auto-establish socket connection. * @param {boolean} value - True to enable, false to disable. * @returns {UIKitSettingsBuilder} The builder instance. */ setAutoEstablishSocketConnection(value: boolean): this; /** * Sets the custom admin host URL. * @param {string} host - The admin host URL. * @returns {UIKitSettingsBuilder} The builder instance. */ setAdminHost(host: string): this; /** * Sets the custom client host URL. * @param {string} host - The client host URL. * @returns {UIKitSettingsBuilder} The builder instance. */ setClientHost(host: string): this; /** * Sets the storage mode. * @param {CometChat.StorageMode} mode - The storage mode. * @returns {UIKitSettingsBuilder} The builder instance. */ setStorageMode(mode: CometChat.StorageMode): this; /** * Enables or disables calling functionality. * @param {boolean} enabled - True to enable, false to disable. * @returns {UIKitSettingsBuilder} The builder instance. */ setCallingEnabled(enabled: boolean): this; /** * Sets custom CallAppSettings for Calls SDK initialization. * If not set, the UIKit builds default settings from appId and region. * * @example * ```typescript * new UIKitSettingsBuilder() * .setCallingEnabled(true) * .setCallAppSettings({ appId: 'APP_ID', region: 'us' }) * .build(); * ``` * * @param {any} callAppSettings - The CallAppSettings object. * @returns {UIKitSettingsBuilder} The builder instance. */ setCallAppSettings(callAppSettings: any): this; } /** * Status values for message lifecycle UI events. * Matches Angular's MessageStatus enum. */ declare enum CometChatMessageStatus { /** Message is being sent (optimistic, before SDK confirmation). */ inprogress = "inprogress", /** Message was sent and confirmed by the SDK. */ success = "success", /** Message send/edit failed. */ error = "error", /** Operation was cancelled by the user (e.g., closed edit/reply preview). */ cancelled = "cancelled" } /** * Discriminated union of all SDK events emitted by the CometChat SDK listeners. * These events originate from the network (other users, other tabs/devices). */ type CometChatSDKEvent = { type: 'message/text-received'; message: CometChat.TextMessage; } | { type: 'message/media-received'; message: CometChat.MediaMessage; } | { type: 'message/custom-received'; message: CometChat.CustomMessage; } | { type: 'message/interactive-received'; message: CometChat.InteractiveMessage; } | { type: 'message/card-received'; message: CometChat.BaseMessage; } | { type: 'message/ai-assistant-received'; message: CometChat.BaseMessage; } | { type: 'message/edited'; message: CometChat.BaseMessage; } | { type: 'message/deleted'; message: CometChat.BaseMessage; } | { type: 'message/moderated'; message: CometChat.BaseMessage; } | { type: 'receipt/delivered'; receipt: CometChat.MessageReceipt; } | { type: 'receipt/read'; receipt: CometChat.MessageReceipt; } | { type: 'receipt/delivered-to-all'; receipt: CometChat.MessageReceipt; } | { type: 'receipt/read-by-all'; receipt: CometChat.MessageReceipt; } | { type: 'reaction/added'; event: CometChat.ReactionEvent; } | { type: 'reaction/removed'; event: CometChat.ReactionEvent; } | { type: 'typing/started'; indicator: CometChat.TypingIndicator; } | { type: 'typing/ended'; indicator: CometChat.TypingIndicator; } | { type: 'user/online'; user: CometChat.User; } | { type: 'user/offline'; user: CometChat.User; } | { type: 'group/member-joined'; action: CometChat.Action; joinedUser: CometChat.User; joinedGroup: CometChat.Group; } | { type: 'group/member-left'; action: CometChat.Action; leftUser: CometChat.User; leftGroup: CometChat.Group; } | { type: 'group/member-kicked'; action: CometChat.Action; kickedUser: CometChat.User; kickedBy: CometChat.User; kickedFrom: CometChat.Group; } | { type: 'group/member-banned'; action: CometChat.Action; bannedUser: CometChat.User; bannedBy: CometChat.User; bannedFrom: CometChat.Group; } | { type: 'group/member-unbanned'; action: CometChat.Action; unbannedUser: CometChat.User; unbannedBy: CometChat.User; unbannedFrom: CometChat.Group; } | { type: 'group/member-added'; action: CometChat.Action; addedBy: CometChat.User; addedUser: CometChat.User; addedTo: CometChat.Group; } | { type: 'group/member-scope-changed'; action: CometChat.Action; changedUser: CometChat.User; newScope: string; oldScope: string; changedGroup: CometChat.Group; } | { type: 'call/incoming'; call: CometChat.Call; } | { type: 'call/accepted'; call: CometChat.Call; } | { type: 'call/rejected'; call: CometChat.Call; } | { type: 'call/cancelled'; call: CometChat.Call; } | { type: 'call/ended'; call: CometChat.Call; } | { type: 'connection/connected'; } | { type: 'connection/disconnected'; }; /** * Discriminated union of UI events published by components for local * cross-component communication. Prefixed with `ui:` to distinguish * from SDK events. * */ type CometChatUIEvent = { type: 'ui:message/sent'; message: CometChat.BaseMessage; status: CometChatMessageStatus.inprogress | CometChatMessageStatus.success | CometChatMessageStatus.error; } | { type: 'ui:message/deleted'; message: CometChat.BaseMessage; } | { type: 'ui:message/read'; message: CometChat.BaseMessage; } | { type: 'ui:conversation/read'; conversationId: string; } | { type: 'ui:conversation/updated'; conversation: CometChat.Conversation; } | { type: 'ui:active-chat/changed'; user?: CometChat.User; group?: CometChat.Group; message?: CometChat.BaseMessage; unreadMessageCount?: number; } | { type: 'ui:compose/edit'; message: CometChat.BaseMessage; status: CometChatMessageStatus; parentMessageId?: number | null | undefined; } | { type: 'ui:compose/reply'; message: CometChat.BaseMessage; status: CometChatMessageStatus.inprogress | CometChatMessageStatus.success | CometChatMessageStatus.cancelled; parentMessageId?: number | null | undefined; } | { type: 'ui:compose/text'; text: string; } | { type: 'ui:compose/recording-started'; composerInstanceId: string; } | { type: 'ui:user/blocked'; user: CometChat.User; } | { type: 'ui:user/unblocked'; user: CometChat.User; } | { type: 'ui:group/created'; group: CometChat.Group; } | { type: 'ui:group/left'; group: CometChat.Group; } | { type: 'ui:group/deleted'; group: CometChat.Group; } | { type: 'ui:group/member-joined'; joinedUser: CometChat.User; joinedGroup: CometChat.Group; } | { type: 'ui:group/member-added'; messages: CometChat.Action[]; group: CometChat.Group; } | { type: 'ui:group/member-kicked'; message: CometChat.Action; user: CometChat.User; group: CometChat.Group; } | { type: 'ui:group/member-banned'; message: CometChat.Action; user: CometChat.User; group: CometChat.Group; } | { type: 'ui:group/member-unbanned'; message?: CometChat.Action; user: CometChat.User; group: CometChat.Group; } | { type: 'ui:group/member-scope-changed'; message: CometChat.Action; user: CometChat.User; group: CometChat.Group; newScope: string; } | { type: 'ui:group/ownership-changed'; group: CometChat.Group; newOwner: CometChat.User; previousOwnerUid: string; } | { type: 'ui:thread/opened'; parentMessage: CometChat.BaseMessage; } | { type: 'ui:thread/closed'; } | { type: 'ui:call/outgoing'; call: CometChat.Call; } | { type: 'ui:call/rejected'; call: CometChat.Call; } | { type: 'ui:call/ended'; call?: CometChat.Call; } | { type: 'ui:call/accepted'; call: CometChat.Call; } | { type: 'ui:call/join'; sessionId: string; message: CometChat.BaseMessage; } | { type: 'ui:conversation/deleted'; conversation: CometChat.Conversation; } | { type: 'ui:card/action'; message: CometChat.BaseMessage; action: CometChatCardAction; } | { type: 'ui:open-chat'; user?: CometChat.User; group?: CometChat.Group; } | { type: 'ui:panel/show'; position: 'messageListFooter' | 'messageListHeader'; panel: 'smartReplies' | 'conversationSummary' | 'conversationStarters'; } | { type: 'ui:panel/hide'; position: 'messageListFooter' | 'messageListHeader'; }; /** All CometChat events — SDK (from network) + UI (from local actions). */ type CometChatEvent = CometChatSDKEvent | CometChatUIEvent; /** * CometChatUIKit — static facade for initializing and interacting with the UIKit. * * Provides a single entry point for: * - SDK initialization (with UIKit-specific configuration) * - User login/logout with session resumption * - Plugin registry management * - Calling SDK initialization * - Convenience send methods (for non-React usage) * * Usage: * ```typescript * import { CometChatUIKit, UIKitSettingsBuilder } from '@cometchat/chat-uikit-react'; * * const settings = new UIKitSettingsBuilder() * .setAppId('APP_ID') * .setRegion('us') * .setAuthKey('AUTH_KEY') * .subscribePresenceForAllUsers() * .setCallingEnabled(true) * .build(); * * await CometChatUIKit.init(settings); * const user = await CometChatUIKit.login('superhero1'); * ``` */ declare class CometChatUIKit { private static _settings; private static _loggedInUser; private static _initialized; /** Settings from the initFromSettings() (ai-agent) path; routes the Calls SDK through initFromSettings too. Null on plain init(). */ private static _callsInitSettings; private static _callingReady; private static _loginListenerId; private static _conversationUpdateSettings; private static _emit; /** * Register the emit function from CometChatEventsProvider. * Called internally by the provider on mount/unmount. */ static _setEmit(fn: ((event: CometChatEvent) => void) | null): void; /** Returns the UIKit settings used during initialization. */ static getSettings(): UIKitSettings | null; /** Returns the currently logged-in user (synchronous). */ static getLoggedInUser(): CometChat.User | null; /** Returns whether the SDK has been initialized. */ static isInitialized(): boolean; /** Returns whether the Calls SDK is ready. */ static isCallingReady(): boolean; /** Returns the conversation update settings fetched from the dashboard. */ static getConversationUpdateSettings(): CometChat.ConversationUpdateSettings | null; /** * Initialize the CometChat SDK and UIKit. * * This: * 1. Validates settings * 2. Builds AppSettings from UIKitSettings * 3. Calls CometChat.init() * 4. Sets source metadata for analytics * 5. Sets up plugin registry * 6. Resumes existing session (if any) * 7. Initializes Calls SDK (if enabled) */ static init(settings: UIKitSettings): Promise<CometChat.User | null>; /** * @internal * File-based init for AI agent skills. * Calls CometChat.initFromSettings(settings) which sets * integrationSource = "ai-agent" in persistent storage. * * This method is completely independent of init() — new→new, old→old. * Regular init(uikitSettings) does NOT set the integrationSource flag. */ static initFromSettings(settings: CometChat.CometChatSettings): Promise<CometChat.User | null>; /** * Log in a user by UID. * Requires authKey to be set in UIKitSettings. */ static login(uid: string): Promise<CometChat.User>; /** * Log in a user with an auth token. */ static loginWithAuthToken(authToken: string): Promise<CometChat.User>; /** * Log out the current user. */ static logout(): Promise<void>; /** * Create a new user. * Requires authKey in UIKitSettings. */ static createUser(user: CometChat.User): Promise<CometChat.User>; /** * Update an existing user. * Requires authKey in UIKitSettings. */ static updateUser(user: CometChat.User): Promise<CometChat.User>; /** * Send a text message with optimistic UI updates. * Emits 'ui:message/sent' at each stage (inprogress → success/error). */ static sendTextMessage(message: CometChat.TextMessage): Promise<CometChat.BaseMessage>; /** * Send a media message with optimistic UI updates. * Emits 'ui:message/sent' at each stage (inprogress → success/error). */ static sendMediaMessage(message: CometChat.MediaMessage): Promise<CometChat.BaseMessage>; /** * Send a custom message with optimistic UI updates. * Emits 'ui:message/sent' at each stage (inprogress → success/error). */ static sendCustomMessage(message: CometChat.CustomMessage): Promise<CometChat.BaseMessage>; /** Post-login initialization: calls SDK, conversation settings, login listener. */ private static _postLogin; /** Attach SDK login listener to track login/logout from other tabs or direct SDK calls. */ private static _attachLoginListener; /** Initialize the Calls SDK. */ private static _initCalling; /** Prepare a message for sending (set muid, sentAt, sender). */ private static _prepareMessage; /** Throw if not initialized. */ private static _checkInitialized; } /** * CometChatCalls — dynamic import wrapper for the optional Calls SDK. * * The Calls SDK (`@cometchat/calls-sdk-javascript`) is an optional peer dependency. * This module attempts to import it. If unavailable (not installed, * test environment, SSR), `CometChatUIKitCalls` will be `null`. * * In ESM/Vite environments, `require()` is not available. The SDK is loaded * asynchronously via `loadCallsSDK()` called from `CometChatUIKit._initCalling()` * or `CometChatProvider`'s calling init effect. * * Usage: * ```typescript * import { CometChatUIKitCalls } from '@cometchat/chat-uikit-react'; * * if (CometChatUIKitCalls) { * // Initialize with plain object * await CometChatUIKitCalls.init({ appId: 'APP_ID', region: 'us' }); * * // Login (after Chat SDK login) * await CometChatUIKitCalls.loginWithAuthToken(authToken); * * // Generate token and join session * const { token } = await CometChatUIKitCalls.generateToken(sessionId); * CometChatUIKitCalls.joinSession(token, callSettings, element); * * // Register event listeners * const unsub = CometChatUIKitCalls.addEventListener('onSessionLeft', () => { }); * * // Leave session * CometChatUIKitCalls.leaveSession(); * } * ``` */ /** * The Calls SDK reference. Starts as `null` and is populated either: * 1. Synchronously via `require()` in CJS/webpack environments * 2. Asynchronously via `loadCallsSDK()` after dynamic import in ESM/Vite environments */ declare let CometChatUIKitCalls: any; /** * Dynamically load the Calls SDK in ESM/Vite environments. * * Uses a literal specifier so Vite's dev server and bundler resolve it * correctly when the package is installed. When not installed, the * `optionalPeerDependency` Vite plugin (in vite.config.ts) intercepts the * import and returns a virtual empty module instead of throwing a build error. * The null-check below handles that case at runtime. * * Returns the resolved CometChatCalls object, or null if not installed. */ declare function loadCallsSDK(): Promise<any>; /** * Initialize the Calls SDK reference. * Call this after the SDK is loaded asynchronously (e.g., via dynamic import). * The CometChatUIKit class and CometChatProvider call this during initialization. */ declare function initCallsSDK(sdk: any): void; /** Supported theme values. */ type CometChatTheme = 'light' | 'dark'; /** Context value for theme. */ interface CometChatThemeContextValue { /** Current theme. */ theme: CometChatTheme; /** Toggle or set theme programmatically. */ setTheme: (theme: CometChatTheme) => void; } /** Props for CometChatThemeProvider. */ interface CometChatThemeProviderProps { /** * The active theme. Controls the `data-theme` attribute on the wrapper. * CSS custom properties in css-variables.css respond to this attribute. * Default: 'light'. */ theme?: CometChatTheme; /** Children. */ children: ReactNode; } /** * Cross-cutting display settings used by multiple components. * * Set once at the provider level, read by any component via `useGlobalConfig()`. * Individual component props override these values when explicitly set. */ interface CometChatGlobalConfig { /** Hide read receipt indicators across all components. Default: false. */ hideReceipts?: boolean; /** Hide user online/offline status across all components. Default: false. */ hideUserStatus?: boolean; /** Disable sound for incoming/outgoing calls. Default: false. */ disableSoundForCalls?: boolean; /** Custom sound URL for calls. */ customSoundForCalls?: string; /** Disable sound for incoming messages across all components. Default: false. */ disableSoundForMessages?: boolean; /** Custom sound URL for incoming messages. */ customSoundForMessages?: string; /** * Custom call settings builder for ongoing call sessions. * Passed to OngoingCall component when a call is started. * If not set, the component creates default settings internally. */ callSettingsBuilder?: any; } /** * Abstract base class for text formatters. * * Formatters detect patterns in text and apply formatting transformations. * They can be chained together — each formatter receives the output of the * previous one. Formatters are applied in order of their `priority` property * (lower = earlier in pipeline). * * Formatters handle ONLY bubble display (text → HTML). Composer input * handling and message metadata are separate concerns. * * @example * ```typescript * class HashtagFormatter extends CometChatTextFormatter { * readonly id = 'hashtag-formatter'; * priority = 50; * getRegex() { return /(#\w+)/g; } * format(text: string): string { * this.originalText = text; * this.formattedText = text.replace(this.getRegex(), '<span class="hashtag">$1</span>'); * return this.formattedText; * } * } * ``` */ declare abstract class CometChatTextFormatter { /** Formatter priority (lower = earlier in pipeline). Default is 100. */ priority: number; /** Unique identifier for this formatter. */ abstract readonly id: string; /** The original unformatted text. */ protected originalText: string; /** The formatted text after applying transformations. */ protected formattedText: string; /** Metadata extracted during formatting (e.g., mentions, URLs). */ protected metadata: Record<string, unknown>; /** Get the regex pattern for detecting formattable content. */ abstract getRegex(): RegExp; /** * Format the input text by applying transformations. * Must store originalText, apply transformations, store formattedText, and return it. */ abstract format(text: string): string; /** Get the formatted text after format() has been called. */ getFormattedText(): string; /** Get the original unformatted text. */ getOriginalText(): string; /** Get metadata extracted during formatting. */ getMetadata(): Record<string, unknown>; /** Reset the formatter state. */ reset(): void; /** * Check if this formatter should process the given text. * Override to conditionally skip formatting. Default: always format. */ shouldFormat(_text: string, // eslint-disable-line @typescript-eslint/no-unused-vars _message?: CometChat.BaseMessage): boolean; } /** Alignment of a message bubble in the message list. */ type CometChatMessageBubbleAlignment = 'left' | 'right' | 'center'; /** A single option in the message context menu (long-press / hover menu). */ interface CometChatMessageOption { /** Unique identifier (e.g., 'react', 'reply', 'copy', 'edit', 'delete'). */ id: string; /** Display title (localized). */ title: string; /** Icon URL or inline SVG string. */ iconURL?: string; /** Callback when the option is selected. */ onClick: (message: CometChat.BaseMessage) => void; /** Show only for messages sent by the logged-in user. */ senderOnly?: boolean; /** Show only for messages NOT sent by the logged-in user. */ receiverOnly?: boolean; /** Show only in group conversations. */ groupOnly?: boolean; } /** Context passed to every plugin method. Contains the current user, conversation, and UI state. */ interface CometChatMessagePluginContext { /** The currently logged-in user. */ loggedInUser: CometChat.User; /** The group (if the conversation is a group chat). Undefined for 1:1 chats. */ group?: CometChat.Group; /** Bubble alignment for the current message. */ alignment: CometChatMessageBubbleAlignment; /** Batch position within a multi-attachment batch group ('first'|'middle'|'last'|'single'). */ batchPosition?: 'first' | 'middle' | 'last' | 'single'; /** Current theme. */ theme: 'light' | 'dark'; /** Localization function. Returns the translated string for a given key. */ getLocalizedString?: (key: string) => string; /** Delete a message. Shows confirm dialog, then calls SDK. */ onDeleteMessage?: (message: CometChat.BaseMessage) => void; /** Open the flag/report dialog for a message. */ onFlagMessage?: (message: CometChat.BaseMessage) => void; /** Open thread view for a message. */ onThreadClick?: (message: CometChat.BaseMessage) => void; /** Mark a message as unread. Updates conversation unread count and last read ID. */ onMarkAsUnread?: (message: CometChat.BaseMessage) => void; /** Show a toast notification with the given text. */ showToast?: (text: string) => void; /** Disable text truncation (read more / show less) in text bubbles. */ disableTruncation?: boolean; /** Disable interaction (click handlers, options) on the bubble. Used in thread header parent bubble. */ disableInteraction?: boolean; /** Set a message into edit mode in the composer. */ onEditMessage?: (message: CometChat.BaseMessage) => void; /** Set a message as the reply-to target in the composer. */ onReplyMessage?: (message: CometChat.BaseMessage) => void; /** Open the emoji picker to react to a message. */ onReactToMessage?: (message: CometChat.BaseMessage) => void; /** Open the message information panel for a message. */ onMessageInfo?: (message: CometChat.BaseMessage) => void; /** Publish a UI event for cross-component communication. */ publish?: (event: CometChatUIEvent) => void; /** Get text formatters from the plugin registry (for caption rendering in media bubbles). */ getTextFormatters?: () => CometChatTextFormatter[]; hideReplyOption?: boolean; hideReplyInThreadOption?: boolean; hideEditMessageOption?: boolean; hideDeleteMessageOption?: boolean; hideCopyMessageOption?: boolean; hideReactionOption?: boolean; hideMessageInfoOption?: boolean; hideFlagMessageOption?: boolean; hideMessagePrivatelyOption?: boolean; hideTranslateMessageOption?: boolean; showMarkAsUnreadOption?: boolean; } /** * The core plugin interface. Every message type plugin implements this. * * A plugin owns one or more message types within one or more categories. * It provides bubble rendering, context menu options, conversation list preview, * text formatters, and composer attachment options. */ interface CometChatMessagePlugin { /** Unique plugin identifier (e.g., 'text', 'image', 'polls'). */ id: string; /** SDK message types this plugin handles (e.g., ['text'], ['image'], ['groupMember']). */ messageTypes: string[]; /** SDK message categories this plugin handles (e.g., ['message'], ['action']). */ messageCategories: string[]; /** * Render the bubble content for a message. * Returns only the inner content — the outer bubble wrapper is handled by CometChatMessageBubble. */ renderBubble(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): ReactNode; /** * Return context menu options for a message. * Return an empty array for messages that have no options (e.g., group actions, deleted). */ getOptions?(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): CometChatMessageOption[]; /** * Return a plain-text preview for the conversation list subtitle. * Must return plain text — no HTML, no markdown. Truncate to ~100 chars. * @param t - Optional localization function. Use it to translate preview strings. */ getLastMessagePreview?(message: CometChat.BaseMessage, loggedInUser: CometChat.User, t?: (key: string) => string): string; /** * Return text formatters this plugin provides. * Only relevant for the text plugin. Other plugins return undefined or []. */ getTextFormatters?(): CometChatTextFormatter[]; /** * Render the leading view (avatar area) for a message bubble. * Default: avatar for incoming messages in group chats. */ renderLeadingView?(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): ReactNode; /** * Render the header view (sender name area) for a message bubble. * Default: sender name for incoming messages in group chats. */ renderHeaderView?(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): ReactNode; /** * Render the footer view (below content, e.g., reactions) for a message bubble. * Default: CometChatReactions when the message has reactions. */ renderFooterView?(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): ReactNode; /** * Render the bottom view (moderation/error footer) for a message bubble. * Default: CometChatModerationView for disapproved or permission-denied messages. */ renderBottomView?(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): ReactNode; /** * Render the status info view (timestamp, receipts, "edited") for a message bubble. * Default: timestamp + delivery/read receipts + "edited" indicator. */ renderStatusInfoView?(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): ReactNode; /** * Render the reply view (quoted message preview) for a message bubble. * Default: CometChatMessageReplyPreview when the message has a quoted message. */ renderReplyView?(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): ReactNode; /** * Render the thread view (reply count indicator) for a message bubble. * Default: CometChatThreadView with reply count. */ renderThreadView?(message: CometChat.BaseMessage, context: CometChatMessagePluginContext): ReactNode; } /** * Types for the CometChatProvider — context composition for the UIKit. */ /** Props for the root CometChatProvider. */ interface CometChatProviderProps { /** Additional plugins beyond the default set. Merged with defaultPlugins internally. */ plugins?: CometChatMessagePlugin[]; /** * Plugins to exclude — including defaults. Each entry is matched against every * plugin's `messageTypes`/`messageCategories`: a plugin is removed when its * `messageTypes` includes `text` AND its `messageCategories` includes `category`. * * ```tsx * <CometChatProvider removePlugins={[{ text: 'extension_poll', category: 'custom' }]}> * ``` */ removePlugins?: { text: string; category: string; }[]; /** Global config overrides (hideReceipts, hideUserStatus, etc.). */ config?: CometChatGlobalConfig; /** Theme: 'light' or 'dark'. Default: 'light'. */ theme?: CometChatTheme; /** Locale override (e.g., 'en', 'fr', 'de'). Default: browser language. */ locale?: string; children: ReactNode; } declare const CometChatProvider: React__default.FC<CometChatProviderProps>; /** * useLoggedInUser — get the logged-in user. * * Reads synchronously from CometChatUIKit first (instant if init+login was done via UIKit class). * Falls back to async CometChat.getLoggedinUser() for cases where the SDK was initialized directly. * SSR-safe: returns null if no user is available. * * Use this in components that can render without a user (graceful degradation). * For components that REQUIRE a user, check the return value and handle null. */ declare function useLoggedInUser(): CometChat.User | null; interface CometChatFrameContextValue { iframeDocument: Document | null; iframeWindow: Window | null; iframe: HTMLIFrameElement | null; } interface CometChatFrameProviderProps { children: ReactNode; iframeId: string; } declare const useCometChatFrameContext: () => CometChatFrameContextValue; declare const CometChatFrameProvider: React__default.FC<CometChatFrameProviderProps>; /** * Log level enum defining verbosity levels. * Ordered from least verbose (none) to most verbose (debug). */ declare enum LogLevel { none = 0, error = 1, warn = 2, info = 3, debug = 4 } /** Sets the active log level. Only messages at this level or below are output. */ declare function setLogLevel(level: LogLevel): void; /** Returns the current log level. */ declare function getLogLevel(): LogLevel; /** Logs an error message if the current level permits. */ declare function error(tag: string, message: string, ...args: unknown[]): void; /** Logs a warning message if the current level permits. */ declare function warn(tag: string, message: string, ...args: unknown[]): void; /** Logs an informational message if the current level permits. */ declare function info(tag: string, message: string, ...args: unknown[]): void; /** Logs a debug message if the current level permits. */ declare function debug(tag: string, message: string, ...args: unknown[]): void; /** * Centralized logging utility for the CometChat UIKit. * All internal logging goes through this object so consumers can control verbosity. * * @example * ```ts * import { CometChatLogger, LogLevel } from '@cometchat/chat-uikit-react'; * CometChatLogger.setLogLevel(LogLevel.debug); * ``` */ declare const CometChatLogger: { readonly setLogLevel: typeof setLogLevel; readonly getLogLevel: typeof getLogLevel; readonly error: typeof error; readonly warn: typeof warn; readonly info: typeof info; readonly debug: typeof debug; }; /** * CometChatUIKitUtility — utility class providing helper methods * such as deep cloning, ID generation, and Unix timestamp retrieval. * */ /** * Creates a deep copy of the value provided. * * @remarks * This function cannot copy truly private properties (those that start with a "#" symbol inside a class block). * Functions are copied by reference and additional properties on array objects are ignored. * * @param arg - Any value * @returns A deep copy of `arg` */ declare function clone<T>(arg: T): T; /** * Generates a unique ID. * @returns A unique string identifier. */ declare function generateId(): string; /** * Retrieves the current Unix timestamp (seconds). * @returns The Unix timestamp. */ declare function getUnixTimestamp(): number; /** * Creates a CometChat.Action message for group member actions. * * @param actionOn - The group member the action is performed on * @param action - The action string (e.g., 'kicked', 'banned', 'added', 'scopeChanged') * @param group - The group where the action occurred * @param loggedInUser - The user performing the action * @returns A properly constructed CometChat.Action message */ declare function createActionMessage(actionOn: CometChat.GroupMember | CometChat.User, action: string, group: CometChat.Group, loggedInUser: CometChat.User): CometChat.Action; declare const CometChatUIKitUtility: { clone: typeof clone; ID: typeof generateId; getUnixTimestamp: typeof getUnixTimestamp; createActionMessage: typeof createActionMessage; }; /** Batch position within a multi-attachment batch group. */ type BatchPosition = 'first' | 'middle' | 'last' | 'single'; /** * Reads the `batchId` from a message's metadata, null-guarded. * Returns `undefined` if the message has no batchId. */ declare function getMessageBatchId(message: CometChat.BaseMessage | undefined | null): string | undefined; /** * Computes the batch position of a message given its immediate neighbors. * * Groups consecutive messages by comparing each message's `batchId` to only its * immediate previous and next neighbors (R6.1). The result drives chrome * suppression in the renderer: * * | Position | Avatar+Name | StatusInfo | * |----------|-------------|------------| * | first | show | suppress | * | middle | suppress | suppress | * | last | suppress | show | * | single | show | show | * * Voice notes have no batchId → always 'single'. */ declare function computeBatchPosition(prev: CometChat.BaseMessage | undefined | null, current: CometChat.BaseMessage | undefined | null, next: CometChat.BaseMessage | undefined | null): BatchPosition; /** A single action item rendered inside the sheet. */ interface CometChatActionSheetItemData { /** Unique identifier. */ id: string; /** Display title. */ title: string; /** Icon element (SVG or ReactNode). */ icon?: ReactNode; /** Callback when item is selected. */ onClick: () => void; /** Optional secondary text. */ subtitle?: string; /** Whether the item is disabled. */ disabled?: boolean; /** Optional custom className. */ className?: string; } /** Layout mode for the action sheet. */ type CometChatActionSheetLayoutMode = 'list' | 'grid'; /** Props for ActionSheetRoot. */ interface CometChatActionSheetRootProps { /** Whether the sheet is open. */ isOpen: boolean; /** Callback when the sheet requests to close (backdrop click, Escape key). */ onClose: () => void; /** Layout mode. Defaults to 'list'. */ layoutMode?: CometChatActionSheetLayoutMode; /** Optional title displayed in the header. */ title?: string; /** Children (ActionSheet.Item elements or custom content). */ children: ReactNode; /** Optional custom className for the root container. */ className?: string; } /** Props for ActionSheetItem. */ interface CometChatActionSheetItemProps { /** The action item data. */ item: CometChatActionSheetItemData; /** Optional custom className. */ className?: string; } /** Props for ActionSheetHeader. */ interface CometChatActionSheetHeaderProps { /** Title text. */ title?: string; /** Optional close button callback. */ onClose?: () => void; /** Children for custom header content. */ children?: ReactNode; } /** Props for ActionSheetLayout. */ interface CometChatActionSheetLayoutProps { /** Layout mode: list (vertical) or grid (icon grid). Defaults to 'list'. */ mode?: CometChatActionSheetLayoutMode; /** Children (ActionSheet.Item elements). */ children: ReactNode; } /** Context value for ActionSheet. */ interface CometChatActionSheetContextValue { isOpen: boolean; onClose: () => void; layoutMode: CometChatActionSheetLayoutMode; } /** * Flat API props for CometChatActionSheet. * Renders Root + Header + Layout with Items in one call. */ interface CometChatActionSheetProps extends Omit<CometChatActionSheetRootProps, 'children' | 'title'> { /** Header title. */ title?: string; /** Callback for the header close button. Defaults to onClose. */ onHeaderClose?: () => void; /** Items to render in the sheet layout. */ items?: CometChatActionSheetItemData[]; } declare const CometChatActionSheet: React__default.FC<CometChatActionSheetProps> & { Root: React__default.FC<CometChatActionSheetRootProps>; Item: React__default.FC<CometChatActionSheetItemProps>; Header: React__default.FC<CometChatActionSheetHeaderProps>; Layout: React__default.FC<CometChatActionSheetLayoutProps>; }; declare function useCometChatActionSheetContext(): CometChatActionSheetContextValue; /** Visual variant of the button. */ type CometChatButtonVariant = 'primary' | 'secondary' | 'ghost'; /** Size variant of the button. */ type CometChatButtonSize = 'sm' | 'md' | 'lg'; /** Props for CometChatButton.Root. */ interface CometChatButtonRootProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children'> { /** Visual variant. Defaults to 'primary'. */ variant?: CometChatButtonVariant; /** Size variant. Defaults to 'md'. */ size?: CometChatButtonSize; /** Whether the button is in a loading state. */ isLoading?: boolean; /** Accessible label for the loading state. */ loadingLabel?: string; /** Tooltip text shown on hover (maps to native title attribute). */ hoverText?: string; /** Children (CometChatButton.Icon, CometChatButton.Text, or custom content). */ children: ReactNode; /** Optional custom className. */ className?: string; } /** Props for CometChatButton.Icon. */ interface CometChatButtonIconProps { /** Icon content — accepts ReactNode (SVG component, img, etc.). */ children: ReactNode; /** Optional custom className. */ className?: string; } /** Props for CometChatButton.Text. */ interface CometChatButtonTextProps { /** Text content. */ children: ReactNode; /** Optional custom className. */ className?: string; } /** Context value for CometChatButton. */ interface CometChatButtonContextValue { variant: CometChatButtonVariant; size: CometChatButtonSize; isLoading: boolean; disabled: boolean; } /** * Flat API props for CometChatButton. * Renders Root + optional Icon + optional Text in one call. */ interface CometChatButtonProps extends Omit<CometChatButtonRootProps, 'children'> { /** Icon content (SVG component, img, etc.). Rendered inside CometChatButton.Icon. */ icon?: React__default.ReactNode; /** Text content. Rendered inside CometChatButton.Text. */ text?: React__default.ReactNode; } declare const CometChatButton: React__default.ForwardRefExoticComponent<CometChatButtonProps & React__default.RefAttributes<HTMLButtonElement>> & { Root: React__default.ForwardRefExoticComponent<CometChatButtonRootProps & React__default.RefAttributes<HTMLButtonElement>>; Icon: React__default.FC<CometChatButtonIconProps>; Text: React__default.FC<CometChatButtonTextProps>; }; declare function useCometChatButtonContext(): CometChatButtonContextValue; /** Event payload emitted on checkbox state change. */ interface CometChatCheckboxChangeEvent { /** Whether the checkbox is now checked. */ checked: boolean; /** The label text, if provided. */ label?: string; /** Whether the Shift key was held during the click. */ shiftKey?: boolean; /** Whether the Meta/Cmd key was held during the click. */ metaKey?: boolean; } /** Props for CometChatCheckbox. */ interface CometChatCheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'type' | 'children'> { /** Whether the checkbox is checked (controlled mode). */ checked?: boolean; /** Default checked state (uncontrolled mode). */ defaultChecked?: boolean; /** Label text displayed next to the checkbox. */ label?: string; /** Whether the checkbox is disabled. */ disabled?: boolean; /** Callback fired when the checkbox value changes. */ onChange?: (event: CometChatCheckboxChangeEvent) => void; /** Optional custom className. */ className?: string; } /** * CometChatCheckbox — a controlled/uncontrolled checkbox with support * for shift/meta key detection (used for range-select in list components). * * Usage: * ```tsx * <CometChatCheckbox * checked={isSelected} * label="Select" * onChange={({ checked, shiftKey }) => handleSelect(checked, shiftKey)} * /> * ``` */ declare const CometChatCheckbox: React__default.ForwardRefExoticComponent<CometChatCheckboxProps & React__default.RefAttributes<HTMLInputElement>>; /** Event payload emitted on radio button state change. */ interface CometChatRadioButtonChangeEvent { /** Whether the radio button is now checked. */ checked: boolean; /** The label text, if provided. */ label?: string | undefined; /** The value of the radio button. */ value?: string | undefined; } /** Props for CometChatRadioButton. */ interface CometChatRadioButtonProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'type' | 'children'> { /** Whether the radio button is checked (controlled mode). */ checked?: boolean; /** Default checked state (uncontrolled mode). */ defaultChecked?: boolean; /** Label text displayed next to the radio button. */ label?: string; /** Whether the radio button is disabled. */ d