diff --git a/ANDROID-DOCS-AUDIT.md b/ANDROID-DOCS-AUDIT.md new file mode 100644 index 000000000..a84ef5f89 --- /dev/null +++ b/ANDROID-DOCS-AUDIT.md @@ -0,0 +1,418 @@ +# Android docs audit — UI Kit v6 + Chat SDK v5 + +Every entry below was found by **mechanically diffing the docs against the shipped source**, not by +reading. Each row names the source file + line that proves it. Raised while building the Android +skill pack (Linear ENG-38207). + +## Source of truth used +| Surface | Repo / artifact | Version | +|---|---|---| +| UI Kit v6 | `cometchat-team/uikit-android` — `chatuikit-kotlin`, `chatuikit-compose`, `chatuikit-core` | 6.0.5 (`master-v6`) | +| Chat SDK v5 | `cometchat-team/chat-sdk-android` (+ installed AAR) | 5.0.5 | + +**Method:** extract every `.setX(...)` call from each page's `Kotlin (XML Views)` tab → check it +against every `fun` declared in the three kit modules → subtract Android-framework methods. 120 +documented setters checked; the misses below are what remained. + +**Reproduce:** `python3` extractor in the ENG-38207 working notes; re-runnable against any kit tag. + +--- + +## A. Wrong method name — documented call does not compile +| # | Page | Docs say | Shipped 6.0.5 | Evidence | +|---|---|---|---|---| +| A1 | `ui-kit/android/incoming-call` | `setOnAcceptClick { }` | `setOnAcceptClickListener(OnClick?)` | `chatuikit-kotlin/.../incomingcall/CometChatIncomingCall.kt:489` | +| A2 | `ui-kit/android/incoming-call` | `setOnRejectClick { }` | `setOnRejectClickListener(OnClick?)` | `…/incomingcall/CometChatIncomingCall.kt:507` | +| A3 | `ui-kit/android/outgoing-call` | `setOnEndCallClick { }` | `setOnEndCallClickListener(OnClick?)` | `…/outgoingcall/CometChatOutgoingCall.kt:493` | +| A4 | `ui-kit/android/message-composer` | `setAuxiliaryButtonView(...)` | `setAuxiliaryButtonViewListener(MessageComposerViewHolderListener)` | `…/messagecomposer/ui/CometChatMessageComposer.kt:5627` | +| A5 | `ui-kit/android/guide-ai-agent` | `messageHeader.setNewChatButtonClick { }` | `setOnNewChatClick(() -> Unit)` | `…/messageheader/ui/CometChatMessageHeader.kt:627` | +| A6 | `ui-kit/android/guide-ai-agent` | `messageHeader.setChatHistoryButtonClick { }` | `setOnChatHistoryClick(() -> Unit)` | `…/messageheader/ui/CometChatMessageHeader.kt:631` | +| A7 | `ui-kit/android/guide-threaded-messages` | `messageList.setParentMessage(it.id)` | `setParentMessageId(Long)` | `…/messagelist/ui/CometChatMessageList.kt:1709` | +| A8 | `ui-kit/android/message-list` | `mentionFormatter.setMessageListMentionTextStyle(context, style)` | no such method — use `setIncomingBubbleMentionTextStyle` / `setOutgoingBubbleMentionTextStyle` | `…/shared/formatters/CometChatMentionsFormatter.kt:166,182` | + +## B. Wrong signature — right name, wrong arity/params +| # | Page | Docs say | Shipped 6.0.5 | Evidence | +|---|---|---|---|---| +| B1 | `guide-threaded-messages`, `message-list` | `setOnThreadRepliesClick { context, baseMessage, template -> }` (3 args) | `((BaseMessage) -> Unit)?` — **one** arg | `…/messagelist/ui/CometChatMessageList.kt:3727` | +| B2 | `ui-kit/android/message-composer` | `setOnSendButtonClick { context, baseMessage -> }` | `(String) -> Unit` — the typed text | `…/messagecomposer/ui/CometChatMessageComposer.kt:5395` | +| B3 | `ui-kit/android/message-composer` (Compose tab) | `onError = { context, exception -> }` | `((CometChatException) -> Unit)` — one arg | `chatuikit-compose/.../CometChatMessageComposer.kt` | + +## C. Removed API — page documents a v5 surface that no longer ships +| # | Page | Issue | Replacement in v6 | Evidence | +|---|---|---|---|---| +| C1 | `ui-kit/android/message-template` | **The whole page.** `CometChatMessageTemplate()`, `setType`, `setCategory`, `setBubbleView`, `setMessageReceipt`, `setTemplates` — none exist in 6.0.5 (only the unrelated `UIKitConstants.MessageTemplateId`) | **`BubbleFactory`** — subclass it (`getCategory()`, `getType()`, `createContentView()`, `bindContentView()`) and register with `messageList.setBubbleFactories(listOf(...))` | `chatuikit-kotlin/.../shared/messagebubble/BubbleFactory.kt`; registration at `…/messagelist/ui/CometChatMessageList.kt:3475` | + +## D. Stale guidance — compiles, but teaches the wrong default +| # | Page | Issue | Should be | +|---|---|---|---| +| D1 | `getting-started-kotlin`, `getting-started-jetpack` | Teach `UIKitSettings.UIKitSettingsBuilder()` + `CometChatUIKit.init(...)` with `APP_ID`/`AUTH_KEY` as **hardcoded source constants** | `CometChatUIKit.initFromSettings(context, callback)` reading a **gitignored** `app/src/main/assets/cometchat-settings.json`. The shipped kit implements it (`chatuikit-core/.../CometChatUIKit.kt:121`) and it persists `integrationSource` telemetry + auto-inits the Calls SDK. Hardcoded credentials in a sample are also a security-guidance problem. | +| D2 | `ui-kit/android/*` component pages | Most v6 component pages have **no "AI Integration Quick Reference"** accordion (35 of 68 pages do) | Backfill, so AI agents get prop/param tables without parsing prose | +| D3 | `sdk/android/v5/*` | **Zero** of the 61 v5 SDK pages carry the accordion (all 46 that exist are on the v4 root tree) | Backfill for v5 | + +## E. Missing artifacts +| # | Item | Status | +|---|---|---| +| E1 | `ui-kit/android/llms-android-v6.mdx` — scoped LLM index for the v6 UI Kit | **Added** (this branch) | +| E2 | `sdk/android/v5/llms-android-v5.mdx` — scoped LLM index for the v5 SDK | **Added** (this branch) | + +--- + +## New findings (added during the fix pass) +| # | Page | Docs say | Shipped 6.0.5 / SDK 5.0.5 | Evidence | +|---|---|---|---|---| +| A9 | `ui-kit/android/upgrading-from-v5` | `conversations.setViewModelFactory(factory)` | `setViewModel(viewModel)` — build the VM with `ViewModelProvider(this, factory)` | `…/conversations/ui/CometChatConversations.kt:887` | +| A10 | `ui-kit/android/upgrading-from-v5` | repository interface `ConversationsRepository` with `fetchConversations()` | `ConversationListRepository` with `getConversations(...)`, `deleteConversation(...)`, `markAsDelivered(...)`, `hasMoreConversations()` | `chatuikit-core/.../domain/repository/ConversationListRepository.kt:13` | +| B4 | `ui-kit/android/upgrading-from-v5` | V6 block: `composer.setOnSendButtonClick { context, message -> }` | `(String) -> Unit` | `…/CometChatMessageComposer.kt:5395` | +| A11 | `ui-kit/android/theme-introduction` (Compose tab) | `CometChatColorScheme.light().copy(...)` / `.dark().copy(...)` | **`lightColorScheme(...)` / `darkColorScheme(...)`** — top-level factories in `com.cometchat.uikit.compose.theme`, configured by **named params**; `CometChatColorScheme` is a plain class with no `.copy()`. Setting `primary` derives the whole extended ramp. | `chatuikit-compose/.../theme/CometChatColorScheme.kt:190,325` | +| S1 | `sdk/android/v5/typing-indicators` | `CometChat.endtyping(...)` — lowercase `t`, does not compile | `CometChat.endTyping(...)` | SDK source API index | +| S2 | `sdk/android/v5/typing-indicators` | 8 tab titles read `"Strat Typing"`; the stop-typing section was also mislabelled "Start" | `Start Typing` (§send) / `Stop Typing` (§end) | copy-edit | + +--- + +## Fix log — all applied on this branch +| # | Page | Change | Verified against | +|---|---|---|---| +| A1 | `incoming-call` | `setOnAcceptClick` → `setOnAcceptClickListener` (Views only; Compose `onAcceptClick` was already correct) | source + shipped AAR | +| A2 | `incoming-call` | `setOnRejectClick` → `setOnRejectClickListener` | source | +| A3 | `outgoing-call` | `setOnEndCallClick` → `setOnEndCallClickListener` | source | +| A4 | `message-composer` | `setAuxiliaryButtonView(view)` → `setAuxiliaryButtonViewListener(object : MessageComposerViewHolderListener { createView(context, user, group) })` | `:5627` + `MessageComposerViewHolderListener.kt:39` | +| A5 | `guide-ai-agent` | `setNewChatButtonClick` → `setOnNewChatClick` | source | +| A6 | `guide-ai-agent` | `setChatHistoryButtonClick` → `setOnChatHistoryClick` | source | +| A7 | `guide-threaded-messages` | `messageList.setParentMessage(id)` → `setParentMessageId(id)` (×2; `viewModel.`/`header.setParentMessage` left alone — both correct) | source | +| A8 | `message-list` | `setMessageListMentionTextStyle` → `setIncomingBubbleMentionTextStyle` + `setOutgoingBubbleMentionTextStyle` | `CometChatMentionsFormatter.kt:166,182` | +| A9 | `upgrading-from-v5` | `setViewModelFactory(factory)` → `ViewModelProvider(this, factory)` + `setViewModel(vm)` | source | +| A10 | `upgrading-from-v5` | `ConversationsRepository.fetchConversations()` → `ConversationListRepository.getConversations()` | source | +| B1 | `guide-threaded-messages`, `message-list`, `upgrading-from-v5` | thread callback 3-arg → **1-arg** `{ baseMessage -> }` in **both** cohorts (V5 Java "before" blocks left intact) | Views `:3727`, Compose `:604` | +| B2 | `message-composer` | Views `setOnSendButtonClick { context, baseMessage -> }` → `{ text -> }` (Compose 2-arg form is correct, untouched) | `:5395` / Compose `:268` | +| B4 | `upgrading-from-v5` | same fix in the V6 "after" block | `:5395` | +| C1 | `message-template` | Added a verified `` — the page's API is absent from the shipped artifact; documented the real `BubbleFactory` + `setBubbleFactories` replacement with a source-accurate example. **Full page rewrite still owed.** | shipped AAR: no `MessageTemplate`, has `BubbleFactory` | +| S1 | `sdk/.../typing-indicators` | `CometChat.endtyping` → `endTyping` | SDK source | +| S2 | `sdk/.../typing-indicators` | `"Strat Typing"` → `Start`/`Stop Typing` (8 titles) | copy-edit | +| A11 | `theme-introduction` | `CometChatColorScheme.light()/.dark()` + `.copy()` → `lightColorScheme(...)`/`darkColorScheme(...)` with named params (4 sites) | source + **compile-proved** in harness fixture `skill-compose-families` | + +## Behaviour gaps (found by the SKILL⇄DOCS⇄SOURCE audit, not by compiling) +| # | Page | Gap | Fix | +|---|---|---|---| +| BEH-1 | `ui-kit/android/group-members` | The kit enforces a **member permission matrix** before opening the long-press menu (owner/admin/moderator/participant, plus "a moderator cannot assign admin"). The page documented scope *filtering* and *badges* but never the matrix — unknowable from the docs alone. | Added a **"Member Permissions"** section with the matrix, the scope constants, and a `` about `updateGroupMemberScope(UID, GUID, …)` vs `transferGroupOwnership(GUID, UID, …)` having **reversed** parameter order. | + +Tracked with the skill-side fixes in `cometchat-skills/THREE-WAY-AUDIT.md`. + +--- + +## Round 2 — the three-way audit (skills ↔ docs ↔ source) + +`test-suite/scripts/three-way-audit.mjs` in the skills repo compares three independent claims about +the same API. **Source is the arbiter** — the installed UI Kit, Chat SDK, Calls SDK and Cards SDK. + +| Disagreement | Meaning | Who fixes | +|---|---|---| +| in SOURCE + DOCS, not in SKILLS | skill under-teaches a real API | skill | +| in SOURCE + SKILLS, not in DOCS | docs under-teach a real API | docs | +| in DOCS or SKILLS, **not in SOURCE** | **phantom** — taught but ships nowhere | whoever teaches it | + +### Phantoms fixed in this round +| # | Page | Docs said | Shipped | Evidence | +|---|---|---|---|---| +| R1 | `ui-kit/android/group-members` | `getSelectedGroupMembers()` | **`getSelectedMembers()`** (+ `setOnSelection {}` to observe) | `CometChatGroupMembers.kt:772,1211` | +| R2 | `ui-kit/android/custom-text-formatter-guide`, `shortcut-formatter-guide`, `message-composer` | `CometChatUIKit.getDataSource().getTextFormatters(...)` / `.getAuxiliaryOption(...)` | **`getDataSource()` was removed after V5** — build the formatter list yourself and pass it to `setTextFormatters(...)`; the auxiliary slot has no "fetch the defaults" API, an override REPLACES them | `javap` on the shipped `chatuikit-core` AAR: no `getDataSource` | +| R3 | `sdk/android/v5/delivery-read-receipts` | `message.getReceiverUID()` **and** `message.getRecieverUID()` — two different wrong spellings on one page | **`getReceiverUid()`** | `BaseMessage.java:297` | +| R4 | `sdk/android/v5/additional-message-filtering` | `.setAttachmemnt(...)` (typo) on a `MessagesRequestBuilder` | **`setAttachmentTypes(...)`** — matching the page's own prose | `MessagesRequest.java:1127` | +| R5 | `sdk/android/v5/flag-message` | `reason.getReason()` | **`reason.getName()`** (`FlagReason` has `getId`/`getName`/`getDescription`) | `FlagReason.java:194` | + +### False positives the audit itself had to learn (recorded so the next platform doesn't repeat them) +- **Calls SDK / Cards SDK.** `setCallCategory`, `setCardSchema`, `setThemeMode`, `setActionCallback` + are real — they ship in `calls-sdk-android` / `cards-android`, which the first pass didn't scan. + Without that, correct docs would have been "fixed" into incorrect ones. +- **V5 "before" blocks.** A ` ```java title="V5" ` fence in `upgrading-from-v5` *should* name removed + APIs; the audit now skips them. +- **Comment lines.** Warning that "X was removed" is documentation, not a claim X exists. +- **`sdk/android/v5/` is the CURRENT SDK.** An early version of the version filter excluded it and + silently audited **zero** SDK pages — which is why R3–R5 were invisible in round 1. + +### Standing result +`PHANTOM in SKILLS = 0` — no Android skill teaches an API that does not ship. The only remaining +docs phantoms are the four in `message-template.mdx`, the page already flagged (C1) for rewrite. + +### Skill gaps (not defects) +The audit reports ~216 real APIs the docs teach that the skills never name. That is the intended +**bake-vs-fetch** split: skills bake the hot path and route everything else to the docs `.md` twin +via `core/references/docs-map.md`. Listed for visibility, not as a backlog. + +--- + +## Round 3 — the fresh-app run (built + executed on an emulator) + +A NEW app was scaffolded from nothing, following **only** the skills, installed on a booted emulator +and driven by hand. Static audits cannot find these: they only appear when the app runs. + +| # | Symptom on a real device | Root cause | Docs fix | Skill fix | +|---|---|---|---|---| +| F1 | **Build fails**, ~40 `Duplicate class org.jetbrains.annotations.*` at dexing | The kit's own transitive chain: `chatuikit-kotlin-android` → `io.noties.markwon:syntax-highlight` → `io.noties:prism4j:2.0.0` → `org.jetbrains:annotations-java5:17.0.0`, colliding with `org.jetbrains:annotations:23.0.0` from AndroidX/Kotlin | `` + `exclude(group="org.jetbrains", module="annotations-java5")` added to **both** getting-started pages | added to the core skill's install block, marked REQUIRED | +| F2 | UI Kit toolbar renders **under the status bar** — "Chats" overlaps the clock | Every recipe calls `enableEdgeToEdge()` and **nothing** consumes the insets. Docs had **zero** occurrences of `setOnApplyWindowInsetsListener` | `` + the runnable inset snippet added to `conversation-message-view` and `one-to-one-chat` | core skill's Sizing section now carries the **code**, not just the words "+ inset padding" | +| F3 | `Intent(this, …)` inside the login callback **does not compile** | Inside `object : CometChat.CallbackListener()`, `this` binds to the listener, not the Activity. The skill's snippet only had `/* unlock the chat UI */`, so it never showed the navigation a consumer writes next | — (docs don't show navigation from the callback) | core skill now shows `this@MainActivity` with an inline warning | + +**Verified working after the fixes**, on device: `init OK → login OK` → conversations list renders +with real data (avatars, unread badges, receipts, presence) → tap opens the message screen for the +right entity → back returns → keyboard opens with the composer above it → **a message sends and is +delivered**. The `cometchatPrimaryColor` from the customization skill is visibly applied. + +F1 and F2 are worth raising with the kit team too: F1 is a dependency-hygiene issue in the published +artifact (a consumer should not need to know about `prism4j`), and F2 means every published Android +recipe produces a visibly broken status bar. + +--- + +## Round 4 — component-wise acceptance on the emulator + +Each drop-in was hosted alone, sized exactly as the skills prescribe, and driven on a booted +emulator. Evidence is the UI hierarchy (`uiautomator dump`), not a screenshot impression. + +| Component | Verdict | Evidence | +|---|---|---| +| `CometChatConversations` | ✅ renders | real rows, avatars, unread badges, receipts, presence dot | +| `CometChatUsers` | ✅ renders | title, `et_search`, real users (Bob Bob, Susan Marie) | +| `CometChatGroups` | ✅ renders | `groups_item_container`, `groups_avatar`, "CometChat Team Meeting" | +| `CometChatGroupMembers` | ✅ compiles + renders | emitted by a skills-only agent; see round 5 | +| `CometChatSearch` | ✅ renders | `chip_group` (Unread/Groups/Photos), `iv_back`, `initial_state_view` | +| `CometChatNotificationFeed` | ✅ renders | "Notifications" | +| `CometChatMessageHeader/List/Composer` | ✅ renders + sends | polls, image bubbles, moderation notice; message sent + delivered | +| **`CometChatCallLogs`** | ❌ **CRASHES** | see C-1 | + +### C-1 — `CometChatCallLogs` requires the Calls SDK **and** calling to be initialized (DOCS gap) +``` +java.lang.NoClassDefFoundError: Failed resolution of: + Lcom/cometchat/calls/core/CallLogRequest$CallLogRequestBuilder; + at com.cometchat.uikit.core.viewmodel.CometChatCallLogsViewModel.(CometChatCallLogsViewModel.kt:97) +``` +**This is a documentation gap, NOT a product defect.** Two distinct runtime states, both expected: + +| Calls artifact | `uiKit.enableCalling` | Result | +|---|---|---| +| absent | anything | `NoClassDefFoundError` — correct JVM behaviour for a missing dependency | +| present | `false` | `RuntimeException: Please call the CometChatCalls.init() method …` — thrown **deliberately by the Calls SDK** (`com.cometchat.calls.core.ApiConnection.getInstance`) as actionable guidance | +| present | `true` | renders | + +Neither is the UI Kit misbehaving: a missing library cannot work, and the Calls SDK's message names +its own fix. The defect is that **`call-logs.mdx` documented the component with zero mention that the +Calls SDK is required at all** — a reader following only that page hits a runtime failure with no +warning. It compiles fine in every state, so no build gate can warn either. + +The non-obvious part worth documenting: with the UI Kit you do **not** call `CometChatCalls.init()` +yourself — `initFromSettings` does it, but **only** when `"uiKit": { "enableCalling": true }` is set +in `cometchat-settings.json`. A developer who adds the artifact and expects it to work will hit +state 2 and has no reason to connect it to a JSON flag they never set. + +| Where | Before | Now | +|---|---|---| +| `ui-kit/android/call-logs` | **zero** mentions of `calls-sdk-android` or any dependency requirement | `` with the exact stack trace + the Gradle line | +| components skills (both cohorts) | a parenthetical "(needs the calls artifact)" | explicit crash warning: compiles fine, fails at runtime | + +*(An earlier revision of this audit framed C-1 as a kit defect and recommended escalation. That was +wrong — the exception originates in the Calls SDK as intentional guidance, and a missing dependency +failing is correct behaviour. Corrected: docs-only.)* + +--- + +## Round 5 — the Compose fresh-app run + +A second fresh app, Jetpack Compose cohort, built from the `…-compose-*` skills only and run on the +emulator. The Compose recipes **compiled first time and rendered correctly** — theming +(`lightColorScheme(primary = …)`), `Scaffold(contentWindowInsets = WindowInsets.statusBars)`, +`weight(1f)` + `imePadding()` all behaved as the skills describe. One severe finding, and it is +**not** Compose-specific — it sits in the shared init path: + +### F4 — `enableCalling: true` without the Calls artifact kills the app at LAUNCH +``` +java.lang.NoClassDefFoundError: Failed resolution of: + Lcom/cometchat/calls/core/CometChatCalls$SessionSettingsBuilder; + at com.cometchat.uikit.core.CometChatUIKit.initCometChatCalls(CometChatUIKit.kt:229) + at com.cometchat.uikit.core.CometChatUIKit$initFromSettings$1.onSuccess(CometChatUIKit.kt:196) + at com.example.composechat.MainActivity.onCreate(MainActivity.kt:38) +``` +`initFromSettings` auto-initializes the Calls SDK when the flag is set. Without the dependency the +throw lands in **`onCreate`, before any UI renders** — so the symptom (app won't start at all) is +maximally distant from the cause (a boolean in a JSON file). Setting `enableCalling: false` with no +other change: `init OK → login OK`, app runs. + +This is worse than C-1: C-1 fails when you *use* a calling component; F4 fails when you *launch the +app*, whether or not calling is ever used. It is trivially hit by copying a settings file between +projects — which is exactly how it was found. + +| Where | Fix | +|---|---| +| `getting-started-kotlin`, `getting-started-jetpack`, `calling-integration` | `` with the stack trace + "change the flag and the dependency together" | +| core skill | warning beside the settings-file JSON block | +| builder-settings skill | `enableCalling` re-described: setting it `true` makes the dependency **mandatory** | +| calls skill | the flag and the artifact documented as a **pair**, with both failure directions | + +The two directions, together: + +| Artifact | `enableCalling` | Result | +|---|---|---| +| absent | `true` | **app crashes at launch** (F4) | +| present | `false` | calling components crash when used (C-1) | +| absent | `false` | fine — until a calling component is used (C-1) | +| present | `true` | correct | + +--- + +## Round 6 — Chat SDK v5 device run (headless, no UI Kit) + +A third fresh app depending on **only** `com.cometchat:chat-sdk-android:5.0.+`, built from +`cometchat-android-v5-sdk` alone. Verified on the emulator: + +``` +1 init OK ← CometChat.initFromSettings (reads the same assets JSON) +2 login OK cometchat-uid-1 ← init-then-login ordering, getLoggedInUser guard +3 message listener registered ← listener-register-with-id +4 conversations fetched: 5 ← pagination-via-request-builder +5 sent id=384770 "sdk-skill-test-2197" ← send-message + sdk-error-handling +6 history fetched: 5 message(s) ← MessagesRequestBuilder.fetchPrevious +7 listener removed (onDestroy) ← listener-remove-on-teardown +``` +No crashes. `CometChat.initFromSettings` reads the same `assets/cometchat-settings.json` as the UI +Kit — confirmed working without the UI Kit present. + +### S-3 — the SDK skill conflated two DIFFERENT `login` overloads (SKILL bug, now fixed) +The shipped SDK has: + +| Overload | Use | +|---|---| +| `login(uid, apiKey, listener)` | dev — **uid required** | +| `login(authToken, listener)` | production — **NO uid**; the server-minted token carries the identity | + +The skill wrote it as `login(uid, authKeyOrToken, …)`, which reads as "put either credential in the +middle slot". Following that for the **production** path passes a token where an apiKey is expected +— the wrong overload, and it fails at auth rather than at compile time. Fixed: both overloads are +now named explicitly, with the trap in Common pitfalls. Docs were correct here; the skill was not. + +--- + +## Round 7 — found by RUNNING the review harness on a device + +The review harness executed on a booted emulator for the first time (skills repo `AUDIT-086`). +The first kit view it inflated crashed, and the cause is a documentation gap: + +| # | Page | Gap | Fix | +|---|---|---|---| +| T1 | `ui-kit/android/getting-started-kotlin` | Neither getting-started page states that the app theme **must** descend from `Theme.MaterialComponents`. The kit's views are Material components, so on a stock `Theme.AppCompat.*` the first CometChat view inflated throws `IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant)`. It is a **launch crash on the chat screen**, not a styling glitch, and it is the very first thing a developer following the page hits. `troubleshooting` and `theme-introduction` mention Material, but a reader only reaches those AFTER it has already crashed. | Added a `` to `getting-started-kotlin` next to the existing dependency-exclude warning: inherit `CometChatTheme.DayNight` in `res/values/themes.xml` and point `` at it. | + +**Scoped to Views on purpose.** `getting-started-jetpack` was deliberately left alone: the Compose +cohort themes through the `CometChatTheme` **composable** +(`chatuikit-compose/.../theme/Theme.kt:13`), so it does not inflate Material Views and the XML +theme requirement does not apply to it. Adding the same warning there would have been a new docs +bug, not a fix. + +**Reproduced, then fixed, in the harness itself:** `test-suite/harness/android` ran on +`Theme.AppCompat.DayNight.NoActionBar` and every emit died at `attach()` with exactly this +exception; it now inherits `CometChatTheme.DayNight` like any integrating app must. + +--- + +## ROOT CAUSE — a v5 UI Kit checkout is vendored inside the docs repo + +`/.cometchat-uikit-android/` is a **shallow clone of `cometchat/cometchat-uikit-android` at tag +`v5.2.9`** (26 MB, its own `.git`, untracked and NOT gitignored). It is a working artifact, not docs +content — and it is the **wrong major** for the v6 pages it sits beside. + +Every "phantom API" found in the v6 docs exists in that v5 checkout: + +| API taught on a v6 page | In shipped v6 (6.0.5)? | In the vendored v5.2.9 clone? | +|---|---|---| +| `CometChatMessageTemplate` | ❌ | ✅ | +| `setTemplates` | ❌ | ✅ | +| `CometChatUIKit.getDataSource()` | ❌ | ✅ | +| `getAuxiliaryOption` | ❌ | ✅ | +| `getSelectedGroupMembers` | ❌ | ✅ | +| `setOnBackButtonPressed` | ❌ | ✅ | + +**6 of 6.** These pages are not randomly wrong — they are **correctly documenting v5** under a v6 +heading. The most economical explanation is that they were written or verified against this +checkout. (Correlation + physical presence in the repo, not proof of intent — but the pattern is +exact, and the fix is the same either way.) + +Note the v5 module layout differs too: this clone has a single `chatuikit/` module, whereas v6 ships +`chatuikit-core` + `chatuikit-kotlin` + `chatuikit-compose`. Anyone checking "does this API exist?" +against it gets a confident, wrong answer. + +### Recommended +1. **Remove it from the docs repo** (or at minimum add it to `.gitignore` — today it is 26 MB of + untracked noise in every `git status`, and a nested `.git` inside a repo invites accidental + commits). +2. If a reference checkout is genuinely wanted for docs authoring, it must be the **v6** source — + `cometchat-team/uikit-android` @ `master-v6` — and it should be pinned to the version the docs + claim, with the version stated in the path or a README beside it. +3. Better still: verify against the **published artifact** (the `.aar` Gradle already resolves), which + cannot drift from what customers actually install. That is what caught all six of these. + +The remaining docs bugs are NOT explained by this and are ordinary copy errors: `endtyping`, +`"Strat Typing"`, `getRecieverUID`, `setAttachmemnt`, `getReason`. + +## Still owed (not fixed here) +- **C1 full rewrite** of `message-template.mdx` (636 lines) against `BubbleFactory` — needs docs-team authoring; a banner is not a substitute. +- **D1** `getting-started-*` → `initFromSettings` + gitignored settings file instead of hardcoded `APP_ID`/`AUTH_KEY` constants. Behaviour change; wants product sign-off. +- **D2/D3** AI Integration Quick Reference accordion backfill (v6 components, all of SDK v5). + +--- + +## Round 8 — phantom CALLBACK TYPES on the search page (three-way audit) + +Surfaced by `three-way-audit.mjs` after the skills started teaching `CometChatSearch`. The page +documents the right method NAMES, but types every callback with a class that **does not exist in +6.0.5**. This sits in the machine-readable "AI Integration Quick Reference" accordion — the block +an AI agent reads first — so an agent would emit v5-Java-style SAM construction +(`new OnItemClick() { … }`) that cannot compile against v6. + +| # | Page | Docs said | Shipped 6.0.5 | +|---|---|---|---| +| P1 | `ui-kit/android/search` | `OnItemClick` / `OnItemClick` | `((Conversation) -> Unit)?` / `((BaseMessage) -> Unit)?` | +| P2 | `ui-kit/android/search` | `OnBackPress` · `OnError` · `OnEmpty` | `(() -> Unit)?` · `((CometChatException) -> Unit)?` · `(() -> Unit)?` | +| P3 | `ui-kit/android/search` | `OnLoad` / `OnLoad` | `((List) -> Unit)?` / `((List) -> Unit)?` | +| P4 | `ui-kit/android/search` | two Kotlin fences calling `setOnLoad*(OnLoad { … })` | trailing lambda: `setOnLoadMessages { list -> … }` | + +**Verified absent from the kit:** `OnItemClick`, `OnBackPress`, `OnError`, `OnEmpty`, `OnLoad` are +not declared anywhere in `chatuikit-kotlin` / `chatuikit-core`. The only such type that IS real is +`OnClick` (used by e.g. `setOnAcceptClickListener(OnClick?)`), which is why the family reads +plausible. 13 sites fixed on this branch. + +**Deliberately NOT changed:** the same `OnItemClick` spelling in `upgrading-from-v5.mdx` is +inside fences labelled `title="V5 — …"`. Those are BEFORE examples of the old v5 Java API, where +the name is correct — "fixing" them would break the migration story. + +**Also confirmed, not a bug:** `setOnConversationClicked` / `setOnMessageClicked` (past tense) DO +ship — they are aliases of `setOnConversationClick` / `setOnMessageClick` +(`CometChatSearch.kt:2431,2436`). Only their declared TYPES were wrong. + +--- + +--- + +## Round 9 — the drift gate wired into CI, and what it then found + +`three-way-audit.mjs` is now a CI gate on the skills side (`npm run verify:sync:android-v6`, folded +into `verify:ci:android`) — the Android equivalent of what RN did with `sync-check.mjs`. Wiring it +up meant fixing it first: it read **only ```kotlin/java fences**, so an API documented in a props +table or in the "AI Integration Quick Reference" accordion counted as undocumented. It now also +reads inline-code mentions and accordion JSON keys — which immediately exposed six phantoms that +fence-scanning could never see. + +| # | Page | Docs said | Shipped | Kind | +|---|---|---|---|---| +| R1 | `ui-kit/android/guide-ai-agent` | `setAIAssistantTools()` | **`setAiAssistantTools()`** (`CometChatMessageList.kt:2446`, `HashMap`) | casing — feature IS real | +| R2 | `ui-kit/android/troubleshooting` | `setAuxiliaryButtonView()` | `setAuxiliaryButtonViewListener()` — the A4 fix never reached this page | wrong name | +| R3 | `sdk/android/v5/edit-message` | `onSucess()` | `onSuccess()` | typo | +| R4 | `sdk/android/v5/send-message` | `setSubtype()` | **`setSubType()`** (`CustomMessage.java:113`) | casing — will not compile | +| R5 | `ui-kit/android/message-template` | the whole 676-line page taught v5's `MessageTemplate` | **rewritten** against `BubbleFactory` (both cohorts), 164 lines | C1 closed | +| R6 | `ui-kit/android/search`, `guide-search-messages` | **8** examples calling `setOnConversationClicked`/`setOnMessageClicked` with a **3-arg** lambda `{ view, position, x -> }` | **ONE** arg — `((Conversation) -> Unit)?` / `((BaseMessage) -> Unit)?` (`CometChatSearch.kt:1790,1797,2431,2436`) | arity — will not compile | + +R6 is the same defect class as B1 (the 3-arg thread callback) on a different page — evidence the +v5 listener idiom is still being carried into v6 pages by hand. + +**Result: `PHANTOM in DOCS` and `PHANTOM in SKILLS` are both 0** under the wider scan. + +**Still advisory, not defects:** the gate's `DOCS GAP (2)` names `setOnConversationClick` / +`setOnMessageClick` — the docs use the `…Clicked` aliases while the skills teach the canonical +names. **Both ship** (the aliases are real, `CometChatSearch.kt:2431,2436`), so this is a naming +inconsistency to settle, not broken code. `SKILL GAP (333)` is long-tail by design: the pack is +deliberately thin and fetches the long tail from docs at runtime. + diff --git a/REPRO-enableCalling-launch-crash.md b/REPRO-enableCalling-launch-crash.md new file mode 100644 index 000000000..fab77234d --- /dev/null +++ b/REPRO-enableCalling-launch-crash.md @@ -0,0 +1,75 @@ +# Repro — `enableCalling: true` without the Calls SDK crashes the app at launch + +**Kit:** `com.cometchat:chatuikit-compose-android:6.0.5` (crash path is in the shared +`chatuikit-core`, so `chatuikit-kotlin-android` is affected identically) +**Device:** Pixel 8 emulator, API 36 · **Observed:** 2026-08-21 + +## Steps + +1. New Android app, `minSdk 28`, Kotlin DSL. Add the CometChat maven to `settings.gradle.kts`: + ```kotlin + maven("https://dl.cloudsmith.io/public/cometchat/cometchat/maven/") + ``` +2. Add **only** the UI Kit — deliberately **no** `calls-sdk-android`: + ```kotlin + dependencies { implementation("com.cometchat:chatuikit-compose-android:6.0.+") } + configurations.all { exclude(group = "org.jetbrains", module = "annotations-java5") } + ``` +3. Create `app/src/main/assets/cometchat-settings.json` with **valid** credentials and the calling + flag ON. Credentials must be valid — the crash occurs *after* chat init succeeds: + ```json + { + "appId": "", + "region": "", + "credentials": { "authKey": "" }, + "uiKit": { "subscribePresenceForAllUsers": true, "enableCalling": true } + } + ``` +4. In `MainActivity.onCreate`, call init — nothing else is required: + ```kotlin + CometChatUIKit.initFromSettings(this, object : CometChat.CallbackListener() { + override fun onSuccess(result: String) { /* never reached */ } + override fun onError(e: CometChatException?) { /* never reached */ } + }) + ``` +5. Build, install, launch. + +## Expected +Either init succeeds with calling silently unavailable, or `onError` fires with an actionable +message naming the missing dependency. + +## Actual +Process dies in `onCreate`, before any UI renders. Neither `onSuccess` nor `onError` is called — +the throw escapes the callback. + +``` +FATAL EXCEPTION: main +java.lang.NoClassDefFoundError: Failed resolution of: + Lcom/cometchat/calls/core/CometChatCalls$SessionSettingsBuilder; + at com.cometchat.uikit.core.CometChatUIKit.initCometChatCalls(CometChatUIKit.kt:229) + at com.cometchat.uikit.core.CometChatUIKit.access$initCometChatCalls(CometChatUIKit.kt:40) + at com.cometchat.uikit.core.CometChatUIKit$initFromSettings$1.onSuccess(CometChatUIKit.kt:196) + at com.cometchat.uikit.core.CometChatUIKit$initFromSettings$1.onSuccess(CometChatUIKit.kt:187) + at com.cometchat.chat.core.CometChat.init(CometChat.java:63) + at com.cometchat.chat.core.CometChat.initFromSettings(CometChat.java:138) + at com.cometchat.uikit.core.CometChatUIKit.initFromSettings(CometChatUIKit.kt:185) + at com.example.composechat.MainActivity.onCreate(MainActivity.kt:38) +``` + +## Confirming the cause +Set `"enableCalling": false`, change nothing else, rebuild → `init OK` then `login OK`, app runs +normally. Flip it back → crash returns. + +## Why it matters +- The symptom (app will not start at all) is maximally distant from the cause (one boolean in a + JSON asset). Nothing in the flag's name implies a Gradle dependency. +- It **compiles cleanly**, so no build-time gate can catch it. +- It is trivially hit by copying `cometchat-settings.json` between projects — which is how it was + found here. +- `onError` is not invoked, so an app that correctly handles init failure still dies. + +## Suggested fix +Guard `initCometChatCalls` so a missing Calls SDK routes to `callbackListener.onError(...)` with a +message naming the required dependency, rather than propagating `NoClassDefFoundError`. Unlike the +`CometChatCallLogs` case (where a missing dependency legitimately cannot work), here calling is an +*optional* feature the app may never use — a launch crash is disproportionate. diff --git a/REST_API_DOCS_AUDIT_REPORT.md b/REST_API_DOCS_AUDIT_REPORT.md deleted file mode 100644 index 85a96fd1c..000000000 --- a/REST_API_DOCS_AUDIT_REPORT.md +++ /dev/null @@ -1,148 +0,0 @@ -# CometChat REST API Documentation Audit Report - -**Date:** 2026-04-24 -**Branch:** `docs/restapi-chatapi-ENG-30061-ketan` -**Preview URL:** https://cometchat-22654f5b-docs-restapi-chatapi-eng-30061-ketan.mintlify.app/ -**Pages Scanned:** 3,090 MDX files across 10 product directories -**OAS Files Scanned:** 5 files with 345 total endpoints - ---- - -## Executive Summary - -| Dimension | Score | -| ---------------------- | ---------- | -| Enterprise Readiness | 7.5/10 | -| AI-Agent Friendliness | 7.0/10 | -| AEO Friendliness | 8.5/10 | -| Link Hygiene | 8.0/10 | -| Completeness | 7.5/10 | -| Consistency | 7.0/10 | -| **Overall (weighted)** | **7.5/10** | - -The REST API docs are well-structured with zero orphan pages, zero ghost nav entries, and 100% frontmatter description coverage. The main gaps are in the OAS response schemas (52 untyped `data: object` responses in chat-apis.json), 4 broken redirect destinations, and cross-product consistency in overview page structure. - ---- - -## Product Coverage - -| Product | OAS File | Endpoints | MDX Pages | Guide Pages | Status | -| --------------------- | --------------------- | --------- | --------- | ------------------ | ------ | -| Chat & Messaging | chat-apis.json | 130 | 404 | 26 (notifications) | Active | -| Voice & Video Calling | calls.json | 2 | 207 | — | Active | -| AI Agents | ai-agent-service.json | 68 | 86 | — | Active | -| Moderation | management-apis.json | 141 | 12 | — | Active | -| Data Import | data-import-apis.json | 4 | — | — | Active | - ---- - -## Score Breakdown - -### Enterprise Readiness: 7.5/10 - -All 345 endpoints have operationIds and zero empty example values. Authentication is documented per-product (apikey for Chat, Basic Auth for Management). The main gap is 52 endpoints in chat-apis.json returning `data` as a generic untyped `object` — enterprise SDK codegen and type-safe clients can't infer response structure. 14 endpoints have completely empty response schemas. - -### AI-Agent Friendliness: 7.0/10 - -100% operationId coverage is excellent for AI agent consumption. The `llms.txt` file is published and accessible. However, 35 list endpoints across 3 OAS files lack pagination metadata in response schemas, making it harder for agents to handle paginated results programmatically. The 52 untyped response objects in chat-apis.json are the biggest blocker for AI agent integration. - -### AEO Friendliness: 8.5/10 - -Every REST API MDX file has a frontmatter `description`. The `llms.txt` is published with clear page descriptions. Heading hierarchy is clean across all scanned pages. Overview pages have structured endpoint tables (except AI Agents overview which uses prose instead). No debug markers in REST API pages. - -### Link Hygiene: 8.0/10 - -Zero broken internal links in REST API pages. Zero legacy domain references. Zero orphan or ghost pages. However, 4 redirect destinations point to non-existent files (`/ai-chatbots/ai-bots/bots`, `/ai-chatbots/ai-bots/instructions`, `/widget/wordpress/legacy`, `/widget/html/legacy`). The `flutter-sdk-changes-review.md` file (286 `
` tags fixed in this branch) and 13 files with invalid `mintlify` imports were cleaned up. - -### Completeness: 7.5/10 - -REST API overview pages for Calls and Moderation are comprehensive with endpoint tables, property tables, error handling, and pagination examples. AI Agents overview is lighter — missing a structured endpoint table. The iOS APNs push notification page renders as code-only with no prose introduction. 11 TODO markers remain in iOS UI Kit and React Native notification pages (screenshots and code snippets needed). - -### Consistency: 7.0/10 - -Overview page structure varies across products — Calls and Moderation have full endpoint tables while AI Agents uses prose. Pagination parameter naming varies across OAS files (`perPage`/`count`/`limit`) — this is an API-contract issue, not a docs issue. Code fence formatting was inconsistent (3 vs 4 backtick closings) across 10 JavaScript SDK files — fixed in this branch. Duplicate frontmatter keys were found in 2 files — fixed in this branch. - ---- - -## Issues Found - -### CRITICAL (P0) - -| # | Issue | File/Product | Dimension | Suggested Fix | -| --- | ------------------------------------------------------ | -------------- | ------------------------------ | ------------------------------------------------------------ | -| 1 | 52 endpoints return `data` as untyped generic `object` | chat-apis.json | Enterprise Readiness, AI-Agent | Add typed response schemas with properties for each endpoint | - -### HIGH (P1) - -| # | Issue | File/Product | Dimension | Suggested Fix | -| --- | ---------------------------------------------------------------- | -------------------------------------------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | -| 2 | 35 list endpoints missing pagination metadata in response schema | chat-apis.json, management-apis.json, ai-agent-service.json | AI-Agent Friendliness | Add `meta`/`pagination` object to list endpoint response schemas | -| 3 | 23 endpoints with empty response schemas | chat-apis.json (14), calls.json (2), ai-agent-service.json (7) | Enterprise Readiness | Define response properties or document as 204 No Content | -| 4 | 4 broken redirect destinations | docs.json redirects | Link Hygiene | Remove or update redirects for `/ai-chatbots/ai-bots/bots`, `/ai-chatbots/ai-bots/instructions`, `/widget/wordpress/legacy`, `/widget/html/legacy` | - -### MEDIUM (P2) - -| # | Issue | File/Product | Dimension | Suggested Fix | -| --- | ------------------------------------------------------- | -------------------------------------------------- | ------------------------- | ------------------------------------------------------------ | -| 5 | AI Agents API overview lacks structured endpoint table | rest-api/ai-agents-apis/overview | Completeness, Consistency | Add endpoint table matching Calls/Moderation overview format | -| 6 | iOS APNs push notification page is code-only | notifications/ios-apns-push-notifications.mdx | Completeness | Add introductory prose, setup steps, and section headers | -| 7 | 11 TODO markers in iOS UI Kit and RN notification pages | ui-kit/ios/_.mdx, notifications/react-native-_.mdx | Completeness | Add missing screenshots and code snippets | - -### LOW (P3) - -| # | Issue | File/Product | Dimension | Suggested Fix | -| --- | -------------------------------------------------------------- | ------------ | -------------------- | ------------------------------------- | -| 8 | `AWSCLIV2.pkg` in repo root (skipped by Mintlify as too large) | Root | Link Hygiene | Add to .gitignore or remove from repo | -| 9 | Calls OAS has only 2 endpoints with empty 400 error schemas | calls.json | Enterprise Readiness | Add error response properties | - ---- - -## Fixes Applied in This Branch - -The following issues were discovered and fixed during this audit session: - -| Fix | Files | Change | -| -------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | -| Duplicate redirect source | docs.json | Removed duplicate `/notifications/push-notification-extension-overview`, kept assets.cometchat.io destination | -| `
` → `
` | flutter-sdk-changes-review.md | 286 self-closing HTML tags for MDX compatibility | -| Mismatched code fences | 10 MDX files (ios-apns, ios-fcm, 8 JS SDK files) | Fixed ``````` closings to match ` `` ` openings | -| Inline code fences | sdk/javascript/retrieve-users.mdx, send-message.mdx | Expanded single-line code fences to proper multi-line blocks | -| Escaped comment syntax | sdk/javascript/send-message.mdx | Fixed `{/\*` → `{/*` and `\*/}` → `*/}` | -| Duplicate frontmatter keys | sdk/android/changelog.mdx, sdk/flutter/ai-chatbots-overview.mdx | Removed duplicate `description` keys | -| Invalid mintlify imports | 13 MDX files across calls, widget, ai-agents | Removed `import { ... } from 'mintlify'` (components are globally available) | - ---- - -## Prioritized Fix List - -### P0 — Must fix (blocks SDK codegen / AI agent consumption) - -1. Add typed response schemas to 52 chat-apis.json endpoints returning generic `data: object` - -### P1 — Should fix (degrades developer experience) - -1. Add pagination metadata to 35 list endpoint response schemas -2. Define response properties for 23 empty response schemas -3. Fix or remove 4 broken redirect destinations in docs.json - -### P2 — Nice to fix (polish) - -1. Add structured endpoint table to AI Agents API overview page -2. Add prose introduction to iOS APNs push notification page -3. Resolve 11 TODO markers (screenshots, code snippets) - -### P3 — Backlog - -1. Remove `AWSCLIV2.pkg` from repo -2. Add error response schemas to calls.json - ---- - -## Appendix - -- **Total issues:** 9 -- **By severity:** 1 critical, 3 high, 3 medium, 2 low -- **By product:** Chat 3, Calls 1, AI Agents 1, Cross-product 4 -- **Pages with zero issues:** 3,070+ of 3,090 -- **OAS files scanned:** chat-apis.json (130), calls.json (2), data-import-apis.json (4), management-apis.json (141), ai-agent-service.json (68) -- **Branch fixes applied:** 3 commits fixing 27 files total diff --git a/agent-skills.mdx b/agent-skills.mdx new file mode 100644 index 000000000..4b187daf2 --- /dev/null +++ b/agent-skills.mdx @@ -0,0 +1,293 @@ +--- +title: "Build CometChat with AI Agent Skills" +sidebarTitle: "Agent Skills" +description: "Install the CometChat agent skills and let your AI coding agent — Claude Code, Cursor, GitHub Copilot, Replit, and more — add production-grade chat and calling to your React or Angular app from natural-language prompts." +canonical: "https://www.cometchat.com/docs/agent-skills" +--- + +**CometChat Agent Skills** teach your AI coding agent how to build with CometChat. +Install the skills once, then open your project and say *"add chat to my app"* — +the agent has a short conversation with you (framework, intent, placement, +credentials), then writes production-grade integration code directly into the +files you already have. + +The skills author against the official **React UI Kit v7** and **Angular UI Kit v5** +task guides and verify their output against them, so what the agent writes builds and +runs against the current published UI Kit — not a hallucinated API. + + +The skills work **inside your existing project** with your existing agent. They +don't scaffold a throwaway demo — they detect your setup and integrate CometChat +into the app you're already building. + + +## Prerequisites + +- **Node.js 18+** — the installer runs through `npx`, so there's nothing to install globally. +- A **CometChat account** — [sign up free](https://app.cometchat.com) to get an app's App ID, Region, and Auth Key. +- An **existing React or Angular app**: + - **React** 18+ — **Vite**, **Create React App**, **Next.js**, **React Router**, or **Astro**. + - **Angular** 17–21 — **Angular CLI** or **Nx**. (Angular 22 is not yet installable: the UI Kit's peer range is `<22.0.0`.) +- One of the [supported AI coding agents](#supported-agents) below. + + +The skills target the **React UI Kit v7** and the **Angular UI Kit v5** today. The +installer tells you if it can't detect a supported setup — it never guesses or +scaffolds a throwaway project. In an empty or ambiguous project the agent asks which +framework you're building rather than assuming one. + + +## Install + +Run the installer in your project root: + +```bash +npx @cometchat/skills add +``` + +It detects your React or Angular setup and opens a picker to install the skills for +the AI agent(s) you use. To pin a single agent — useful in CI or a Dockerfile — pass +`--ide`: + +```bash +npx @cometchat/skills add --ide claude # Claude Code → .claude/skills/ +npx @cometchat/skills add --ide cursor # Cursor → ./.cometchat/skills + router +npx @cometchat/skills add --ide replit # Replit Agent → .agents/skills/ +npx @cometchat/skills add --ide all # every supported agent +``` + +### Supported agents + +| Agent | Install with | +| --- | --- | +| Claude Code | `--ide claude` | +| Cursor | `--ide cursor` | +| GitHub Copilot | `--ide copilot` | +| Windsurf | `--ide windsurf` | +| Replit Agent | `--ide replit` | +| Cline | `--ide cline` | +| Codex | `--ide codex` | +| Gemini | `--ide gemini` | +| Continue | `--ide continue` | +| Aider | `--ide aider` | +| Kiro | `--ide kiro` | +| Antigravity | `--ide antigravity` | + + +Claude Code, Kiro, and Replit get a native `SKILL.md` tree. The other agents get +an orienting router plus a `./.cometchat/skills` tree. Add `--global` (Claude +Code, Kiro, and Replit only) to install into your user-level directory instead of +the project. + + +## Use it + +Open your project in your agent and prompt it: + +``` +add chat to my app +``` + +or type the dispatcher directly: + +``` +/cometchat +``` + +The `cometchat` dispatcher detects your framework and routes to `cometchat-onboarding`, +which walks a short **discover → understand → plan → approve** flow. Once you +approve the plan, it hands a scoped build directive to that family's `core` skill +(`cometchat-react-v7-core` or `cometchat-angular-v5-core`) and pulls in the other +skills as the plan needs them (components, placement, theming, features, calls, push). + +Keep iterating in plain language afterward: + +- *"Add message reactions and threaded replies."* +- *"Switch the chat to dark mode and match my brand color."* +- *"Add a group details side panel."* +- *"Set up production authentication."* + +## Connect your credentials + +You don't paste your **App ID / Region / Auth Key** by hand. During the build, +when the skill notices they're missing, it offers two paths and defaults to +fetching them from your dashboard: + +- **Fetch from your dashboard (recommended)** — the skill runs the standalone + [CometChat CLI](/cli) for you, on demand: it opens the dashboard login in your + browser, lets you pick one of your **existing** apps, pulls the credentials, + and writes a neutral `.cometchat/config.json`. You can also run the CLI yourself + — it works on its own, in a script, or in CI. +- **Paste manually** — copy App ID, Region, and Auth Key from **Dashboard → Your + App → Credentials** if you'd rather not log in. + +Either way, the **skill** then writes the framework env file (`.env` / `VITE_` / +`NEXT_PUBLIC_` …) from those credentials — the CLI only fetches them and never +touches your framework code. + + +**Keep credentials out of version control.** Both `.cometchat/config.json` and +the generated env file contain your **Auth Key**. Make sure they're in +`.gitignore` — Vite, CRA, and Astro ignore only `*.local` (not `.env`), so add +`.env` yourself; Next.js ignores `.env.local` by default. The Auth Key is for +**development only**: in production, mint a short-lived per-user **auth token** on +your backend and log in with `loginWithAuthToken()` — never ship the Auth Key to +a production client. + + + +Prefer to drive it yourself? The credential CLI is also a standalone tool — +`npx @cometchat/skills-cli auth login`, then `provision run`. See the +[CLI reference](/cli) for the full command surface. + + +## What's in the pack + +Task-shaped skills the agent loads on demand — two shared, then one set per framework: + +| Skill | Purpose | +| --- | --- | +| `cometchat` | Thin dispatcher — detect the framework and route | +| `cometchat-onboarding` | Discover → understand → plan → approve (the front door) | +| `cometchat-react-v7-core` | Install · credentials · init → login → render · the golden-path chat surface | +| `cometchat-react-v7-components` | The v7 component catalog + props / slots | +| `cometchat-react-v7-placement` | Where chat lives — full app / sidebar / popup / embed | +| `cometchat-react-v7-customization` | Theming · brand · light/dark · view slots | +| `cometchat-react-v7-patterns` | Vite / Next.js / React Router / Astro glue (env · SSR · routing) | +| `cometchat-react-v7-features` | Enable a feature — reactions · polls · AI · moderation · … | +| `cometchat-react-v7-calls` | Voice / video calling | +| `cometchat-react-v7-push` | Web push (Notifications product) | +| `cometchat-react-v7-migration` | Upgrade a v6 UI Kit → v7 | + +**Angular UI Kit v5** + +| Skill | Purpose | +| --- | --- | +| `cometchat-angular-v5-core` | Install · credentials · init → login → render · the golden-path chat surface | +| `cometchat-angular-v5-components` | The v5 component catalog + inputs / outputs / view slots | +| `cometchat-angular-v5-placement` | Where chat lives — chat shell · thread and details panels · routing | +| `cometchat-angular-v5-customization` | Theming · brand · light/dark · view slots | +| `cometchat-angular-v5-patterns` | Angular CLI / Nx glue (environments · SSR · lazy routes · RxJS) | +| `cometchat-angular-v5-features` | Enable a feature — reactions · polls · AI · moderation · … | +| `cometchat-angular-v5-calls` | Voice / video calling | +| `cometchat-angular-v5-push` | Web push (Notifications product) | +| `cometchat-angular-v5-production` | Server-minted auth tokens · hardening before you ship | +| `cometchat-angular-v5-testing` | Testing an app that embeds CometChat | +| `cometchat-angular-v5-troubleshooting` | Diagnosing a broken integration | + +## Example prompts + +Everything starts from one prompt — **"add chat to my app"** — then you refine in +plain language. Example prompts, grouped by goal: + +**Get started** + +- *"Add chat to my app."* — the default: a conversation list + message view +- *"Add 1:1 direct messaging between my users."* +- *"Add group chat with file sharing."* +- *"Build a full chat app with Chats, Users, and Calls tabs."* + +**Where chat lives** + +- *"Add a support chat widget in the bottom-right corner."* +- *"Add a floating chat popup I can toggle open and closed."* +- *"Put chat in a sidebar next to my app."* +- *"Embed a chat panel on my dashboard page."* + +**Features** + +- *"Add message reactions, typing indicators, and read receipts."* +- *"Add threaded replies and @mentions."* +- *"Add image and file sharing."* +- *"Add message search."* +- *"Add polls and stickers."* + +**Calling & AI** + +- *"Add voice and video calling with a click-to-call button."* +- *"Add smart replies and conversation summaries."* +- *"Add an AI assistant to the chat."* +- *"Turn on moderation so banned words are blocked before delivery."* + +**Look & feel** + +- *"Switch the chat to dark mode and match my brand color."* +- *"Make the chat follow the user's system light/dark setting."* + +**Ship it** + +- *"Set up production authentication with auth tokens."* +- *"Add web push notifications."* +- *"Migrate my v6 UI Kit to v7."* + +The agent plans each change with you, then writes the integration into your +existing files — you don't have to know the component or prop names. + +## Manage the skills + +- **Update** — re-run `npx @cometchat/skills add` to pull the latest skills; it overwrites the installed skill tree in place. +- **Inspect** — `npx @cometchat/skills list` shows the installed skills, and `npx @cometchat/skills doctor` runs an environment health check. +- **Uninstall** — delete the installed skill directory for your agent (for example `.claude/skills/cometchat*`, `.agents/skills/`, or `./.cometchat/skills`). +- **Version control** — commit the skill files so your whole team shares the same setup. Do **not** commit `.cometchat/config.json` or the generated env file — they hold your Auth Key. + +## Troubleshooting + +| Symptom | Likely cause | Fix | +| --- | --- | --- | +| The agent doesn't pick up the skills | Installed for a different agent, or a router-based agent needs pointing at the tree | Re-run `npx @cometchat/skills add --ide `. For router agents (Cursor, Copilot, …) open `.cometchat/skills/cometchat/SKILL.md` to orient it. | +| Blank screen, no errors | A UI Kit component rendered before `init()` + `login()` resolved, or the wrong Region / env prefix | The `init → login → render` order is required. Check that the Region matches your dashboard app and the env prefix matches your bundler (`VITE_` / `NEXT_PUBLIC_` / `PUBLIC_`). | +| `login()` fails — "user not found" | Logging in a UID that doesn't exist in the app | Use a UID that exists (Dashboard → your app → **Users**; fresh apps seed `cometchat-uid-1`). | +| Auth error on init / login | Region mismatch between your code and the dashboard app | Re-check the Region (`us` / `eu` / `in`) in both the dashboard and your env file. | +| `ERROR_API_KEY_NOT_FOUND` | An env var is empty or not picked up by the bundler | Confirm the env file uses the right prefix for your bundler, then restart the dev server. | +| Version conflict during install | An older **v6** UI Kit is already installed | Ask the agent to migrate — the `cometchat-react-v7-migration` skill upgrades v6 → v7. | + +## Compatibility + +**React** + +| Dependency | Version | +| --- | --- | +| `@cometchat/chat-uikit-react` | `7.x` (verified 7.1.x) | +| `@cometchat/chat-sdk-javascript` | `4.x` | +| `@cometchat/calls-sdk-javascript` | `5.x` (calling) | +| React | `≥ 18` | + +**Angular** + +| Dependency | Version | +| --- | --- | +| `@cometchat/chat-uikit-angular` | `5.x` (verified 5.1.0) | +| `@cometchat/chat-sdk-javascript` | `^4.1.13` | +| `@cometchat/cards-angular` | `^1.0.0` | +| `@cometchat/calls-sdk-javascript` | `^5.0.3` (calling) | +| `dompurify` | `^3.0.0` | +| Angular | `≥ 17` and `< 22` | + + +Angular 22 is not yet installable — the UI Kit's peer range is `>=17.0.0 <22.0.0`, so +`npm install` fails with `ERESOLVE` on Angular 22. Scaffold with `@angular/cli@21` until +a kit release widens the range. + + +## Next steps + + + + Authenticate, provision credentials, and manage the skills from your terminal + + + Connect CometChat to any Model Context Protocol–compatible agent + + + The manual React UI Kit setup the skills automate + + + The manual Angular UI Kit setup the skills automate + + + Browse all prebuilt React components + + + Browse all prebuilt Angular components + + diff --git a/cli.mdx b/cli.mdx new file mode 100644 index 000000000..85f7d8c24 --- /dev/null +++ b/cli.mdx @@ -0,0 +1,211 @@ +--- +title: "CometChat CLI" +sidebarTitle: "CLI" +description: "Authenticate against the CometChat dashboard, provision app credentials, toggle features, and manage the AI agent skills — all from your terminal, with JSON output for scripting and CI." +canonical: "https://www.cometchat.com/docs/cli" +--- + +CometChat ships two complementary command-line tools: + +| CLI | Package | What it does | +| --- | --- | --- | +| **Credentials CLI** | `@cometchat/skills-cli` | Dashboard authentication + app-credential provisioning + feature toggles | +| **Skills CLI** | `@cometchat/skills` | Install, list, and verify the [AI Agent Skills](/agent-skills) | + + +The credentials CLI is **standalone** — use it on its own, in a script, or in CI. +It's a pure dashboard/API client: it authenticates, fetches your app credentials +(App ID / Region / Auth Key), and writes a neutral `.cometchat/config.json`. By +design it does **not** detect your framework, write env files, or generate code, +so it stays framework-agnostic and works with any stack. The +[agent skills](/agent-skills) are one consumer that can run it for you — but the +CLI doesn't require them. + + +Both run through `npx` with no global install, and most commands accept `--json` +for machine-readable output (the exceptions are `config set` and `config path`, +which print plain text). + +## Prerequisites + +- **Node.js 18+** — both CLIs run through `npx`. +- A **CometChat account** — [sign up free](https://app.cometchat.com). `auth login` opens the dashboard in your browser to authenticate. + +--- + +## Credentials CLI — `@cometchat/skills-cli` + +Its only job is authenticating against the CometChat dashboard and fetching your +**App ID / Region / Auth Key**, then writing a neutral `.cometchat/config.json` +that any tool — your own scripts, a CI job, or the agent skills — can read. + +### Quick start + +```bash +# 1. Authenticate against the dashboard (opens your browser) +npx @cometchat/skills-cli auth login + +# 2. List the apps on your account +npx @cometchat/skills-cli provision list --json + +# 3. Pick or create an app, fetch creds, write .cometchat/config.json +npx @cometchat/skills-cli provision run + +# 4. Inspect the local config you just wrote +npx @cometchat/skills-cli config show --json +``` + +### Authenticate + +```bash +npx @cometchat/skills-cli auth login +``` + +Opens your browser at the CometChat dashboard for device authentication and +stores the bearer token in your OS keychain (falling back to a `chmod 600` file). + +| Command | Purpose | +| --- | --- | +| `auth login` | Sign in via the dashboard (device auth) | +| `auth status` | Show whether you're signed in | +| `auth me` | Print the authenticated account | +| `auth logout` | Clear the stored token | +| `auth signup` | Create a CometChat account | + +### Provision credentials + +```bash +npx @cometchat/skills-cli provision run +``` + +Fetches your **App ID / Region / Auth Key**, prints them as JSON, and writes a +neutral `.cometchat/config.json`. It writes **no** framework env file — read +`config.json` and set your framework's env vars (`.env` / `VITE_` / +`NEXT_PUBLIC_` …) yourself, or let the agent skills do it. + +| Command | Purpose | +| --- | --- | +| `provision run` | Interactive: pick or create an app, fetch creds, write config | +| `provision list` | List the apps on your account | +| `provision create --name ` | Create a new app (`--name` required) | +| `provision use --app-id ` | Select a specific app by id | + +Create a new app non-interactively — `--name` is required, `--region` and +`--industry` are optional: + +```bash +npx @cometchat/skills-cli provision create --name "My Chat" --region us +``` + +The config file `provision` writes: + +```json +{ + "$schema": "https://cometchat.com/schemas/config.json", + "version": 1, + "appId": "…", + "region": "us", + "authKey": "…", + "appName": "My Chat", + "plan": "…", + "industry": "…" +} +``` + + +`.cometchat/config.json` contains your **Auth Key** — add it to `.gitignore`. The +Auth Key is for **development only**; in production, mint a per-user **auth +token** on your backend and log in with `loginWithAuthToken()` instead of +shipping the Auth Key to a client. + + +### Manage config + +Read and edit the local `.cometchat/config.json` (credential/app state only): + +| Command | Purpose | +| --- | --- | +| `config init` | Create an empty config | +| `config get ` | Read a single value | +| `config set ` | Write a single value | +| `config show` | Print the full config | +| `config path` | Print the config file location | + +### Toggle features + +Enable or disable app features from the terminal: + +| Command | Purpose | +| --- | --- | +| `features list` | List available features and their state | +| `features enable ` | Turn a feature on | +| `features disable ` | Turn a feature off | +| `features ai-key ` | Set the app's OpenAI key that AI features need | + +Set the OpenAI key AI features require before they can run — the key is a +required argument: + +```bash +npx @cometchat/skills-cli features ai-key +``` + +--- + +## Skills CLI — `@cometchat/skills` + +Installs and manages the [AI Agent Skills](/agent-skills) that let your coding +agent build with CometChat. + +```bash +npx @cometchat/skills add +``` + +| Command | Purpose | +| --- | --- | +| `detect` | Probe the current project (framework, UI Kit, version conflicts) | +| `add [--ide ]` | Install the skills for an AI agent (default: Claude Code) | +| `list` | List the skills this pack ships | +| `info ` | Show a skill's triggers + compatibility | +| `verify [tier]` | Run the skill quality gates | +| `catalog` | Refresh the component catalog from the installed UI Kit | +| `doctor` | Environment health check | + +See [Agent Skills](/agent-skills) for the install picker, supported agents, and +the prompt-driven workflow. + +--- + +## Scripting and CI + +Most commands support `--json` (the exceptions are `config set` and +`config path`, which print plain text), and `add` can be pinned to one agent with +`--ide`, so the whole flow runs non-interactively: + +```bash +# Authenticate, select a known app, and install the skills for Claude Code +npx @cometchat/skills-cli auth login +npx @cometchat/skills-cli provision use --app-id "$COMETCHAT_APP_ID" --json +npx @cometchat/skills add --ide claude +``` + +Commands **exit non-zero on failure** and surface dashboard errors verbatim (for +example `ACCESS_DENIED`, `EXPIRED`, `TIMEOUT`, `ABORTED`), so a broken auth or +provisioning step fails the CI job loudly instead of continuing with empty +credentials. + +## Next steps + + + + Install the skills and build CometChat from natural-language prompts + + + Connect CometChat to any Model Context Protocol–compatible agent + + + The manual React UI Kit setup, credentials and all + + + Open the CometChat dashboard + + diff --git a/docs.json b/docs.json index cb43da08b..5cb0ba072 100644 --- a/docs.json +++ b/docs.json @@ -41,20 +41,27 @@ { "product": "Home", "pages": [ - "index", - { - "group": "Docs MCP", - "hidden": true, - "pages": [ - "mcp-server" - ] - } + "index" ] }, { "product": "Home", "hidden": true, "tabs": [ + { + "tab": "Developer Tools", + "hidden": true, + "pages": [ + { + "group": "Developer Tools", + "pages": [ + "agent-skills", + "cli", + "mcp-server" + ] + } + ] + }, { "tab": "On-Premise Deployment", "hidden": true, diff --git a/flutter-sdk-changes-review.md b/flutter-sdk-changes-review.md deleted file mode 100644 index 93fd6ab90..000000000 --- a/flutter-sdk-changes-review.md +++ /dev/null @@ -1,134 +0,0 @@ -# Flutter SDK (`sdk/flutter/`) Changes Review - -> **Base:** commit `5e4976de` (state before the improvements branch) -> **Target:** commit `9feb900b` (tip of `docs/flutter-sdk-improvments`) -> **Scope:** `sdk/flutter/*.mdx` only, `sdk/flutter/3.0/` excluded -> **Total:** 62 files modified (+8,176 lines, −16 lines) -> **Commits:** -> - `659f8839` — "feat: made docs more agentic and developer friendly" (added Quick Reference `` blocks, `description` frontmatter, `` blocks, `` blocks, and Next Steps `` navigation to all files) -> - `beb0cc1c` — "docs(flutter): add response and error accordions to SDK docs" (added `` and `` sections after every SDK method call across all files except presenter-mode) -> - `9feb900b` — "docs(flutter): add response and error accordions to presenter mode" (added response/error accordions to the final remaining file) - ---- - -## What Changed Across All Files — Pattern Summary - -Every file received some combination of these five additions: - -### 1. `description` frontmatter (all 62 files) -A one-line SEO description was added to the YAML frontmatter of every file. Example: -```yaml -description: "Get started with the CometChat Flutter SDK to add real-time chat and calling features to your Flutter application." -``` - -### 2. AI Agent Quick Reference `` blocks (all 62 files) -A hidden comment `{/* TL;DR for Agents and Quick Reference */}` followed by an `` block containing copy-paste-ready Dart/YAML code snippets was added at the top of every page, right after the frontmatter. These blocks are designed for both AI agents and developers to quickly understand the page's core functionality without reading the full content. Example from `overview.mdx`: -```dart -// Initialize (run once at app start) -AppSettings appSettings = (AppSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..region = "REGION" - ..autoEstablishSocketConnection = true -).build(); - -CometChat.init("APP_ID", appSettings, - onSuccess: (msg) => debugPrint("Init success"), - onError: (e) => debugPrint("Init failed: ${e.message}"), -); -``` - -### 3. Response/Error Accordions (most files — wherever SDK methods exist) -After every SDK method call on the page, two expandable `` sections were added: -- **``** — Documents the success callback return type with a table of fields including Parameter, Type, Description, and Sample Value. For complex objects (User, Group, BaseMessage, Call), every field is listed with realistic sample values. -- **``** — Documents the error callback with `code`, `message`, and `details` fields and sample error values. - -Example Response table fields for `sendMessage()`: -`id`, `metadata`, `receiver`, `editedBy`, `conversationId`, `sentAt`, `receiverUid`, `type`, `readAt`, `deletedBy`, `deliveredAt`, `deletedAt`, `replyCount`, `sender`, `receiverType`, `editedAt`, `parentMessageId`, `readByMeAt`, `category`, `deliveredToMeAt`, `updatedAt`, `text`, `tags`, `unreadRepliesCount`, `mentionedUsers`, `hasMentionedMe`, `reactions`, `moderationStatus`, `quotedMessageId` — plus nested Sender and Receiver User object tables. - -Example Error table: -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `code` | string | Error code identifier | `"ERR_CHAT_API_FAILURE"` | -| `message` | string | Human-readable error message | `"SDK initialization failed."` | -| `details` | string | Additional technical details | `"Please verify your App ID and region, then try again."` | - -### 4. `` blocks (select files — where common pitfalls exist) -Warning callouts were added for critical developer pitfalls. Examples: -- `overview.mdx` / `setup.mdx`: *"`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail."* -- `authentication-overview.mdx`: *"Auth Key is for development/testing only. In production, generate Auth Tokens server-side."* -- `delete-message.mdx` / `delete-conversation.mdx` / `delete-group.mdx`: Warnings about permanent/irreversible deletion -- `default-call.mdx`: *"Generate a call token before starting a session"* -- `ai-agents.mdx`: *"Always remove AI Assistant listeners when they're no longer needed (e.g., on widget dispose or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling."* -- `receive-messages.mdx`: Warning about removing message listeners on dispose - -### 5. Next Steps `` navigation (all 62 files) -A `---` horizontal rule followed by a `## Next Steps` heading and a `` with 2–4 `` links was added at the bottom of every page. Each card has a title, icon, href, and description pointing to logically related pages. - ---- - -## Detailed File-by-File Changes - -| File Name | Changes List | Description | -|-----------|-------------|-------------| -| `overview.mdx` | 1. Added `description: "Get started with the CometChat Flutter SDK to add real-time chat and calling features to your Flutter application."`
2. Added Quick Reference `` block containing: `cometchat_sdk: ^4.0.33` install yaml, `CometChat.init()` with `AppSettingsBuilder` code, `CometChat.login()` with Auth Key code, commented `loginWithAuthToken()` alternative, credential source note pointing to Dashboard
3. Added ``: "CometChat.init() must be called before any other SDK method. Calling login(), sendMessage(), or registering listeners before init() will fail."
4. Added Response accordion after `CometChat.init()` — success returns a `String` message: `"Initialization completed successfully"`
5. Added Error accordion after `CometChat.init()` — error fields: `code` (`"ERR_CHAT_API_FAILURE"`), `message` (`"SDK initialization failed."`), `details` (`"Please verify your App ID and region, then try again."`)
6. Added Response accordion after `CometChat.createUser()` — returns a `User` object with 12 fields: `uid`, `name`, `link`, `avatar`, `metadata`, `status` (`"offline"`), `role` (`"default"`), `statusMessage`, `tags`, `hasBlockedMe`, `blockedByMe`, `lastActiveAt`
7. Added Error accordion after `CometChat.createUser()` — error fields: `code` (`"ERR_UID_NOT_FOUND"`), `message`, `details`
8. Added Response accordion after `CometChat.login()` — returns a `User` object with same 12 fields, sample `status` is `"online"`, sample `lastActiveAt` is `1745554700`
9. Added Error accordion after `CometChat.login()` — same error structure
10. Added Next Steps CardGroup with 4 cards: "Setup SDK" (icon: gear, href: `/sdk/flutter/setup`), "Key Concepts" (icon: lightbulb, href: `/sdk/flutter/key-concepts`), "Authentication" (icon: key, href: `/sdk/flutter/authentication-overview`), "Send Messages" (icon: paper-plane, href: `/sdk/flutter/send-message`) | This is the main entry point for the Flutter SDK docs. The Quick Reference block gives developers the complete install → init → login flow in one glance. The `` prevents the #1 integration mistake (calling SDK methods before init). Response accordions document the exact shape of `User` objects returned by `createUser()` and `login()`, including all 12 fields with realistic sample values. Error accordions show the standard `CometChatException` structure (`code`/`message`/`details`) that is consistent across all SDK methods. The Next Steps cards create a guided learning path from overview → setup → auth → messaging. | -| `setup.mdx` | 1. Added `description: "Install and initialize the CometChat Flutter SDK in your application"`
2. Added Quick Reference `` block — same install + init + login code as overview, plus credential source note
3. Added ``: same init-before-other-methods warning
4. Added Response accordion after `CometChat.init()` — `String` success message
5. Added Error accordion after `CometChat.init()` — `code`/`message`/`details`
6. Added Next Steps CardGroup with 2 cards: "Authentication" (icon: key), "Send Messages" (icon: paper-plane) | The setup page is the detailed installation guide (pubspec.yaml, podfile, minSdkVersion, etc.). The Quick Reference duplicates the overview's code block intentionally — developers may land on either page first. Response/Error accordions document what `init()` returns on success/failure so developers know what to expect in their callbacks. | -| `authentication-overview.mdx` | 1. Added `description: "Learn how to authenticate users in your Flutter app using CometChat SDK with Auth Key for development or Auth Token for production."`
2. Added Quick Reference `` block with: `CometChat.login(UID, authKey)` code, `CometChat.loginWithAuthToken(authToken)` code, `CometChat.logout()` code, note about `getLoggedInUser()` to check existing session
3. Added ``: "Auth Key is intended for development/testing only. For production, generate Auth Tokens server-side via the REST API and use loginWithAuthToken()."
4. Added Response accordion after `login()` with Auth Key — `User` object with 12 fields (uid, name, avatar, status=`"online"`, role=`"default"`, lastActiveAt, etc.)
5. Added Error accordion after `login()` with Auth Key — `code` (`"ERR_UID_NOT_FOUND"`), `message`, `details`
6. Added Response accordion after `loginWithAuthToken()` — same `User` object structure
7. Added Error accordion after `loginWithAuthToken()` — same error structure
8. Added Response accordion after `logout()` — `String` success message: `"User logged out successfully"`
9. Added Error accordion after `logout()` — `code`/`message`/`details`
10. Added Next Steps CardGroup with 4 cards: "Send Messages", "Receive Messages", "Key Concepts", "Users" | The auth page now clearly distinguishes between Auth Key (dev) and Auth Token (prod) flows. The `` is a critical security note — shipping Auth Keys in production client code is a common mistake. Each of the three auth methods (login with key, login with token, logout) has its own response/error accordion so developers can see exactly what each returns. | -| `key-concepts.mdx` | 1. Added `description: "Understand the core concepts of CometChat including Dashboard, API keys, users, groups, messages, and conversations."`
2. Added Quick Reference `` block summarizing: CometChat Dashboard purpose, Auth Key vs REST API Key differences (Auth Key = client-side dev, REST API Key = server-side), Users/UID/Auth Token concepts, Groups (GUID, public/private/password types), Messages (text/media/custom/interactive), Conversations (user/group)
3. Added Next Steps CardGroup with 4 cards: "Setup", "Authentication", "Send Messages", "Groups" | The Quick Reference block condenses the entire key-concepts page into a scannable summary. This is especially useful for AI agents that need to understand CometChat's data model quickly. No response/error accordions here since this is a conceptual page with no SDK method calls. | -| `send-message.mdx` | 1. Added `description: "Learn how to send text, media, and custom messages to users and groups using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.sendMessage(textMessage)` code, `CometChat.sendMediaMessage(mediaMessage)` code, `CometChat.sendCustomMessage(customMessage)` code
3. Added ``: "Available via: SDK \| REST API \| UI Kits \| Dashboard"
4. Added ``: "CometChat.init() and CometChat.login() must complete before sending messages."
5. Added Response accordion after `sendMessage()` for text — `BaseMessage` object with 28 fields: `id` (401), `metadata`, `receiver` (nested User object), `editedBy`, `conversationId` (`"cometchat-uid-1_user_cometchat-uid-2"`), `sentAt` (epoch), `receiverUid`, `type` (`"text"`), `readAt`, `deletedBy`, `deliveredAt`, `deletedAt`, `replyCount`, `sender` (nested User object with uid/name/avatar/status/role/tags/etc.), `receiverType` (`"user"`), `editedAt`, `parentMessageId`, `readByMeAt`, `category` (`"message"`), `deliveredToMeAt`, `updatedAt`, `text` (`"messageText"`), `tags`, `unreadRepliesCount`, `mentionedUsers`, `hasMentionedMe`, `reactions`, `moderationStatus`, `quotedMessageId` — plus full nested Sender User object (12 fields) and Receiver User object (12 fields)
6. Added Error accordion after `sendMessage()` for text
7. Added Response accordion after `sendMediaMessage()` — similar `BaseMessage` structure with additional `attachment` field containing `url`, `extension`, `size`, `mimeType`
8. Added Error accordion after `sendMediaMessage()`
9. Added Response accordion after `sendCustomMessage()` — `BaseMessage` with `customData` map field
10. Added Error accordion after `sendCustomMessage()`
11. Added Next Steps CardGroup with 4 cards: "Receive Messages", "Edit Message", "Delete Message", "Threaded Messages" | This is one of the most heavily documented files (+559 lines). The `BaseMessage` response table is the most comprehensive object documentation in the entire SDK docs — 28 top-level fields plus two nested User objects (Sender and Receiver) each with 12 fields. This gives developers complete visibility into what the `onSuccess` callback returns. The nested object tables use anchor links (`#send-text-sender-object`, `#send-text-receiver-object`) for easy navigation. Media message response adds attachment metadata. Custom message response shows the `customData` map structure. | -| `receive-messages.mdx` | 1. Added `description: "Learn how to receive real-time messages and fetch message history using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addMessageListener()` code showing `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` callbacks; `MessagesRequestBuilder` with `fetchPrevious()`/`fetchNext()` code; `CometChat.removeMessageListener()` cleanup code
3. Added ``: "Always remove message listeners when they're no longer needed (e.g., on widget dispose). Failing to remove listeners can cause memory leaks and duplicate event handling."
4. Added Response accordion after `fetchPrevious()` — `List` with full BaseMessage object table (28 fields per message, same structure as send-message)
5. Added Error accordion after `fetchPrevious()`
6. Added Response accordion after `fetchNext()` — same `List` structure
7. Added Error accordion after `fetchNext()`
8. Added Response accordions for each real-time listener callback: `onTextMessageReceived` (TextMessage object), `onMediaMessageReceived` (MediaMessage with attachment), `onCustomMessageReceived` (CustomMessage with customData), `onTypingStarted`, `onTypingEnded`, `onMessagesDelivered`, `onMessagesRead`, `onMessageEdited`, `onMessageDeleted`
9. Added Error accordions for listener callbacks
10. Added Next Steps CardGroup with 4 cards: "Send Messages", "Threaded Messages", "Message Filtering", "Delivery Receipts" | The largest change after `default-call.mdx` (+767 lines). Every real-time listener callback now has its own Response accordion documenting the exact object shape that arrives in the callback. This is critical for developers building custom UIs — they need to know exactly which fields are available on `TextMessage` vs `MediaMessage` vs `CustomMessage`. The memory leak warning about removing listeners is a common Flutter pitfall. | -| `edit-message.mdx` | 1. Added `description: "Learn how to edit sent messages in your Flutter app using the CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.editMessage(textMessage)` code for text, `CometChat.editMessage(mediaMessage)` code for media
3. Added Response accordion after `editMessage()` for text — `BaseMessage` object with `editedAt` populated (non-zero epoch), `editedBy` populated with editor's UID
4. Added Error accordion after `editMessage()` for text
5. Added Response accordion after `editMessage()` for media — same structure with attachment metadata
6. Added Error accordion after `editMessage()` for media
7. Added Next Steps CardGroup with 3 cards: "Delete Message", "Send Messages", "Threaded Messages" | The response accordions specifically highlight the `editedAt` and `editedBy` fields that change when a message is edited — this helps developers understand which fields to check in their UI to show "edited" indicators. | -| `delete-message.mdx` | 1. Added `description: "Learn how to delete messages and handle real-time deletion events in your Flutter app using CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.deleteMessage(messageId)` code, `onMessageDeleted` listener callback code
3. Added ``: "Deleting a message is permanent and cannot be undone. The message will be removed for all participants in the conversation."
4. Added Response accordion after `deleteMessage()` — `BaseMessage` object with `deletedAt` populated (non-zero epoch), `deletedBy` populated with deleter's UID
5. Added Error accordion after `deleteMessage()`
6. Added Next Steps CardGroup with 3 cards: "Edit Message", "Send Messages", "Receive Messages" | The permanence warning is important — unlike some chat platforms, CometChat's delete is not soft-delete by default. Response accordion highlights `deletedAt` and `deletedBy` fields. | -| `delivery-read-receipts.mdx` | 1. Added `description: "Learn how to implement message delivery and read receipts in your Flutter app using CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.markAsDelivered(message)` code, `CometChat.markAsRead(message)` code, `CometChat.markAsUnread(message)` code, listener callbacks for `onMessagesDelivered`/`onMessagesRead`
3. Added Response accordion after `markAsDelivered()` — void success (no return value)
4. Added Error accordion after `markAsDelivered()`
5. Added Response accordion after `markAsRead()` — void success
6. Added Error accordion after `markAsRead()`
7. Added Response accordion after `markAsUnread()` — void success
8. Added Error accordion after `markAsUnread()`
9. Added Next Steps CardGroup with 3 cards: "Receive Messages", "Send Messages", "Typing Indicators" | Receipt methods return void on success (no object), so the Response accordions simply confirm "void — no return value". The Error accordions still document the `CometChatException` structure. | -| `typing-indicators.mdx` | 1. Added `description: "Learn how to send and receive typing indicators in your Flutter app using CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.startTyping(typingIndicator)` code, `CometChat.endTyping(typingIndicator)` code, `onTypingStarted`/`onTypingEnded` listener callbacks
3. Added Next Steps CardGroup with 3 cards: "Send Messages", "Receive Messages", "Delivery Receipts" | No response/error accordions — typing indicator methods are fire-and-forget with no success/error callbacks. Quick reference shows both sending and receiving sides. | -| `threaded-messages.mdx` | 1. Added `description: "Learn how to send, receive, and fetch messages within a thread attached to a parent message in CometChat Flutter SDK."`
2. Added Quick Reference `` block with: send-in-thread code (`textMessage.parentMessageId = 103`), fetch-thread code (`MessagesRequestBuilder()..parentMessageId = 103`), hide-replies code (`..hideReplies = true`)
3. Added Response accordion after `sendMessage()` in thread — `BaseMessage` with `parentMessageId` populated (103)
4. Added Error accordion after `sendMessage()` in thread
5. Added Response accordion after `fetchPrevious()` for thread — `List` with `parentMessageId` on each message
6. Added Error accordion after `fetchPrevious()`
7. Added Response accordion after `fetchNext()` for thread — same structure
8. Added Error accordion after `fetchNext()`
9. Added Next Steps CardGroup with 3 cards: "Send Messages", "Receive Messages", "Message Filtering" | The Quick Reference block shows the three key thread operations in one place: sending into a thread, fetching a thread's messages, and excluding thread replies from the main conversation. Response accordions highlight the `parentMessageId` field that links messages to their thread. | -| `mentions.mdx` | 1. Added `description: "Learn how to mention users in messages and fetch mentioned messages using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: mention in text message code (setting `mentionedUsers` on `TextMessage`), fetch mentioned messages code (`MessagesRequestBuilder()..mentionsWithType`)
3. Added Response accordion after sending message with mentions — `BaseMessage` with `mentionedUsers` array populated, `hasMentionedMe` boolean
4. Added Error accordion
5. Added Response accordion after fetching mentioned messages — `List` with mention metadata
6. Added Error accordion
7. Added Next Steps CardGroup with 3 cards: "Send Messages", "Receive Messages", "Message Filtering" | Response accordions specifically show how `mentionedUsers` array and `hasMentionedMe` boolean appear in the response — developers need this to render @mention UI elements. | -| `reactions.mdx` | 1. Added `description: "Learn how to add, remove, and fetch reactions on messages using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addReaction(messageId, emoji)` code, `CometChat.removeReaction(messageId, emoji)` code, `CometChat.fetchMessageReactions(messageId)` code
3. Added Response accordion after `addReaction()` — `BaseMessage` with `reactions` array populated
4. Added Error accordion after `addReaction()`
5. Added Response accordion after `removeReaction()` — `BaseMessage` with updated `reactions` array
6. Added Error accordion after `removeReaction()`
7. Added Response accordion after `fetchMessageReactions()` — `List` with fields: `reaction` (emoji string), `count` (number), `reactedByMe` (boolean)
8. Added Error accordion after `fetchMessageReactions()`
9. Added Next Steps CardGroup with 3 cards: "Send Messages", "Receive Messages", "Interactive Messages" | The `fetchMessageReactions()` response introduces a new object type (`ReactionCount`) not seen in other pages — it has `reaction`, `count`, and `reactedByMe` fields. | -| `interactive-messages.mdx` | 1. Added `description: "Learn how to send interactive messages (Form, Card, Scheduler) using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `FormMessage` construction code, `CardMessage` construction code, `SchedulerMessage` construction code
3. Added Response accordion after sending `FormMessage` — `BaseMessage` with `interactiveData` map containing form fields
4. Added Error accordion
5. Added Response accordion after sending `CardMessage` — `BaseMessage` with `interactiveData` containing card layout
6. Added Error accordion
7. Added Next Steps CardGroup with 3 cards: "Send Messages", "Reactions", "Message Filtering" | Interactive messages have a unique `interactiveData` field in the response that contains the form/card/scheduler structure. | -| `transient-messages.mdx` | 1. Added `description: "Learn how to send and receive transient (ephemeral) messages that are not stored in CometChat's database."`
2. Added Quick Reference `` block with: `CometChat.sendTransientMessage(transientMessage)` code, `onTransientMessageReceived` listener callback
3. Added Next Steps CardGroup with 3 cards: "Send Messages", "Typing Indicators", "Real-Time Listeners" | No response/error accordions — transient messages are fire-and-forget. The Quick Reference clarifies that these messages are not persisted. | -| `flag-message.mdx` | 1. Added `description: "Learn how to flag or report messages for moderation in your Flutter app using CometChat SDK."`
2. Added Quick Reference `` block with: `CometChat.flagMessage(message)` code
3. Added Response accordion after `flagMessage()` — success confirmation
4. Added Error accordion after `flagMessage()`
5. Added Next Steps CardGroup with 3 cards: "Delete Message", "AI Moderation", "Extensions" | Flag message is a simple method with a straightforward response. | -| `additional-message-filtering.mdx` | 1. Added `description: "Learn how to use MessagesRequestBuilder to filter and fetch messages with various parameters including pagination, categories, types, tags, and advanced search options in Flutter."`
2. Added Quick Reference `` block with: `MessagesRequestBuilder` examples showing filters by `..categories`, `..types`, `..tags`, `..uid`, `..guid`, `..limit`, `..searchKeyword`, `..hideReplies`, `..hideDeletedMessages`
3. Added Next Steps CardGroup with 4 cards: "Receive Messages", "Send Messages", "Threaded Messages", "Message Structure" | No response/error accordions — this page documents the request builder configuration, not the fetch methods themselves (those are on `receive-messages.mdx`). The Quick Reference is a comprehensive filter cheat sheet. | -| `message-structure-and-hierarchy.mdx` | 1. Added `description: "Understand the message class hierarchy in CometChat Flutter SDK — BaseMessage, TextMessage, MediaMessage, CustomMessage, and InteractiveMessage."`
2. Added Quick Reference `` block summarizing the class hierarchy: `BaseMessage` (parent) → `TextMessage`, `MediaMessage`, `CustomMessage`, `InteractiveMessage` (children), with key fields for each
3. Added Next Steps CardGroup with 4 cards: "Send Messages", "Receive Messages", "Interactive Messages", "Message Filtering" | Conceptual page — no SDK method calls, so no response/error accordions. The Quick Reference gives a class hierarchy overview. | -| `messaging-overview.mdx` | 1. Added `description: "Overview of CometChat's messaging capabilities for Flutter including text, media, custom, and interactive messages."`
2. Added Quick Reference `` block listing all messaging features with links: Send Messages, Receive Messages, Edit/Delete, Threaded Messages, Typing Indicators, Delivery/Read Receipts, Mentions, Reactions, Interactive Messages, Transient Messages, Flag Message
3. Added Next Steps CardGroup with 4 cards: "Send Messages", "Receive Messages", "Threaded Messages", "Reactions" | Index page — the Quick Reference serves as a complete table of contents for the messaging section. | -| `retrieve-conversations.mdx` | 1. Added `description: "Learn how to fetch and paginate through conversations using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `ConversationsRequestBuilder` code showing `..limit`, `..conversationType`, `..withTags`, `..tags` filters; `fetchNext()`/`fetchPrevious()` pagination code
3. Added Response accordion after `fetchNext()` — `List` with fields: `conversationId`, `conversationType` (`"user"`/`"group"`), `lastMessage` (nested BaseMessage), `conversationWith` (nested User or Group object), `unreadMessageCount`, `updatedAt`, `tags`, `lastReadMessageId`
4. Added Error accordion after `fetchNext()`
5. Added Response accordion after `fetchPrevious()` — same structure
6. Added Error accordion after `fetchPrevious()`
7. Added Next Steps CardGroup with 4 cards: "Delete Conversation", "Send Messages", "Retrieve Users", "Retrieve Groups" | The `Conversation` object is a complex nested type — it contains a `lastMessage` (full BaseMessage) and a `conversationWith` (User or Group depending on type). The response tables document all these nested structures. | -| `delete-conversation.mdx` | 1. Added `description: "Learn how to delete user and group conversations from the logged-in user's conversation list using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.deleteConversation(conversationWith, conversationType)` code
3. Added ``: "Deleting a conversation removes it only from the logged-in user's list. The other participant's conversation is not affected. This action cannot be undone."
4. Added Response accordion after `deleteConversation()` — `String` success message
5. Added Error accordion after `deleteConversation()`
6. Added Next Steps CardGroup with 2 cards: "Retrieve Conversations", "Send Messages" | The warning clarifies that conversation deletion is one-sided (only affects the current user) and irreversible. | -| `retrieve-users.mdx` | 1. Added `description: "Learn how to fetch and paginate through users using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `UsersRequestBuilder` code showing `..limit`, `..searchKeyword`, `..status`, `..hideBlockedUsers`, `..roles`, `..tags`, `..uids` filters; `fetchNext()` pagination code
3. Added Response accordion after `fetchNext()` — `List` with 12 fields per user: `uid`, `name`, `link`, `avatar`, `metadata`, `status`, `role`, `statusMessage`, `tags`, `hasBlockedMe`, `blockedByMe`, `lastActiveAt`
4. Added Error accordion after `fetchNext()`
5. Added Next Steps CardGroup with 3 cards: "Block Users", "User Presence", "User Management" | The User object table is reused across many pages (login, send-message, etc.) but this is the canonical reference for the full User object shape. | -| `user-management.mdx` | 1. Added `description: "Learn how to create and update users using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.createUser(user, authKey)` code, `CometChat.updateUser(user)` code
3. Added Response accordion after `createUser()` — `User` object (12 fields)
4. Added Error accordion after `createUser()`
5. Added Response accordion after `updateUser()` — `User` object (12 fields)
6. Added Error accordion after `updateUser()`
7. Added Next Steps CardGroup with 3 cards: "Retrieve Users", "Block Users", "User Presence" | Both user management methods return the full User object on success. | -| `user-presence.mdx` | 1. Added `description: "Learn how to track user online/offline status in real-time using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addUserListener()` code showing `onUserOnline`/`onUserOffline` callbacks
3. Added Next Steps CardGroup with 3 cards: "Retrieve Users", "User Management", "Real-Time Listeners" | No response/error accordions — presence is received via listeners, not method calls. | -| `users-overview.mdx` | 1. Added `description: "Overview of CometChat's user management capabilities for Flutter."`
2. Added Quick Reference `` block listing: Retrieve Users, User Management, Block Users, User Presence with links
3. Added Next Steps CardGroup with 4 cards | Index page for the Users section. | -| `block-users.mdx` | 1. Added `description: "Learn how to block and unblock users in your Flutter app using the CometChat SDK to manage user interactions and privacy."`
2. Added Quick Reference `` block with: `CometChat.blockUsers(uids)` code, `CometChat.unblockUsers(uids)` code, `BlockedUsersRequestBuilder` with `fetchNext()` code
3. Added Response accordion after `blockUsers()` — `Map` showing success/failure per UID
4. Added Error accordion after `blockUsers()`
5. Added Response accordion after `unblockUsers()` — same Map structure
6. Added Error accordion after `unblockUsers()`
7. Added Response accordion after `fetchNext()` for blocked users — `List` (12 fields per user)
8. Added Error accordion after `fetchNext()`
9. Added Next Steps CardGroup with 3 cards: "Retrieve Users", "User Management", "User Presence" | The `blockUsers()`/`unblockUsers()` methods return a `Map` (not a simple success string) — the response accordion documents this unique return type. | -| `create-group.mdx` | 1. Added `description: "Learn how to create public, private, and password-protected groups using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `Group` constructor code for public/private/password types, `CometChat.createGroup(group)` code
3. Added Response accordion after `createGroup()` — `Group` object with 15+ fields: `guid`, `name`, `type` (`"public"`/`"private"`/`"password"`), `icon`, `description`, `owner`, `metadata`, `tags`, `membersCount`, `createdAt`, `updatedAt`, `hasJoined`, `scope`, `joinedAt`, `conversationId`
4. Added Error accordion after `createGroup()`
5. Added Next Steps CardGroup with 3 cards: "Join Group", "Retrieve Groups", "Group Members" | The Group object table is the canonical reference for group data — 15+ fields including `membersCount`, `hasJoined`, `scope`, and `conversationId`. | -| `join-group.mdx` | 1. Added `description: "Learn how to join public and password-protected groups using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.joinGroup(guid, groupType, password)` code
3. Added Response accordion after `joinGroup()` — `Group` object (same 15+ fields)
4. Added Error accordion after `joinGroup()`
5. Added Next Steps CardGroup with 3 cards: "Leave Group", "Retrieve Group Members", "Create Group" | Response shows the Group object with `hasJoined` now `true` and `scope` set to `"participant"`. | -| `leave-group.mdx` | 1. Added `description: "Learn how to leave a group using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.leaveGroup(guid)` code
3. Added Response accordion after `leaveGroup()` — `String` success message
4. Added Error accordion after `leaveGroup()`
5. Added Next Steps CardGroup with 3 cards: "Join Group", "Delete Group", "Retrieve Groups" | Simple method — returns success string on leave. | -| `delete-group.mdx` | 1. Added `description: "Learn how to permanently delete a group in CometChat using the Flutter SDK. Only group admins can delete groups."`
2. Added Quick Reference `` block with: `CometChat.deleteGroup(guid)` code
3. Added ``: "Only the group admin can delete a group. Deleting a group is permanent and removes all messages and members."
4. Added Response accordion after `deleteGroup()` — `String` success message
5. Added Error accordion after `deleteGroup()`
6. Added Next Steps CardGroup with 3 cards: "Create Group", "Retrieve Groups", "Leave Group" | The admin-only + permanent deletion warning is critical context for developers. | -| `update-group.mdx` | 1. Added `description: "Learn how to update group details using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.updateGroup(group)` code
3. Added Response accordion after `updateGroup()` — `Group` object (15+ fields) with updated values
4. Added Error accordion after `updateGroup()`
5. Added Next Steps CardGroup with 3 cards: "Create Group", "Retrieve Groups", "Group Members" | Response shows the updated Group object. | -| `transfer-group-ownership.mdx` | 1. Added `description: "Learn how to transfer group ownership to another member using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.transferOwnership(guid, uid)` code
3. Added Response accordion after `transferOwnership()` — `String` success message
4. Added Error accordion after `transferOwnership()`
5. Added Next Steps CardGroup with 3 cards: "Group Members", "Update Group", "Change Member Scope" | Simple method — returns success string. | -| `retrieve-groups.mdx` | 1. Added `description: "Learn how to fetch and paginate through groups using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `GroupsRequestBuilder` code showing `..limit`, `..searchKeyword`, `..joinedOnly`, `..tags`, `..withTags` filters; `fetchNext()` code
3. Added Response accordion after `fetchNext()` — `List` (15+ fields per group)
4. Added Error accordion after `fetchNext()`
5. Added Next Steps CardGroup with 3 cards: "Create Group", "Join Group", "Group Members" | Group retrieval response documents the full Group object for each item in the list. | -| `retrieve-group-members.mdx` | 1. Added `description: "Learn how to fetch and paginate through group members using the CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `GroupMembersRequestBuilder("GROUP_ID")` code showing `..limit`, `..scopes` (admin/moderator/participant) filters; `fetchNext()` code
3. Added ``: "Available via: SDK \| REST API \| UI Kits"
4. Simplified intro paragraph — removed redundant sentence about `GroupMembersRequestBuilder`
5. Added Response accordion after `fetchNext()` — `List` with 14 fields: all 12 User fields plus `scope` (`"admin"`/`"moderator"`/`"participant"`) and `joinedAt` (epoch timestamp)
6. Added Error accordion after `fetchNext()`
7. Added Next Steps CardGroup with 3 cards: "Add Members", "Kick Member", "Change Scope" | `GroupMember` extends `User` with two additional fields (`scope` and `joinedAt`) — the response table documents all 14 fields. | -| `group-add-members.mdx` | 1. Added `description: "Learn how to add members to a group using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addMembersToGroup(guid, members, bannedMembers)` code
3. Added Response accordion after `addMembersToGroup()` — `Map` showing success/failure per member UID
4. Added Error accordion
5. Added Next Steps CardGroup with 3 cards: "Retrieve Group Members", "Kick Member", "Change Scope" | The Map response type is unique — it maps each member UID to a success/failure status string. | -| `group-change-member-scope.mdx` | 1. Added `description: "Learn how to change a group member's scope (role) using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.changeMemberScope(guid, uid, scope)` code showing scope values: `CometChatMemberScope.admin`, `.moderator`, `.participant`
3. Added Response accordion — `String` success message
4. Added Error accordion
5. Added Next Steps CardGroup with 3 cards: "Retrieve Group Members", "Add Members", "Transfer Ownership" | Quick Reference shows all three scope enum values. | -| `group-kick-member.mdx` | 1. Added `description: "Learn how to kick, ban, and unban group members using CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.kickGroupMember(guid, uid)` code, `CometChat.banGroupMember(guid, uid)` code, `CometChat.unbanGroupMember(guid, uid)` code
3. Added Response accordion after `kickGroupMember()` — `String` success message
4. Added Error accordion after `kickGroupMember()`
5. Added Response accordion after `banGroupMember()` — `String` success message
6. Added Error accordion after `banGroupMember()`
7. Added Response accordion after `unbanGroupMember()` — `String` success message
8. Added Error accordion after `unbanGroupMember()`
9. Added Next Steps CardGroup with 3 cards: "Retrieve Group Members", "Add Members", "Change Scope" | All three member moderation methods documented with response/error. | -| `groups-overview.mdx` | 1. Added `description: "Overview of CometChat's group management capabilities for Flutter."`
2. Added Quick Reference `` block listing: Create Group, Join Group, Leave Group, Delete Group, Update Group, Transfer Ownership, Retrieve Groups, Retrieve Group Members, Add Members, Change Scope, Kick/Ban Members with links
3. Added Next Steps CardGroup with 4 cards | Index page for the Groups section. | -| `default-call.mdx` | 1. Added `description: "Implement complete calling workflow with ringing functionality including incoming/outgoing call UI, call acceptance, rejection, and cancellation in your Flutter app."`
2. Added Quick Reference `` block with: `CometChat.initiateCall(call)` code, `CometChat.acceptCall(sessionId)` code, `CometChat.rejectCall(sessionId, status)` code with `CometChatCallStatus.rejected`/`.cancelled`/`.busy`, `CometChat.endCall(sessionId)` code
3. Added ``: "You must generate a call token using `CometChatCalls.generateToken()` before starting a call session with `CometChatCalls.startSession()`."
4. Added Response accordion after `initiateCall()` — `Call` object with 28+ fields: all BaseMessage fields (id, metadata, receiver, sender, conversationId, sentAt, type, category, etc.) PLUS call-specific fields: `sessionId` (`"v1.us.1.xxxxxxxx"`), `callStatus` (`"initiated"`), `action` (`"initiated"`), `callInitiator` (nested User object), `callReceiver` (nested User object), `initiatedAt` (epoch), `joinedAt` (epoch) — plus nested Sender, Receiver, CallInitiator, and CallReceiver User object tables (12 fields each)
5. Added Error accordion after `initiateCall()`
6. Added Response accordion after `acceptCall()` — `Call` object with `callStatus` = `"ongoing"`, `action` = `"accepted"`
7. Added Error accordion after `acceptCall()`
8. Added Response accordion after `rejectCall()` (rejected) — `Call` object with `callStatus` = `"rejected"`, `action` = `"rejected"`
9. Added Error accordion after `rejectCall()` (rejected)
10. Added Response accordion after `rejectCall()` (cancelled by initiator) — `Call` object with `callStatus` = `"cancelled"`, `action` = `"cancelled"`
11. Added Error accordion after `rejectCall()` (cancelled)
12. Added Response accordion after `endCall()` — `Call` object with `callStatus` = `"ended"`, `action` = `"ended"`
13. Added Error accordion after `endCall()`
14. Added Response accordion after `CometChatCalls.startSession()` — `Widget?` representing the call UI to embed in your screen
15. Added Error accordion after `startSession()`
16. Added Next Steps CardGroup with 3 cards: "Direct Call", "Standalone Calling", "Call Logs" | This is the single largest file change (+876 lines). The `Call` object extends `BaseMessage` with 7 additional call-specific fields (`sessionId`, `callStatus`, `action`, `callInitiator`, `callReceiver`, `initiatedAt`, `joinedAt`). Each call lifecycle state (initiated, ongoing, rejected, cancelled, ended) has its own Response accordion showing the exact `callStatus` and `action` values for that state — this is critical for developers building custom call UIs who need to know which status values to check. The `startSession()` response is unique — it returns a Flutter `Widget?` that developers embed in their screen to show the call interface. | -| `direct-call.mdx` | 1. Added `description: "Implement direct calling without ringing functionality — generate a token and start a call session directly."`
2. Added Quick Reference `` block with: `CometChatCalls.generateToken(sessionId, userAuthToken)` code, `CometChatCalls.startSession(callToken, callSettings)` code with `CallSettingsBuilder` showing `..enableDefaultLayout`, `..listener`
3. Added Response accordion after `generateToken()` — `String` call token
4. Added Error accordion after `generateToken()`
5. Added Response accordion after `startSession()` — `Widget?` call UI widget
6. Added Error accordion after `startSession()`
7. Added Next Steps CardGroup with 3 cards: "Default Call", "Standalone Calling", "Recording" | Direct calling skips the ringing flow — the Quick Reference shows the simplified two-step process (generate token → start session). | -| `standalone-calling.mdx` | 1. Added `description: "Implement standalone calling that works independently of CometChat's messaging infrastructure."`
2. Added Quick Reference `` block with: standalone `CometChatCalls.init()` code, `generateToken()` code, `startSession()` code
3. Added Response accordion after `generateToken()` — `String` call token
4. Added Error accordion
5. Added Response accordion after `startSession()` — `Widget?` call UI widget
6. Added Error accordion
7. Added Next Steps CardGroup with 3 cards: "Default Call", "Direct Call", "Call Logs" | Standalone calling is for apps that only need calling (no chat). The Quick Reference shows the independent init flow. | -| `calling-setup.mdx` | 1. Added `description: "Learn how to install and initialize the CometChat Calls SDK for Flutter to enable voice and video calling in your application."`
2. Added Quick Reference `` block with: `cometchat_calls_sdk: ^4.0.x` install yaml, `CometChatCalls.init(callAppSettings)` code with `CallAppSettingsBuilder` showing `..appId`, `..region`
3. Added Response accordion after `CometChatCalls.init()` — `String` success message: `"CometChat Calls SDK initialized successfully"`
4. Added Error accordion after `CometChatCalls.init()`
5. Added Next Steps CardGroup with 3 cards: "Default Call", "Direct Call", "Standalone Calling" | The Calls SDK has its own separate init method (`CometChatCalls.init()`) distinct from the main SDK's `CometChat.init()`. | -| `calling-overview.mdx` | 1. Added `description: "Implement voice and video calling in your Flutter application with CometChat's calling SDK, supporting ringing calls, direct calls, and standalone calling."`
2. Added Quick Reference `` block summarizing three calling modes: Default Calling (with ringing, requires chat SDK), Direct Calling (no ringing, requires chat SDK), Standalone Calling (independent, no chat SDK needed) — with use-case guidance for each
3. Added Next Steps CardGroup with 4 cards: "Calling Setup", "Default Call", "Direct Call", "Standalone Calling" | The Quick Reference is a decision guide — helps developers choose between the three calling modes based on their use case. | -| `call-logs.mdx` | 1. Added `description: "Learn how to fetch and manage call logs in your Flutter application using CometChat's Call SDK, including filtering by call type, status, and direction."`
2. Added Quick Reference `` block with: `CallLogRequestBuilder` code showing `..limit`, `..callType`, `..callStatus`, `..callDirection` filters; `fetchNext()`/`fetchPrevious()` code; `CometChatCalls.getCallDetails(sessionId)` code
3. Added Response accordion after `fetchNext()` — `List` with 10+ fields: `sessionId`, `callType` (`"audio"`/`"video"`), `callStatus` (`"initiated"`/`"ongoing"`/`"ended"`/`"cancelled"`/`"rejected"`/`"busy"`/`"unanswered"`), `callDirection` (`"incoming"`/`"outgoing"`), `initiator` (User object), `receiver` (User object), `initiatedAt`, `endedAt`, `duration`, `participants`
4. Added Error accordion after `fetchNext()`
5. Added Response accordion after `fetchPrevious()` — same structure
6. Added Error accordion after `fetchPrevious()`
7. Added Response accordion after `getCallDetails()` — `List` for a specific session
8. Added Error accordion after `getCallDetails()`
9. Added Next Steps CardGroup with 3 cards: "Default Call", "Recording", "Presenter Mode" | The `CallLog` object is distinct from the `Call` object — it's a historical record with `duration`, `endedAt`, and `participants` fields not present on the real-time `Call` object. | -| `recording.mdx` | 1. Added `description: "Learn how to enable and manage call recording in your Flutter app using CometChat's Calls SDK."`
2. Added Quick Reference `` block with: recording configuration in `CallSettingsBuilder` (`..enableRecording`), fetch recordings code
3. Added Response accordion after fetching recordings — recording object with `recordingUrl`, `recordingDuration`, `startedAt`, `endedAt`
4. Added Error accordion
5. Added Next Steps CardGroup with 3 cards: "Call Logs", "Default Call", "Presenter Mode" | Recording response includes the `recordingUrl` for playback/download. | -| `presenter-mode.mdx` | 1. Added `description: "Learn how to implement presenter mode in your Flutter app for webinars, online classes, and broadcast-style calling experiences with CometChat."`
2. Added Quick Reference `` block with: `PresentationSettingsBuilder` code showing `..enableDefaultLayout`, `..isPresenter = true` (presenter) and `..isPresenter = false` (viewer); `CometChatCalls.joinPresentation(callToken, settings)` code for both roles
3. Added Response accordion after `joinPresentation()` — `Widget?` representing the presentation UI, documented as: "A Flutter widget containing the presentation UI. Display this widget in your screen to show the presentation interface."
4. Added Error accordion after `joinPresentation()` — `code` (`"ERR_CHAT_API_FAILURE"`), `message` (`"Failed to start the presentation session."`), `details` (`"The call token provided is invalid or expired."`)
5. Added Next Steps CardGroup with 3 cards: "Default Call", "Recording", "Video View Customisation" | This was the final file updated (commit `9feb900b`). The Quick Reference shows both presenter and viewer code side-by-side so developers can see the `isPresenter` flag difference. | -| `video-view-customisation.mdx` | 1. Added `description: "Learn how to customize the video view in CometChat calls for Flutter."`
2. Added Quick Reference `` block with: video view customization code
3. Added Next Steps CardGroup with 3 cards: "Presenter Mode", "Default Call", "Recording" | No response/error accordions — this page covers UI customization, not SDK method calls. | -| `real-time-listeners.mdx` | 1. Added `description: "Complete reference for all real-time event listeners in the CometChat Flutter SDK."`
2. Added Quick Reference `` block listing all 5 listener types with their key callbacks: `MessageListener` (onTextMessageReceived, onMediaMessageReceived, onCustomMessageReceived, onMessageEdited, onMessageDeleted, onMessagesDelivered, onMessagesRead, onTypingStarted, onTypingEnded, onTransientMessageReceived), `UserListener` (onUserOnline, onUserOffline), `GroupListener` (onGroupMemberJoined, onGroupMemberLeft, onGroupMemberKicked, onGroupMemberBanned, onGroupMemberUnbanned, onGroupMemberScopeChanged, onMemberAddedToGroup), `CallListener` (onIncomingCallReceived, onOutgoingCallAccepted, onOutgoingCallRejected, onIncomingCallCancelled), `ConnectionListener` (onConnected, onConnecting, onDisconnected, onFeatureThrottled)
3. Added Next Steps CardGroup with 3 cards: "Receive Messages", "Connection Status", "Login Listeners" | The Quick Reference is a comprehensive callback catalog — developers can scan all available listener callbacks in one place without reading the full page. | -| `login-listeners.mdx` | 1. Added `description: "Learn how to handle login and logout state changes using LoginListener in CometChat Flutter SDK."`
2. Added Quick Reference `` block with: `CometChat.addLoginListener()` code showing `onLoginSuccess`, `onLoginFailure`, `onLogoutSuccess`, `onLogoutFailure` callbacks
3. Added Next Steps CardGroup with 3 cards: "Authentication", "Real-Time Listeners", "Connection Status" | Login listeners help developers react to auth state changes (e.g., auto-redirect on logout). | -| `connection-status.mdx` | 1. Added `description: "Monitor real-time WebSocket connection status with CometChat SDK using ConnectionListener callbacks and getConnectionStatus method."`
2. Added Quick Reference `` block with: `CometChat.addConnectionListener()` code showing `onConnected`, `onConnecting`, `onDisconnected`, `onFeatureThrottled` callbacks; `CometChat.getConnectionStatus()` code returning `CometChatConnectionStatus.connected`/`.connecting`/`.disconnected`
3. Added Next Steps CardGroup with 3 cards: "Connection Behaviour", "Real-Time Listeners", "Login Listeners" | The Quick Reference shows both the listener approach (reactive) and the `getConnectionStatus()` approach (polling) for monitoring connection state. | -| `connection-behaviour.mdx` | 1. Added `description: "Understand how CometChat SDK manages WebSocket connections in auto and manual modes, including background behavior and reconnection handling."`
2. Added Quick Reference `` block comparing Auto Mode (default — SDK manages connections automatically) vs Manual Mode (`autoEstablishSocketConnection = false` — developer controls `connect()`/`disconnect()`/`ping()`)
3. Added Response accordion after `CometChat.connect()` — `String` success message
4. Added Error accordion after `CometChat.connect()`
5. Added Response accordion after `CometChat.disconnect()` — `String` success message
6. Added Error accordion after `CometChat.disconnect()`
7. Added Response accordion after `CometChat.ping()` — `String` success message
8. Added Error accordion after `CometChat.ping()`
9. Added Next Steps CardGroup with 3 cards: "Connection Status", "Real-Time Listeners", "Setup" | The auto vs manual mode comparison in the Quick Reference is a key decision point for developers — most should use auto mode, but apps with specific background requirements may need manual mode. | -| `session-timeout.mdx` | 1. Added `description: "Learn how to configure session timeout behavior in CometChat Flutter SDK."`
2. Added Quick Reference `` block with: session timeout configuration code
3. Added Next Steps CardGroup with 3 cards: "Authentication", "Connection Behaviour", "Login Listeners" | No response/error accordions — session timeout is a configuration, not a method call. | -| `rate-limits.mdx` | 1. Added `description: "Understand the API rate limits for CometChat Flutter SDK operations."`
2. Added Quick Reference `` block summarizing rate limit categories and their values (messages per second, API calls per minute, etc.)
3. Added Next Steps CardGroup with 3 cards: "Send Messages", "Retrieve Conversations", "Setup" | The Quick Reference gives developers a quick view of rate limits without reading the full table. | -| `advanced-overview.mdx` | 1. Added `description: "Advanced SDK features including connection management, real-time listeners, and login state handling for Flutter applications."`
2. Added Quick Reference `` block listing 4 advanced features with one-line descriptions and links: Connection Status (monitor SDK connection state), Connection Behaviour (understand connection lifecycle), Login Listeners (handle login state changes), Real-Time Listeners (all event listeners reference)
3. Added Next Steps CardGroup with 4 cards: "Connection Status", "Real-Time Listeners", "Login Listeners", "Connection Behaviour" | Index page for the Advanced section. | -| `resources-overview.mdx` | 1. Added `description` frontmatter
2. Added Quick Reference `` block listing resource topics
3. Added Next Steps CardGroup | Index page for the Resources section. | -| `flutter-overview.mdx` | 1. Added `description` frontmatter
2. Added Quick Reference `` block with high-level SDK capabilities: real-time messaging, voice/video calling, user/group management, typing indicators, read receipts, file sharing, reactions, mentions, interactive messages, AI features
3. Added Next Steps CardGroup with 4 cards: "Overview/Setup", "Key Concepts", "Authentication", "Send Messages" | Top-level Flutter SDK overview — the Quick Reference gives a feature checklist. | -| `upgrading-from-v3-guide.mdx` | 1. Added `description: "Guide for migrating your Flutter app from CometChat SDK v3 to v4."`
2. Added Quick Reference `` block summarizing key v3→v4 breaking changes and migration steps
3. Added Next Steps CardGroup with 3 cards: "Setup", "Authentication", "Key Concepts" | The Quick Reference gives a scannable migration checklist. | -| `ai-agents.mdx` | 1. Added `description: "Learn how to integrate AI Agents in your Flutter app to enable intelligent, automated interactions that process user messages, trigger tools, and respond with contextually relevant information."`
2. Added Quick Reference `` block with: `CometChat.addAIAssistantListener("LISTENER_ID", AIAssistantListener(onAIAssistantEventReceived: (event) {}))` code, `CometChat.addMessageListener("LISTENER_ID", MessageListener(onAIAssistantMessageReceived: (msg) {}, onAIToolResultReceived: (result) {}))` code, `CometChat.removeAIAssistantListener("LISTENER_ID")` cleanup code
3. Added ``: "Available via: SDK \| REST API \| UI Kits \| Dashboard"
4. Added ``: "Always remove AI Assistant listeners when they're no longer needed (e.g., on widget dispose or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling."
5. Added Next Steps CardGroup with 3 cards: "AI Moderation", "AI Chatbots", "Extensions" | The Quick Reference shows both the AI-specific listener (`AIAssistantListener`) and the message listener callbacks for AI events (`onAIAssistantMessageReceived`, `onAIToolResultReceived`). The memory leak warning is especially important for AI listeners since they may be added in multiple screens. | -| `ai-moderation.mdx` | 1. Added `description: "Learn how to implement AI-powered content moderation in your Flutter app using CometChat SDK to automatically review messages for inappropriate content."`
2. Added Quick Reference `` block with: moderation check code showing `message.metadata["@injected"]["extensions"]["ai-moderation"]` path, status values (`"approved"`, `"pending"`, `"rejected"`), real-time listener for moderation status updates
3. Added Response accordion after sending a moderated message — `BaseMessage` with `metadata` containing nested `@injected.extensions.ai-moderation` object with fields: `status` (`"pending"`), `confidence` (number), `categories` (array of flagged categories)
4. Added Error accordion
5. Added Response accordion for real-time moderation status update — same metadata structure with `status` changed to `"approved"` or `"rejected"`
6. Added Error accordion
7. Added Next Steps CardGroup with 4 cards: "AI Agents", "AI Chatbots", "Send Messages", "Extensions" | The moderation metadata path (`@injected.extensions.ai-moderation`) is deeply nested — the Response accordion documents the exact path developers need to access moderation results. The two Response accordions show the initial "pending" state and the final "approved"/"rejected" state. | -| `ai-chatbots-overview.mdx` | 1. Added `description: "Configure AI-powered chatbots to provide automated assistance and maintain conversational momentum in your Flutter app."`
2. Added Quick Reference `` block summarizing: chatbot configuration via Dashboard, chatbot types (rule-based, AI-powered), integration with messaging flow
3. Added Next Steps CardGroup with 4 cards: "AI Agents", "AI Moderation", "AI User Copilot", "Extensions" | Index page for AI chatbots — no SDK method calls, so no response/error accordions. | -| `extensions-overview.mdx` | 1. Added `description: "Explore CometChat extensions that add enhanced functionality to your Flutter chat application"`
2. Added Quick Reference `` block listing all extension categories: User Experience (Pin message, Link preview, Thumbnails, Voice transcription), User Engagement (Polls, Reactions, Mentions, Message translation, Stickers), Collaboration (Whiteboard, Collaborative documents), Notifications (Push, Email, SMS), Moderation (Content filtering, Profanity detection), Security (Disappearing messages, End-to-end encryption) — with link to full Extensions Overview
3. Added ``: "Available via: SDK \| REST API \| UI Kits"
4. Added Next Steps CardGroup with 3 cards: "AI Features", "Webhooks", "Setup" | The Quick Reference is a comprehensive extension catalog organized by category — developers can quickly find which extension they need. | -| `webhooks-overview.mdx` | 1. Added `description: "Configure server-side webhooks to receive real-time notifications for messages, users, groups, calls, and moderation events in your Flutter application."`
2. Added Quick Reference `` block with: setup requirements (HTTPS endpoint, publicly accessible URL, POST method with `application/json`, return HTTP 200 OK), event categories (Messages: `message_sent`/`message_edited`/`message_deleted`/`message_read_receipt`; Users: `user_blocked`/`user_unblocked`/`user_connection_status_changed`; Groups: `group_created`/`group_member_added`/`group_member_left`; Calls: `call_initiated`/`call_started`/`call_ended`/`recording_generated`; Moderation: `moderation_engine_approved`/`moderation_engine_blocked`), configuration link to Dashboard
3. Added ``: "Webhooks are configured at the application level through the CometChat Dashboard, not within the Flutter SDK. The SDK handles real-time events via listeners, while webhooks deliver events to your backend server."
4. Added Next Steps CardGroup with 3 cards: "Extensions", "Real-Time Listeners", "AI Agents" | The Quick Reference lists all webhook event names — this is valuable for backend developers who need to know which events to listen for. The `` clarifies the SDK vs webhook distinction (SDK = client-side listeners, webhooks = server-side HTTP callbacks). | diff --git a/index.mdx b/index.mdx index bdfa093c2..2ae62f464 100644 --- a/index.mdx +++ b/index.mdx @@ -141,6 +141,14 @@ canonical: "https://cometchat.com/docs" Add CometChat Docs MCP to your AI tools for instant documentation access.
+ + Let your AI coding agent add CometChat chat & calling to your React app. + + + + Authenticate, provision credentials, and manage the skills from your terminal. + +
diff --git a/prompt/documentation-improvement-guidelines.md b/prompt/documentation-improvement-guidelines.md new file mode 100644 index 000000000..30217caae --- /dev/null +++ b/prompt/documentation-improvement-guidelines.md @@ -0,0 +1,1163 @@ +# CometChat SDK Documentation Improvement Guidelines + +These guidelines document the patterns, standards, and improvements applied to SDK documentation. Use this as a reference when improving documentation for any SDK technology (JavaScript, Android, iOS, Flutter, React Native) with AI assistance. + +## Table of Contents + +1. [Quick Reference Blocks](#1-quick-reference-blocks) +2. [Available Via Notes](#2-available-via-notes) +3. [Code Examples: Tab Conventions](#3-code-examples-tab-conventions) +4. [Tab Naming Standards](#4-tab-naming-standards) +5. [Mintlify Components](#5-mintlify-components) +6. [Next Steps Navigation](#6-next-steps-navigation) +7. [Page Structure Templates](#7-page-structure-templates) +8. [Feature Page Anatomy](#8-feature-page-anatomy) +9. [Navigation Organization](#9-navigation-organization) +10. [Integration Guides](#10-integration-guides) +11. [Glossary & Key Concepts](#11-glossary--key-concepts) +12. [Security & Init Warnings](#12-security--init-warnings) +13. [Cross-Linking & References](#13-cross-linking--references) +14. [What NOT to Do](#14-what-not-to-do) +15. [File Classification](#15-file-classification) +16. [File-by-File Checklist](#16-file-by-file-checklist) +17. [Prompt Template for AI Assistants](#17-prompt-template-for-ai-assistants) + +--- + +## 1. Quick Reference Blocks + +Every content page should have a Quick Reference block at the very top, immediately after the frontmatter. + +**Why:** AI agents parsing docs need a fast, copy-paste-ready summary. Developers scanning docs want the TL;DR. + +### Feature Pages (Messaging, Users, Groups, Calling, etc.) + +Show the most common API calls for that feature: + +```mdx +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Send text message to user +const msg = new CometChat.TextMessage("UID", "Hello!", CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMessage(msg); + +// Send to group +const msg = new CometChat.TextMessage("GUID", "Hello!", CometChat.RECEIVER_TYPE.GROUP); +await CometChat.sendMessage(msg); + +// Media message +const msg = new CometChat.MediaMessage("UID", file, CometChat.MESSAGE_TYPE.IMAGE, CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMediaMessage(msg); +``` + +``` + +### Overview/Hub Pages + +For overview pages that link to sub-pages, list the paths instead of code: + +```mdx + +**Quick Reference for AI Agents & Developers** + +Choose your path: +- **Chat Only** → [guide-chat-only](/sdk/javascript/guide-chat-only) - Text, media, groups +- **Calls Only** → [guide-calls-only](/sdk/javascript/guide-calls-only) - Standalone video/audio +- **Chat + Calls** → [guide-chat-calls](/sdk/javascript/guide-chat-calls) - Full communication + +``` + +### Setup/Getting Started Pages + +Show install + init + login in one block: + +```mdx + +**Quick Setup Reference** + +```bash +# Install +npm install @cometchat/chat-sdk-javascript + +# Initialize (run once at app start) +CometChat.init(APP_ID, appSettings) + +# Login (after init) +CometChat.login(UID, AUTH_KEY) # Dev only +CometChat.login(AUTH_TOKEN) # Production +``` + +**Required Credentials:** App ID, Region, Auth Key (dev) or Auth Token (prod) +**Get from:** [CometChat Dashboard](https://app.cometchat.com) → Your App → API & Auth Keys + +``` + +### Reference Pages (Listeners, Message Structure, Key Concepts) + +Show the most-used API calls or constants: + +```mdx + +**Quick Reference for AI Agents & Developers** + +```javascript +// Add message listener +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onTextMessageReceived: (message) => { }, + onMediaMessageReceived: (message) => { } +})); + +// Remove listener +CometChat.removeMessageListener("LISTENER_ID"); +``` + +``` + +### Rules (all page types) + +- Add necessary code examples +- Show the most common use cases +- Use real method names and constants — no pseudocode +- Include comments explaining what each snippet does +- Use `await` style for brevity (async/await is most readable) + +--- + +## 2. Available Via Notes + +Add an "Available via" note on **feature pages only** — pages that document a user-facing capability. + +### What qualifies as a feature page + +- Messaging: `send-message`, `receive-message`, `edit-message`, `delete-message`, `threaded-messages`, `reactions`, `mentions`, `interactive-messages`, `transient-messages` +- Users: `user-presence`, `block-users`, `retrieve-users`, `user-management` +- Groups: `groups-overview`, `create-group`, `join-group`, `leave-group`, `delete-group`, `update-group`, `retrieve-groups`, `retrieve-group-members`, `group-add-members`, `group-kick-ban-members`, `group-change-member-scope`, `transfer-group-ownership` +- Conversations: `retrieve-conversations`, `delete-conversation` +- Receipts & indicators: `delivery-read-receipts`, `typing-indicators` +- Calling: `default-call`/`default-calling`, `direct-call`/`direct-calling`, `call-logs`, `recording` +- AI: `ai-agents`, `ai-chatbots-overview`, `ai-moderation`, `ai-user-copilot-overview` +- Other: `flag-message`, `mentions` + +### What does NOT get "Available via" + +- Setup/installation pages (`overview`, `setup`, `setup-sdk`, `calling-setup`) +- Configuration pages (`managing-web-sockets-connections-manually`, `session-timeout`, `connection-status`) +- Styling/customization pages (`custom-css`, `video-view-customisation`, `virtual-background`, `presenter-mode`) +- Reference pages (`all-real-time-listeners`, `message-structure-and-hierarchy`, `key-concepts`, `login-listener`) +- Guide pages (`guide-chat-only`, `guide-calls-only`, `guide-chat-calls`, `guide-moderation`, `guide-notifications`, `guides`) +- Overview/hub pages that just link to sub-pages (`messaging-overview`, `users-overview`, `calling-overview`, `advanced-overview`, `resources-overview`, `extensions-overview`) +- Migration pages (`upgrading-from-v3`, `upgrading-from-v2`) +- Framework-specific pages (`react-overview`, `angular-overview`, `vue-overview`) +- Changelog, rate limits, webhooks overview +- Standalone calling (implementation approach, not a feature) + +### Pattern + +```mdx + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) + +``` + +### Common combinations + +| Feature Type | Available Via | +| --- | --- | +| Messaging features (send, receive, edit, delete, threads, reactions) | SDK \| REST API \| UI Kits | +| Calling features (ringing, direct call) | SDK \| UI Kits | +| User/Group management | SDK \| REST API \| UI Kits | +| Conversations (retrieve, delete) | SDK \| REST API \| UI Kits | +| Receipts, typing indicators | SDK \| REST API \| UI Kits | +| AI features (moderation, agents, copilot) | SDK \| REST API \| UI Kits \| Dashboard | +| Call logs | SDK \| REST API \| Dashboard | +| Flag/report message | SDK \| REST API \| Dashboard | +| Recording | SDK \| Dashboard | +| Advanced filtering | SDK \| REST API | + +### Placement + +Right after the introductory sentence/paragraph, before the first `##` section heading. + +--- + +## 3. Code Examples: Tab Conventions + +Every code example should provide multiple language variants in tabs. The tabs differ by SDK technology. + +### JavaScript SDK + +```mdx + + +```javascript +CometChat.sendMessage(textMessage).then( + (message) => console.log("Sent:", message), + (error) => console.log("Error:", error) +); +``` + + +```typescript +CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => console.log("Sent:", message), + (error: CometChat.CometChatException) => console.log("Error:", error) +); +``` + + +```javascript +try { + const message = await CometChat.sendMessage(textMessage); + console.log("Sent:", message); +} catch (error) { + console.log("Error:", error); +} +``` + + +``` + +### Android SDK + +```mdx + + +```kotlin +CometChat.sendMessage(textMessage, object : CometChat.CallbackListener() { + override fun onSuccess(message: TextMessage) { + Log.d(TAG, "Message sent: ${message.text}") + } + override fun onError(e: CometChatException) { + Log.e(TAG, "Error: ${e.message}") + } +}) +``` + + +```java +CometChat.sendMessage(textMessage, new CometChat.CallbackListener() { + @Override + public void onSuccess(TextMessage message) { + Log.d(TAG, "Message sent: " + message.getText()); + } + @Override + public void onError(CometChatException e) { + Log.e(TAG, "Error: " + e.getMessage()); + } +}); +``` + + +``` + +### iOS SDK + +```mdx + + +```swift +CometChat.sendTextMessage(message: textMessage, onSuccess: { message in + print("Message sent: \(message.text)") +}, onError: { error in + print("Error: \(error?.errorDescription)") +}) +``` + + +``` + +### Flutter SDK + +```mdx + + +```dart +CometChat.sendMessage(textMessage, onSuccess: (TextMessage message) { + debugPrint("Message sent: ${message.text}"); +}, onError: (CometChatException e) { + debugPrint("Error: ${e.message}"); +}); +``` + + +``` + +### React Native SDK + +```mdx + + +```javascript +CometChat.sendMessage(textMessage).then( + (message) => console.log("Sent:", message), + (error) => console.log("Error:", error) +); +``` + + +```typescript +CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => console.log("Sent:", message), + (error: CometChat.CometChatException) => console.log("Error:", error) +); +``` + + +``` + +### Contextual tabs (all platforms) + +When showing alternative approaches (not language variants), use descriptive tab titles: + +```mdx + + + + + + + + +``` + +```mdx + +... +... +... +... + +``` + +### Rules + +- Every major code block should have language tabs — don't leave single-language examples +- TypeScript tabs should add proper type annotations, not just rename the file +- Async/Await tab (JavaScript SDK) should show try/catch pattern +- Simple one-liners (e.g., `CometChat.disconnect()`) can skip tabs — use a single block +- Keep code copy-paste ready: include variable declarations, imports where needed +- Use realistic placeholder values: `"user_uid"`, `"group_guid"`, `"YOUR_APP_ID"` +- For "To User" / "To Group" tabs, show the same operation for both receiver types + +--- + +## 4. Tab Naming Standards + +Use consistent tab titles across all pages. Never use arbitrary or inconsistent titles. + +### Correct tab titles by platform + +| Platform | Primary Tab | Secondary Tab | Tertiary Tab | +| --- | --- | --- | --- | +| JavaScript SDK | `JavaScript` | `TypeScript` | `Async/Await` | +| Android SDK | `Kotlin` | `Java` | — | +| iOS SDK | `Swift` | `Objective-C` (if supported) | — | +| Flutter SDK | `Dart` | — | — | +| React Native SDK | `JavaScript` | `TypeScript` | — | + +### Contextual tab titles (all platforms) + +| Tab Content | Title | +| --- | --- | +| Send to user | `To User` | +| Send to group | `To Group` | +| npm install | `npm` | +| yarn install | `yarn` | +| pnpm install | `pnpm` | +| CDN script tag | `CDN` | +| ES Module import | `ES Modules` | +| CommonJS require | `CommonJS` | +| Dashboard setup | `Dashboard (Testing)` | +| REST API setup | `REST API (Production)` | +| SDK setup | `SDK (On-the-fly)` | +| All users presence | `All Users` | +| By role presence | `By Role` | +| Friends only presence | `Friends Only` | +| File input upload | `From File Input` | +| URL upload | `From URLs` | +| Users only filter | `Users Only` | +| Groups only filter | `Groups Only` | +| Hide AI agents | `Hide AI Agents` | +| Only AI agents | `Only AI Agents` | + +### When to use language tabs vs contextual tabs + +- **Language tabs** (JavaScript/TypeScript/Async/Await): When showing the same code in different language styles +- **Contextual tabs** (To User/To Group, npm/yarn): When showing alternative approaches or configurations +- **Framework tabs** (React/Next.js/Vue/Angular/Nuxt): When showing framework-specific implementations + +--- + +## 5. Mintlify Components + +Use these Mintlify components consistently across all pages: + +### Steps — For sequential procedures + +```mdx + + + npm install @cometchat/chat-sdk-javascript + + + CometChat.init(appID, appSettings); + + +``` + +**Use for:** Setup flows, multi-step procedures, getting started guides, authentication flows. + +### Tabs — For code variants and alternative approaches + +**Use for:** Language variants (JS/TS/Async), package manager options (npm/yarn), platform-specific code, alternative approaches (To User/To Group), framework-specific implementations (React/Vue/Angular). + +### CardGroup + Card — For navigation and next steps + +```mdx + + + Send text, media, and custom messages + + +``` + +**Use for:** Next Steps sections, feature overviews, choosing between options, guide hub pages. + +### AccordionGroup + Accordion — For supplementary info + +```mdx + + + Explanation of the best practice. + + +``` + +**Use for:** Best practices, FAQs, troubleshooting tips, edge cases, common errors, framework-specific patterns. + +### Note, Warning, Info — For callouts + +```mdx +Informational callout — general tips and context. +Critical warning — data loss, security, breaking changes. +Highlighted info — quick references, availability, requirements. +``` + +**Use for:** + +- `` — Prerequisites, tips, general information, "Available via" notes, test user info +- `` — Destructive operations, security concerns (Auth Key in production), init-before-login, mutually exclusive options +- `` — Quick references, feature requirements, plan restrictions, feature flags + +### Frame — For images/screenshots + +```mdx + + + +``` + +**Use for:** Architecture diagrams, flow diagrams, dashboard screenshots. + +### Mermaid — For flow diagrams + +```mdx +```mermaid +sequenceDiagram + participant User + participant App + participant CometChat + User->>App: Login + App->>CometChat: CometChat.login() +``` +``` + +**Use for:** Authentication flows, message delivery flows, call signaling flows. Preserve existing mermaid diagrams — never remove them. + +--- + +## 6. Next Steps Navigation + +Every content page should end with a `## Next Steps` section using CardGroup. + +### Pattern + +```mdx +--- + +## Next Steps + + + + One-line description of what they'll learn + + + One-line description + + +``` + +### Rules + +- Always use `cols={2}` for consistency +- Include 2–4 cards (not more) +- Link to logically next topics (what would the developer need after this?) +- Use descriptive FontAwesome icon names +- Keep descriptions to one short sentence +- Use `## Next Steps` as the heading — not `## Next Steps & Further Reading` or other variants +- Do NOT include bullet-list links alongside the CardGroup — the cards are sufficient + +### Logical next step patterns + +| Current Page | Suggested Next Steps | +| --- | --- | +| Overview | Setup SDK, Key Concepts | +| Setup SDK | Authentication, Send First Message | +| Authentication | Send Message, User Management | +| Send Message | Receive Messages, Edit Message, Interactive Messages | +| Receive Message | Delivery Receipts, Typing Indicators | +| Edit Message | Delete Message, Send Message | +| Delete Message | Edit Message, Receive Message | +| Threaded Messages | Send Message, Receive Message | +| Reactions | Send Message, Receive Message | +| Mentions | Send Message, Receive Message | +| Users Overview | Retrieve Users, User Presence, Block Users | +| User Presence | Retrieve Users, Connection Status | +| Block Users | Retrieve Users, User Management | +| Groups Overview | Create Group, Retrieve Groups | +| Create Group | Join Group, Add Members | +| Join Group | Leave Group, Retrieve Members | +| Retrieve Conversations | Delete Conversation, Typing Indicators, Read Receipts | +| Calling Overview | Calling Setup, Default Call | +| Default Call (Ringing) | Direct Call, Call Logs, Recording | +| Direct Call | Default Call, Recording | +| Call Logs | Default Call, Recording | +| AI Agents | AI Chatbots, AI Moderation | +| Guides Hub | Individual guides | +| Key Concepts | Setup SDK, Send Message | + +--- + +## 7. Page Structure Templates + +### Feature Page Structure + +```text +1. Frontmatter (title, sidebarTitle, description) +2. Quick Reference block (Info component with code) +3. Introductory sentence (1-2 lines, what this feature does) +4. Available Via note (feature pages only) +5. Main content sections with code examples in tabs +6. Parameter tables after code examples +7. Common Use Cases / Examples +8. Real-Time Events / Listeners (if applicable) +9. Best Practices (AccordionGroup) — if applicable +10. Troubleshooting (AccordionGroup) — if applicable +11. Next Steps (CardGroup) +``` + +### Overview/Hub Page Structure + +```text +1. Frontmatter (title, sidebarTitle, description) +2. Quick Reference block (Info with links to sub-pages) +3. Introductory paragraph +4. Available Via note (if this is a feature overview like Groups Overview) +5. Key concepts / types / constants tables +6. Quick Start examples +7. Sub-feature CardGroups (management, membership, etc.) +8. Object properties table +9. Common Use Cases with code +10. Real-Time Events +11. Next Steps (CardGroup) +``` + +### Setup/Getting Started Page Structure + +```text +1. Frontmatter (title, sidebarTitle, description) +2. Quick Reference block (Info with install + init + login) +3. Intro paragraph +4. Prerequisites (Steps component) +5. Installation (Tabs for npm/yarn/pnpm/CDN) +6. Import (Tabs for ES Modules/CommonJS/CDN) +7. Initialize CometChat (Tabs for JS/TS/Async) +8. Complete Quick Start example +9. Configuration Options (tables + code) +10. Framework Integration (Tabs for React/Next.js/Vue/Angular/Nuxt) +11. Next Steps (CardGroup) +``` + +### Authentication Page Structure + +```text +1. Frontmatter (title, sidebarTitle, description) +2. Quick Reference block (Info with login methods) +3. Intro paragraph + note about user management +4. Authentication Flow (mermaid diagram) +5. Choose Your Method (CardGroup: Auth Key vs Auth Token) +6. Create a User (Tabs: Dashboard/REST API/SDK) +7. Login with Auth Key (Tabs: JS/TS/Async) + Warning +8. Login with Auth Token (Tabs: JS/TS/Async) + Steps +9. Check Login Status +10. Logout +11. Server-Side Token Generation (Tabs: Node.js/Python) +12. User Object properties table +13. Login Listeners +14. Best Practices (AccordionGroup) +15. Troubleshooting (AccordionGroup) +16. Next Steps (CardGroup) +``` + +### Guide Page Structure + +```text +1. Frontmatter (title, sidebarTitle, description) +2. Quick Reference block (Info with guide path links) +3. What you'll build (outcome) +4. Prerequisites (accounts, keys, dependencies) +5. Step-by-step implementation (Steps component) +6. Complete working code at the end +7. Integration Checklist +8. Next Steps (CardGroup — related guides + feature docs) +``` + +### Migration Page Structure + +```text +1. Frontmatter (title, description) +2. Quick Reference block (Info with summary of key changes) +3. Breaking changes list +4. Migration steps +5. API changes tables +6. Next Steps (CardGroup) +``` + +### Frontmatter template + +```yaml +--- +title: "Human-Readable Title" +sidebarTitle: "Short Sidebar Name" # Optional, only if title is too long for sidebar +description: "One sentence describing what this page covers" +--- +``` + +--- + +## 8. Feature Page Anatomy + +Every SDK feature page follows a consistent structure. When improving these pages, enhance each section without changing the order. + +### 1. Quick Reference + Intro + +- Quick Reference block with copy-paste ready code +- 1–2 sentence description of what the feature does +- "Available via" note (feature pages only) +- Type/method overview table (if multiple operations exist) + +### 2. Main Operations + +Each operation gets its own `##` section with: +- Code examples in language tabs (JS/TS/Async or platform equivalents) +- Contextual tabs where applicable (To User / To Group) +- Parameter table after the code +- Optional features (metadata, tags, etc.) as sub-sections + +### 3. Response/Object Properties + +- Table showing the returned object's properties +- Getter methods and their return types +- Example code accessing properties + +### 4. Filtering / Request Builders + +- `RequestBuilder` pattern with all available methods +- Filter options table +- Pagination examples (`fetchNext()` pattern) + +### 5. Real-Time Events / Listeners + +- Listener registration code +- All event callbacks documented +- Cleanup/removal code +- Link to full listeners reference + +### 6. Common Use Cases + +- Complete working examples for typical scenarios +- Framework-specific examples (React hooks, Vue composables, etc.) + +### 7. Best Practices & Troubleshooting + +- AccordionGroup with best practices +- AccordionGroup with common errors and solutions + +### 8. Next Steps + +- CardGroup with 2-4 related pages + +### Adding Missing Tabs + +When improving existing pages: + +- If a code block shows `.then()` pattern → add TypeScript and Async/Await tabs +- If a code block shows only Async/Await → add JavaScript (.then()) and TypeScript tabs +- If a code block shows only TypeScript → add JavaScript and Async/Await tabs +- For Android: if only Java → add Kotlin tab; if only Kotlin → add Java tab +- Do NOT convert existing single-tab examples to no-tab code blocks — always keep tabs + +### Parameter Table Format + +The existing SDK docs use this table format: + +```markdown +| Parameter | Type | Description | +| --- | --- | --- | +| `receiverID` | string | UID of user or GUID of group | +| `messageText` | string | The text content | +| `receiverType` | string | `CometChat.RECEIVER_TYPE.USER` or `GROUP` | +``` + +Preserve this format. When adding new parameters, follow the same pattern. + +### Object Properties Table Format + +```markdown +| Property | Method | Description | +| --- | --- | --- | +| ID | `getConversationId()` | Unique conversation identifier | +| Type | `getConversationType()` | `user` or `group` | +| Last Message | `getLastMessage()` | Most recent message object | +``` + +### Filter Options Table Format + +```markdown +| Method | Description | +| --- | --- | +| `setLimit(limit)` | Number of results (max 50) | +| `setSearchKeyword(keyword)` | Search by name | +| `setTags(tags)` | Filter by tags | +``` + +--- + +## 9. Navigation Organization + +The SDK sidebar should follow this structure (adapt per technology): + +```text +SDK v4 +├── Overview +├── Setup +├── Key Concepts +├── Authentication +│ └── Login, Logout, Auth Tokens +├── Messaging +│ ├── Overview +│ ├── Send Message +│ ├── Receive Message +│ ├── Edit / Delete Message +│ ├── Threaded Messages +│ ├── Reactions +│ ├── Mentions +│ ├── Message Structure & Hierarchy +│ ├── Interactive Messages +│ ├── Transient Messages +│ └── Additional Message Filtering +├── Users +│ ├── Overview +│ ├── Retrieve Users +│ ├── User Presence +│ ├── Block Users +│ └── User Management +├── Groups +│ ├── Overview +│ ├── Create / Update / Delete Group +│ ├── Join / Leave Group +│ ├── Retrieve Groups / Members +│ ├── Add Members / Kick-Ban +│ ├── Change Scope / Transfer Ownership +├── Conversations +│ ├── Retrieve Conversations +│ └── Delete Conversation +├── Receipts & Indicators +│ ├── Delivery & Read Receipts +│ ├── Typing Indicators +│ └── Flag Message +├── Calling +│ ├── Overview +│ ├── Setup +│ ├── Default Calling (Ringing) +│ ├── Direct Calling +│ ├── Standalone Calling +│ ├── Recording +│ ├── Call Logs +│ ├── Session Timeout +│ ├── Presenter Mode +│ ├── Virtual Background +│ ├── Video View Customisation +│ └── Custom CSS +├── AI Features +│ ├── AI Agents +│ ├── AI Chatbots +│ ├── AI Moderation +│ └── AI User Copilot +├── Advanced +│ ├── Connection Status +│ ├── WebSocket Management +│ ├── Login Listeners +│ ├── All Real-Time Listeners +│ └── Webhooks +├── Integration Guides +│ ├── Hub Page +│ ├── Chat Only +│ ├── Calls Only +│ ├── Chat + Calls +│ ├── Moderation +│ └── Notifications +├── Framework Guides (JavaScript SDK only) +│ ├── React +│ ├── Angular +│ └── Vue +├── Resources +│ ├── Rate Limits +│ ├── Extensions +│ └── Changelog +└── Migration Guide +``` + +--- + +## 10. Integration Guides + +The SDK should have step-by-step integration guides for common scenarios. These are separate from feature docs — they walk through a complete implementation from zero. + +### Guides to have + +- **Chat Only** — Text + media + groups (no calling) +- **Calls Only** — Standalone video/audio (no chat SDK) +- **Chat + Calls** — Full communication suite +- **Moderation** — Content filtering setup +- **Notifications** — Push alerts + +### Guide structure + +```text +1. What you'll build (outcome) +2. Prerequisites (accounts, keys, dependencies) +3. Step-by-step implementation (Steps component) +4. Complete working code at the end +5. Integration checklist +6. Next steps / what to add +``` + +### Rules + +- Every step must have copy-paste ready code +- Include expected output or what the developer should see +- Link back to detailed feature docs for customization +- Keep guides focused — one scenario per guide +- Include a "Quick Decision Guide" table on the hub page + +--- + +## 11. Glossary & Key Concepts + +SDK-specific terms that should be defined or linked when first used: + +| Term | Definition | +| --- | --- | +| UID | Unique User Identifier — alphanumeric string you assign to each user | +| GUID | Group Unique Identifier — alphanumeric string you assign to each group | +| Auth Key | Development-only credential for quick testing. Never use in production | +| Auth Token | Secure, per-user token generated via REST API. Use in production | +| REST API Key | Server-side credential for REST API calls. Never expose in client code | +| Receiver Type | Specifies if a message target is a `user` or `group` | +| Scope | Group member role: `admin`, `moderator`, or `participant` | +| Listener | Callback handler for real-time events (messages, presence, calls, groups) | +| Conversation | A chat thread between two users or within a group | +| Metadata | Custom JSON data attached to users, groups, or messages | +| Tags | String labels for categorizing users, groups, conversations, or messages | +| RequestBuilder | Builder pattern class for constructing filtered/paginated queries | +| AppSettings | Configuration object for initializing the SDK (App ID, Region, presence) | +| Transient Message | Ephemeral message not stored on server (typing indicators, live reactions) | +| Interactive Message | Message with actionable UI elements (forms, cards, buttons) | + +Include 10–20 terms. Define acronyms. Link to relevant pages where the concept is explained in detail. + +--- + +## 12. Security & Init Warnings + +### Init Warning + +```mdx + +`CometChat.init()` must be called before any other SDK method. Calling `login()`, `sendMessage()`, or registering listeners before `init()` will fail. + +``` + +### Auth Key Warning + +```mdx + +**Auth Key** is for development/testing only. In production, generate **Auth Tokens** on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + +``` + +### SSR/Framework Note (JavaScript SDK only) + +```mdx + +**Server-Side Rendering (SSR):** CometChat SDK requires browser APIs (`window`, `WebSocket`). For Next.js, Nuxt, or other SSR frameworks, initialize the SDK only on the client side using dynamic imports or `useEffect`. See the [Framework Integration](/sdk/javascript/setup-sdk#framework-integration) section. + +``` + +### Listener Cleanup Warning + +```mdx + +Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +``` + +### Destructive Operation Warning + +```mdx + +This operation is irreversible. Deleted [messages/groups/conversations] cannot be recovered. + +``` + +### Placement + +- Init + Auth Key warnings: on `overview` and `setup` pages +- SSR note: on `overview` and framework-specific pages (JavaScript SDK only) +- Listener cleanup: on any page that registers listeners +- Destructive warnings: on delete pages (`delete-message`, `delete-group`, `delete-conversation`) + +--- + +## 13. Cross-Linking & References + +Link related concepts together. When a page references a concept explained elsewhere, add an inline link. + +### Standard cross-links + +- On messaging pages: "For a deeper understanding of how messages are structured, see [Message Structure & Hierarchy](/sdk/[tech]/message-structure-and-hierarchy)." +- On any page using listeners: "Remember to [remove listeners](/sdk/[tech]/all-real-time-listeners) when they're no longer needed." +- On pages using RequestBuilders: "See [Additional Message Filtering](/sdk/[tech]/additional-message-filtering) for all builder options." +- On feature pages: Link to the REST API equivalent when available. +- On calling pages: Link to [Calling Setup](/sdk/[tech]/calling-setup) for SDK installation. +- On AI pages: Link to Dashboard for enabling features. + +### Related feature links + +- Send Message → Receive Message, Edit Message, Delete Message +- Receive Message → Delivery Receipts, Typing Indicators +- Create Group → Join Group, Add Members, Retrieve Groups +- Groups Overview → all group sub-pages +- Users Overview → all user sub-pages +- Default Call ↔ Direct Call ↔ Standalone Calling +- Retrieve Conversations → Delete Conversation, Typing Indicators + +--- + +## 14. What NOT to Do + +Lessons learned from the SDK documentation improvement process: + +1. **Do NOT remove existing prose or explanatory text.** Even if it seems verbose, developers rely on explanations. Only add — never subtract content. + +2. **Do NOT remove code examples.** Every code snippet exists for a reason. Add more variants (TypeScript, Async/Await, Kotlin) but never remove existing ones. + +3. **Do NOT remove mermaid diagrams or flow charts.** Visual aids help developers understand authentication flows, message delivery, and call signaling. + +4. **Do NOT remove framework-specific guides.** React, Angular, Vue, Next.js, Nuxt guides are all valuable even if they seem redundant. + +5. **Do NOT minimize or condense docs.** The goal is comprehensive, not concise. More detail is better than less. + +6. **Do NOT add "Available via" to non-feature pages.** Setup guides, configuration pages, reference pages, guide pages, and migration pages should not have availability notes. + +7. **Do NOT change section headings** that developers may have bookmarked or that other pages link to. + +8. **Do NOT restructure content within pages** unless explicitly asked. Navigation reorganization (sidebar order) is fine; content reorganization within pages is risky. + +9. **Do NOT remove AccordionGroup sections** (best practices, troubleshooting, common errors). These are high-value for developers debugging issues. + +10. **Do NOT remove server-side code examples** (Node.js, Python token generation). These are critical for production implementations. + +11. **Do NOT add UI Kit component code to SDK docs.** SDK docs show raw API calls. UI Kit component rendering belongs in UI Kit docs. + +12. **Do NOT remove "Complete Working Example" sections.** These end-to-end examples are the most valuable part of many pages. + +--- + +## 15. File Classification + +### Full Treatment (Quick Reference + Available Via + Next Steps) + +**Messaging feature pages:** +- `send-message`, `receive-message`, `edit-message`, `delete-message` +- `threaded-messages`, `reactions`, `mentions` +- `interactive-messages`, `transient-messages` +- `delivery-read-receipts`, `typing-indicators` +- `flag-message` + +**User feature pages:** +- `user-presence`, `block-users`, `retrieve-users`, `user-management` + +**Group feature pages:** +- `groups-overview`, `create-group`, `join-group`, `leave-group`, `delete-group`, `update-group` +- `retrieve-groups`, `retrieve-group-members` +- `group-add-members`, `group-kick-ban-members` / `group-kick-member` +- `group-change-member-scope`, `transfer-group-ownership` + +**Conversation feature pages:** +- `retrieve-conversations`, `delete-conversation` + +**Calling feature pages:** +- `default-call` / `default-calling`, `direct-call` / `direct-calling` +- `call-logs`, `recording` + +**AI feature pages:** +- `ai-agents`, `ai-chatbots-overview`, `ai-moderation`, `ai-user-copilot-overview` + +### Quick Reference + Next Steps Only (No "Available Via") + +**Setup/config pages:** +- `overview`, `setup` / `setup-sdk`, `calling-setup` +- `key-concepts`, `authentication-overview` + +**Reference pages:** +- `all-real-time-listeners` / `all-real-time-delegates-listeners` +- `message-structure-and-hierarchy` +- `additional-message-filtering` +- `connection-status`, `session-timeout` +- `managing-web-sockets-connections-manually` / `managing-web-socket-connections-manually` +- `login-listener` / `login-listeners` + +**Calling config/customization pages:** +- `standalone-calling`, `presenter-mode`, `virtual-background` +- `video-view-customisation`, `custom-css` + +**Overview/hub pages:** +- `messaging-overview`, `users-overview`, `groups-overview` (gets Available Via), `calling-overview` +- `advanced-overview`, `resources-overview`, `extensions-overview` +- `ai-user-copilot-overview` (gets Available Via — it's a feature) + +**Guide pages:** +- `guides`, `guide-chat-only`, `guide-calls-only`, `guide-chat-calls` +- `guide-moderation`, `guide-notifications` + +**Framework pages (JavaScript SDK only):** +- `react-overview`, `angular-overview`, `vue-overview` + +**Migration pages:** +- `upgrading-from-v3`, `upgrading-from-v2`, `upgrading-from-v3-to-v4` + +**Platform-specific pages:** +- `android-overview`, `ios-overview` +- `publishing-app-on-playstore`, `publishing-app-on-appstore` +- `connection-behaviour`, `web-socket-connection-behaviour` +- Platform-specific push notification pages (iOS) + +**Resource pages:** +- `rate-limits`, `webhooks-overview` + +### Skip Entirely + +- `changelog` (auto-generated or link page) +- Legacy version folders (`2.0/`, `3.0/`) +- `research.md` (internal notes) + +--- + +## 16. File-by-File Checklist + +Use this checklist when improving each SDK documentation file: + +```text +[ ] Frontmatter has title, description (and sidebarTitle if needed) +[ ] Quick Reference block present at top (Info component with code) +[ ] "Available via" note present (ONLY if this is a feature page) +[ ] Introductory sentence explains what the feature does +[ ] All code examples have language tabs (JS/TS/Async or platform equivalents) +[ ] Tab titles use standard names (JavaScript/TypeScript/Async/Await, Kotlin/Java, Swift, Dart) +[ ] Parameter tables follow code examples where applicable +[ ] Object properties tables present for returned objects +[ ] Filter options table present for RequestBuilder pages +[ ] Pagination example shown for list/fetch operations +[ ] Real-time listeners documented with register + cleanup code +[ ] Best Practices section (AccordionGroup) where applicable +[ ] Troubleshooting section (AccordionGroup) where applicable +[ ] Next Steps section at bottom with CardGroup (2-4 relevant links) +[ ] Next Steps uses ## Next Steps heading (not variants) +[ ] No bullet-list links alongside CardGroup in Next Steps +[ ] Cross-links to related pages where concepts are referenced +[ ] Security warnings where applicable (init, auth keys, destructive operations) +[ ] Listener cleanup warnings on pages that register listeners +[ ] No content, code examples, diagrams, or explanatory text removed +[ ] Code is copy-paste ready with realistic placeholders +[ ] Mermaid diagrams preserved (never removed) +[ ] Framework-specific examples preserved +[ ] Server-side code examples preserved +[ ] Page reads naturally from top to bottom — journey feels logical +``` + +--- + +## 17. Prompt Template for AI Assistants + +When asking an AI assistant to improve SDK docs for any technology, use this prompt: + +```text +Improve the [TECHNOLOGY] SDK documentation files following these guidelines: + +1. Add a Quick Reference block at the top of every content page using component + with copy-paste ready code snippets (5-15 lines, most common use cases) + +2. Add "Available via: SDK | REST API | UI Kits" notes on FEATURE PAGES ONLY + (not setup, config, reference, guide, or migration pages) + +3. Ensure all code examples have language tabs: + - For JavaScript: JavaScript | TypeScript | Async/Await + - For Android: Kotlin | Java + - For iOS: Swift + - For Flutter: Dart + - For React Native: JavaScript | TypeScript + +4. Use standard tab titles: "JavaScript", "TypeScript", "Async/Await", "Kotlin", "Java", etc. + Use contextual titles for approach tabs: "To User", "To Group", "npm", "yarn" + +5. Add a description field to frontmatter on every page + +6. Add Next Steps navigation at the bottom of every page using + with 2-4 cards linking to logically next topics. Use ## Next Steps heading only. + +7. Use Mintlify components: , , , , + , , , , , + +8. CRITICAL: Do NOT remove any existing content, code examples, mermaid diagrams, + framework guides, server-side examples, or explanatory text. Only ADD improvements. + +9. Add cross-links between related feature pages + +10. Add security warnings on init/login pages + (Auth Key for dev only, Auth Token for production) + +11. Add listener cleanup warnings on pages that register listeners + +12. Add Best Practices and Troubleshooting AccordionGroups where applicable + +13. Preserve existing mermaid diagrams and flow charts + +Reference: sdk/documentation-improvement-guidelines.md +``` + +--- \ No newline at end of file diff --git a/sdk/android/v5/additional-message-filtering.mdx b/sdk/android/v5/additional-message-filtering.mdx index 6532fb806..a32f60db7 100644 --- a/sdk/android/v5/additional-message-filtering.mdx +++ b/sdk/android/v5/additional-message-filtering.mdx @@ -1263,7 +1263,7 @@ val UID = "cometchat-uid-1" val messagesRequest = MessagesRequestBuilder() .setLimit(50) .setUID(UID) - .setAttachmemnt(attachmentTypes) + .setAttachmentTypes(attachmentTypes) .build() ``` diff --git a/sdk/android/v5/delivery-read-receipts.mdx b/sdk/android/v5/delivery-read-receipts.mdx index 93f59de93..315f0e6c4 100644 --- a/sdk/android/v5/delivery-read-receipts.mdx +++ b/sdk/android/v5/delivery-read-receipts.mdx @@ -225,7 +225,7 @@ CometChat.markAsRead(message.id, message.sender.uid, CometChatConstants.RECEIVER ```java -CometChat.markAsRead(message.getId(), message.getReceiverUID(), CometChatConstants.RECEIVER_TYPE_GROUP,message.getSender().getUid()) +CometChat.markAsRead(message.getId(), message.getReceiverUid(), CometChatConstants.RECEIVER_TYPE_GROUP,message.getSender().getUid()) ``` @@ -263,7 +263,7 @@ CometChat.markAsRead(message.getId(), message.getSender().getUid(),CometChatCons ```java -CometChat.markAsRead(message.getId(), message.getRecieverUID(), CometChatConstants.RECEIVER_TYPE_USER, message.getSender().getUid(), new CometChat.CallbackListener() { +CometChat.markAsRead(message.getId(), message.getReceiverUid(), CometChatConstants.RECEIVER_TYPE_USER, message.getSender().getUid(), new CometChat.CallbackListener() { @Override public void onSuccess(Void unused) { Log.e(TAG, "markAsRead : " + "Success"); diff --git a/sdk/android/v5/edit-message.mdx b/sdk/android/v5/edit-message.mdx index a710c009c..73cc2f039 100644 --- a/sdk/android/v5/edit-message.mdx +++ b/sdk/android/v5/edit-message.mdx @@ -87,7 +87,7 @@ CometChat.editMessage(updatedMessage, object: CometChat.CallbackListener -The object of the edited message will be returned in the `onSucess()` callback method of the listener. The message object will contain the `editedAt` field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The `editedBy` field is also set to the `UID` of the user who edited the message. +The object of the edited message will be returned in the `onSuccess()` callback method of the listener. The message object will contain the `editedAt` field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The `editedBy` field is also set to the `UID` of the user who edited the message. By default, CometChat allows certain roles to edit a message. diff --git a/sdk/android/v5/flag-message.mdx b/sdk/android/v5/flag-message.mdx index 0843d2902..ea962c80d 100644 --- a/sdk/android/v5/flag-message.mdx +++ b/sdk/android/v5/flag-message.mdx @@ -69,7 +69,7 @@ Before flagging a message, retrieve the list of available flag reasons configure Log.d(TAG, "Flag reasons fetched: " + reasons); // Use reasons to populate your report dialog UI for (FlagReason reason : reasons) { - Log.d(TAG, "Reason ID: " + reason.getId() + ", Title: " + reason.getReason()); + Log.d(TAG, "Reason ID: " + reason.getId() + ", Title: " + reason.getName()); } } diff --git a/sdk/android/v5/llms-android-v5.mdx b/sdk/android/v5/llms-android-v5.mdx new file mode 100644 index 000000000..1aed991bb --- /dev/null +++ b/sdk/android/v5/llms-android-v5.mdx @@ -0,0 +1,139 @@ +--- +title: "Android Chat SDK v5 — LLM docs index" +description: "Machine-readable, Android-SDK-v5-scoped index of every SDK page as a clean .md twin. Built for AI coding agents; kept out of the human sidebar." +--- + +{/* + SCOPED LLM INDEX for the Android Chat SDK v5. + - UNLISTED, NOT hidden: intentionally omitted from docs.json navigation so it never shows in + the human sidebar — but it IS built, served as a clean .md twin, and INDEXED for search + + AI assistants (so AI tools, and this pack's skill via its docs-map, can discover and read it). + - We deliberately do NOT use `hidden: true`/`noindex` here: in Mintlify `hidden` auto-applies + noindex, which would drop this page from search AND the auto global llms.txt / AI context. + We want it discoverable, so it stays indexable. + - Fetch this file's own .md twin as a lightweight, Android-SDK-only routing index instead of + the site-wide /docs/llms.txt (which spans every product and is far larger). + - URL NOTE: Android SDK v5 pages live under the versioned path /sdk/android/v5/... — + the unversioned /sdk/android/... tree is v4. Do not mix them. +*/} + +# Android Chat SDK v5 — LLM docs index (Latest) + +> Low-level Android (Kotlin/Java) chat + calling client. Gradle coordinate +> `com.cometchat:chat-sdk-android:5.+` (calls add `com.cometchat:calls-sdk-android:5.+`). This +> page is an **Android-SDK-v5-only** routing index for AI agents — a scoped alternative to the +> site-wide `/docs/llms.txt`. + +## How to use this index +Each link points to the docs page; **append `.md`** to its URL to fetch the clean Markdown twin +(verbatim code + method signatures, parameters, and listener contracts). Pick the page for the +intent, then read the API there. +- Convention: any docs page URL + `.md` → raw Markdown. +- Fallback: if a `.md` twin 404s, fetch the same URL **without** `.md` (HTML). Never answer + APIs from memory. +- Pages show Kotlin and Java variants side by side where they differ. + +## Hot path — usually no fetch needed +For a plain "add chat" the Gradle setup, `init → login`, and the core send/receive listener flow +are stable; a well-built agent skill bakes them. Fetch below only for exhaustive parameters, +long-tail methods, group/user management, calling, or edge-case listeners. +- Setup: [Integration / Setup](/sdk/android/v5/setup) +- Auth/lifecycle: [Authentication](/sdk/android/v5/authentication-overview) +- Core send/receive: [Send a Message](/sdk/android/v5/send-message) · [Receive Messages](/sdk/android/v5/receive-messages) · [Real-time Listeners](/sdk/android/v5/real-time-listeners) + +## Getting started / integration +- [Android SDK — Overview](/sdk/android/v5/android-overview) +- [Overview](/sdk/android/v5/overview) +- [Integration / Setup](/sdk/android/v5/setup) +- [Key Concepts](/sdk/android/v5/key-concepts) +- [Authentication](/sdk/android/v5/authentication-overview) +- [Login Listeners](/sdk/android/v5/login-listeners) + +## Messaging +- [Messaging — Overview](/sdk/android/v5/messaging-overview) +- [Send a Message](/sdk/android/v5/send-message) +- [Media & File Messages](/sdk/android/v5/upload-files) +- [Receive Messages](/sdk/android/v5/receive-messages) +- [Additional Message Filtering](/sdk/android/v5/additional-message-filtering) +- [Retrieve Conversations](/sdk/android/v5/retrieve-conversations) +- [Threaded Messages](/sdk/android/v5/threaded-messages) +- [Edit a Message](/sdk/android/v5/edit-message) +- [Delete a Message](/sdk/android/v5/delete-message) +- [Flag a Message](/sdk/android/v5/flag-message) +- [Delete a Conversation](/sdk/android/v5/delete-conversation) +- [Typing Indicators](/sdk/android/v5/typing-indicators) +- [Delivery & Read Receipts](/sdk/android/v5/delivery-read-receipts) +- [Transient Messages](/sdk/android/v5/transient-messages) +- [Mentions](/sdk/android/v5/mentions) +- [Reactions](/sdk/android/v5/reactions) + +## Calling +- [Calling — Overview](/sdk/android/v5/calling-overview) + +## Users +- [Users — Overview](/sdk/android/v5/users-overview) +- [Retrieve Users](/sdk/android/v5/retrieve-users) +- [User Management](/sdk/android/v5/user-management) +- [Block Users](/sdk/android/v5/block-users) +- [User Presence](/sdk/android/v5/user-presence) + +## Groups +- [Groups — Overview](/sdk/android/v5/groups-overview) +- [Retrieve Groups](/sdk/android/v5/retrieve-groups) +- [Create a Group](/sdk/android/v5/create-group) +- [Update a Group](/sdk/android/v5/update-group) +- [Join a Group](/sdk/android/v5/join-group) +- [Leave a Group](/sdk/android/v5/leave-group) +- [Delete a Group](/sdk/android/v5/delete-group) +- [Retrieve Group Members](/sdk/android/v5/retrieve-group-members) +- [Add Group Members](/sdk/android/v5/group-add-members) +- [Kick / Ban Members](/sdk/android/v5/group-kick-member) +- [Change Member Scope](/sdk/android/v5/group-change-member-scope) +- [Transfer Group Ownership](/sdk/android/v5/transfer-group-ownership) + +## AI & advanced features +- [AI Moderation](/sdk/android/v5/ai-moderation) +- [AI Agents](/sdk/android/v5/ai-agents) +- [AI User Copilot — Overview](/sdk/android/v5/ai-user-copilot-overview) +- [AI Chatbots — Overview](/sdk/android/v5/ai-chatbots-overview) +- [Campaigns](/sdk/android/v5/campaigns) +- [Extensions — Overview](/sdk/android/v5/extensions-overview) +- [Webhooks — Overview](/sdk/android/v5/webhooks-overview) + +## Resources & listeners +- [Resources — Overview](/sdk/android/v5/resources-overview) +- [Real-time Listeners](/sdk/android/v5/real-time-listeners) +- [Message Structure & Hierarchy](/sdk/android/v5/message-structure-and-hierarchy) +- [Rate Limits](/sdk/android/v5/rate-limits) + +## Advanced +- [Advanced — Overview](/sdk/android/v5/advanced-overview) +- [Connection Status](/sdk/android/v5/connection-status) +- [Connection Behaviour](/sdk/android/v5/connection-behaviour) +- [Publishing your app on the Play Store](/sdk/android/v5/publishing-app-on-playstore) + +## Want ready-made UI instead? — the Android UI Kit +This SDK is headless: it gives you data and methods, no screens. If the app needs a conversation +list, a message list or a composer, the UI Kit already ships them (and sits on this SDK, so +`init`/`login` are shared — never initialise twice). +- **Android UI Kit v6 — scoped LLM index:** [llms-android-v6](/ui-kit/android/llms-android-v6) +- Use the SDK directly for what the kit has no component for: unread counts, webhooks, low-level + presence/connection, granular group management, ban/unban round-trips. + +## Feature switched on OUTSIDE the app — dashboard, extensions, AI +Sending the right SDK call is not enough when the capability is dashboard-gated. These pages are +outside the SDK tree: +- Start here: [Extensions overview](/fundamentals/extensions-overview) · [Key concepts](/fundamentals/key-concepts) +- **Message extensions:** [Polls](/fundamentals/polls) · [Stickers](/fundamentals/stickers) · [Collaborative whiteboard](/fundamentals/collaborative-whiteboard) · [Collaborative document](/fundamentals/collaborative-document) · [Link preview](/fundamentals/link-preview) · [Message translation](/fundamentals/message-translation) · [Thumbnail generation](/fundamentals/thumbnail-generation) +- **AI (user copilot):** [Overview](/fundamentals/ai-user-copilot/overview) · [Smart replies](/fundamentals/ai-user-copilot/smart-replies) · [Conversation starter](/fundamentals/ai-user-copilot/conversation-starter) · [Conversation summary](/fundamentals/ai-user-copilot/conversation-summary) · [AI agents](/ai-agents) +- **Moderation:** [Moderation extensions](/fundamentals/moderation-extensions) · [Overview](/moderation/overview) · [Getting started](/moderation/getting-started) · [Rules](/moderation/rules-management) · [Lists](/moderation/lists-management) · [Flagged messages](/moderation/flagged-messages) + +## Push, campaigns, auth & webhooks +- **Push (Android):** [Push overview](/notifications/push-overview) · [**Android push notifications**](/notifications/android-push-notifications) · [Badge count](/notifications/badge-count) · [Limits](/notifications/constraints-and-limits) · [Notification extensions](/fundamentals/notification-extensions) +- **Campaigns:** [Campaigns](/campaigns/campaigns) · [Templates](/campaigns/templates) · [Channels](/campaigns/channels) +- **Auth & permissions:** [User auth](/fundamentals/user-auth) · [Roles & permissions](/fundamentals/user-roles-and-permissions) · [Mentions](/fundamentals/mentions) +- **Server-side hooks:** [Webhooks overview](/fundamentals/webhooks-overview) · [Call webhooks](/calls/webhooks) · [Ringing webhooks](/calls/webhooks-ringing) + +## Migration & misc +- [Upgrading from v4](/sdk/android/v5/upgrading-from-v4) +- [Changelog](/sdk/android/v5/changelog) diff --git a/sdk/android/v5/send-message.mdx b/sdk/android/v5/send-message.mdx index aa799028a..1f27bd8a6 100644 --- a/sdk/android/v5/send-message.mdx +++ b/sdk/android/v5/send-message.mdx @@ -795,7 +795,7 @@ The parameters involved are: 3. `customType` - custom message type that you need to set 4. `customData` - The data to be passed as the message in the form of a JSONObject. -You can also use the subType field of the `CustomMessage` class to set a specific type for the custom message. This can be achieved using the `setSubtype()` method. +You can also use the subType field of the `CustomMessage` class to set a specific type for the custom message. This can be achieved using the `setSubType()` method. ### Add Tags diff --git a/sdk/android/v5/typing-indicators.mdx b/sdk/android/v5/typing-indicators.mdx index 452fd1f4a..6e7ae3489 100644 --- a/sdk/android/v5/typing-indicators.mdx +++ b/sdk/android/v5/typing-indicators.mdx @@ -13,7 +13,7 @@ title: "Typing Indicators" You can use the `startTyping()` method to inform the receiver that the logged in user has started typing. The receiver will receive this information in the `onTypingStarted()` method of the `MessageListener` class. In order to send the typing indicator, you need to use the `TypingIndicator` class. - + ```java TypingIndicator typingIndicator = new TypingIndicator(UID, CometChatConstants.RECEIVER_TYPE_USER); @@ -22,7 +22,7 @@ CometChat.startTyping(typingIndicator); - + ```kotlin val typingIndicator =TypingIndicator(UID,CometChatConstants.RECEIVER_TYPE_USER) @@ -31,7 +31,7 @@ CometChat.startTyping(typingIndicator) - + ```java TypingIndicator typingIndicator = new TypingIndicator(GUID, CometChatConstants.RECEIVER_TYPE_GROUP); @@ -40,7 +40,7 @@ CometChat.startTyping(typingIndicator); - + ```kotlin val typingIndicator = TypingIndicator(GUID,CometChatConstants.RECEIVER_TYPE_GROUP) @@ -56,16 +56,16 @@ CometChat.startTyping(typingIndicator) You can use the `endTyping()` method to inform the receiver that the logged in user has stopped typing. The receiver will receive this information in the `onTypingEnded()` method of the `MessageListener` class. In order to send the typing indicator, you need to use the `TypingIndicator` class. - + ```java TypingIndicator typingIndicator = new TypingIndicator(UID, CometChatConstants.RECEIVER_TYPE_USER); -CometChat.endtyping(typingIndicator); +CometChat.endTyping(typingIndicator); ``` - + ```kotlin val typingIndicator = TypingIndicator(UID,CometChatConstants.RECEIVER_TYPE_USER) @@ -74,7 +74,7 @@ CometChat.endTyping(typingIndicator) - + ```java TypingIndicator typingIndicator = new TypingIndicator(GUID, CometChatConstants.RECEIVER_TYPE_GROUP); @@ -83,7 +83,7 @@ CometChat.endTyping(typingIndicator); - + ```kotlin val typingIndicator = TypingIndicator(GUID,CometChatConstants.RECEIVER_TYPE_GROUP) diff --git a/sdk/flutter/ai-agents.mdx b/sdk/flutter/ai-agents.mdx index 5ca04c766..cd29b254c 100644 --- a/sdk/flutter/ai-agents.mdx +++ b/sdk/flutter/ai-agents.mdx @@ -3,6 +3,22 @@ title: "AI Agents" description: "Learn how to integrate AI Agents in your Flutter app to process messages, trigger tools, and respond with context." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Learn how to integrate AI Agents in your Flutter app to process messages, trigger tools, and respond with context. | +| Key methods | `addAIAssistantListener()` · `addMessageListener()` · `removeAIAssistantListener()` | +| Key classes | `AIAssistantMessage` · `Call` · `CometChatCardView` · `AIAssistantBaseEvent` · `AIAssistantCardEndedEvent` · `AIAssistantCardReceivedEvent` · `AIAssistantCardStartedEvent` · `AIToolArgumentMessage` | +| Listener callbacks | `onAIAssistantEventReceived()` · `onAIAssistantMessageReceived()` · `onAIToolArgumentsReceived()` · `onAIToolResultReceived()` · `onCardMessageReceived()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Full reference | [`AIAssistantMessage`](/sdk/reference/messages#aiassistantmessage) · [`Call`](/sdk/reference/messages#call) · [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) · [`AIAssistantCardEndedEvent`](/sdk/reference/messages#aiassistantcardendedevent) · [`AIAssistantCardReceivedEvent`](/sdk/reference/messages#aiassistantcardreceivedevent) · [`AIAssistantCardStartedEvent`](/sdk/reference/messages#aiassistantcardstartedevent) | + + + # AI Agents Overview AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). diff --git a/sdk/flutter/ai-moderation.mdx b/sdk/flutter/ai-moderation.mdx index ff3bf5a8f..05f4d7664 100644 --- a/sdk/flutter/ai-moderation.mdx +++ b/sdk/flutter/ai-moderation.mdx @@ -3,6 +3,22 @@ title: "AI Moderation" description: "Automatically review CometChat messages for inappropriate content in Flutter apps using AI moderation rules and message status updates." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Automatically review CometChat messages for inappropriate content in Flutter apps using AI moderation rules and message status updates. | +| Key methods | `addMessageListener()` · `removeMessageListener()` · `sendMessage()` | +| Key classes | `TextMessage` · `BaseMessage` · `CometChatException` · `MediaMessage` | +| Listener callbacks | `onMessageModerated()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Full reference | [`TextMessage`](/sdk/reference/messages#textmessage) · [`BaseMessage`](/sdk/reference/messages#basemessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`MediaMessage`](/sdk/reference/messages#mediamessage) | + + + ## Overview AI Moderation in the CometChat SDK helps ensure that your chat application remains safe and compliant by automatically reviewing messages for inappropriate content. This feature leverages AI to moderate messages in real-time, reducing manual intervention and improving user experience. diff --git a/sdk/flutter/authentication-overview.mdx b/sdk/flutter/authentication-overview.mdx index ef71739ff..21e700cda 100644 --- a/sdk/flutter/authentication-overview.mdx +++ b/sdk/flutter/authentication-overview.mdx @@ -4,6 +4,22 @@ sidebarTitle: "Overview" description: "Authenticate Flutter app users with CometChat using UID login, auth tokens, session checks, logout, and backend user management." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Authenticate Flutter app users with CometChat using UID login, auth tokens, session checks, logout, and backend user management. | +| Key methods | `getLoggedInUser()` · `login()` · `loginWithAuthToken()` · `logout()` | +| Key classes | `CometChatException` · `User` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Setup](/sdk/flutter/setup) · [Login Listeners](/sdk/flutter/login-listeners) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`User`](/sdk/reference/entities#user) | + + + To allow a user to use CometChat, the user must log in to CometChat. **CometChat does not handle user management.** You must handle user registration and login at your end. Once the user is logged into your app/site, you can log in the user to CometChat **programmatically**. The user does not ever directly login to CometChat. diff --git a/sdk/flutter/block-users.mdx b/sdk/flutter/block-users.mdx index ae2187e6e..bbb8eb19c 100644 --- a/sdk/flutter/block-users.mdx +++ b/sdk/flutter/block-users.mdx @@ -3,6 +3,22 @@ title: "Block Users" description: "Block and unblock CometChat users in Flutter apps to stop direct communication and manage blocked user lists." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Block and unblock CometChat users in Flutter apps to stop direct communication and manage blocked user lists. | +| Key methods | `blockUser()` · `unblockUser()` | +| Key classes | `User` · `CometChatException` · `CometChatBlockedUsersDirection` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Retrieve Users](/sdk/flutter/retrieve-users) · [User Management](/sdk/flutter/user-management) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Block Users diff --git a/sdk/flutter/campaigns.mdx b/sdk/flutter/campaigns.mdx index 47501606b..23de1eae7 100644 --- a/sdk/flutter/campaigns.mdx +++ b/sdk/flutter/campaigns.mdx @@ -3,6 +3,22 @@ title: "Campaigns" description: "Fetch notification feed items, listen for real-time delivery, mark items as read/delivered, report engagement, and retrieve unread counts in Flutter." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Fetch notification feed items, listen for real-time delivery, mark items as read/delivered, report engagement, and retrieve unread counts in Flutter. | +| Key methods | `addMessageListener()` · `addNotificationFeedListener()` · `getNotificationFeedItem()` · `getNotificationFeedUnreadCount()` · `markFeedItemAsDelivered()` · `markFeedItemAsRead()` · `markPushNotificationClicked()` · `markPushNotificationDelivered()` · `removeNotificationFeedListener()` · `reportFeedEngagement()` | +| Key classes | `CometChatException` · `CometChatCardView` · `CardMessage` · `CometChatCardActionEvent` · `CometChatCardChatWithUserAction` · `CometChatCardOpenUrlAction` · `CometChatCardThemeMode` | +| Listener callbacks | `onCardMessageReceived()` · `onFeedItemReceived()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`CardMessage`](/sdk/reference/messages#cardmessage) | + + + CometChat Campaigns lets you deliver targeted, rich notifications to users via an in-app notification feed. Each notification is a **Card Schema JSON** — a structured layout rendered natively by the CometChat Cards library. The SDK provides APIs to fetch feed items, listen for real-time delivery, mark items as read/delivered, report engagement, and retrieve unread counts. diff --git a/sdk/flutter/connection-behaviour.mdx b/sdk/flutter/connection-behaviour.mdx index 6c4fcb354..95921171e 100644 --- a/sdk/flutter/connection-behaviour.mdx +++ b/sdk/flutter/connection-behaviour.mdx @@ -3,6 +3,22 @@ title: "Connection Behaviour" description: "Manage CometChat Flutter SDK WebSocket behavior with automatic connection handling, background disconnects, and manual connection mode." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Manage CometChat Flutter SDK WebSocket behavior with automatic connection handling, background disconnects, and manual connection mode. | +| Key methods | `connect()` · `disconnect()` · `init()` · `ping()` | +| Key classes | `CometChatException` · `CometChatSubscriptionType` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Connection Status](/sdk/flutter/connection-status) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Default SDK behaviour on login diff --git a/sdk/flutter/connection-status.mdx b/sdk/flutter/connection-status.mdx index 1e594983a..a1e161ad8 100644 --- a/sdk/flutter/connection-status.mdx +++ b/sdk/flutter/connection-status.mdx @@ -3,6 +3,23 @@ title: "Connection Status" description: "Monitor CometChat WebSocket connection status in Flutter apps with callbacks for connecting, connected, disconnected, and errors." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Monitor CometChat WebSocket connection status in Flutter apps with callbacks for connecting, connected, disconnected, and errors. | +| Key methods | `addConnectionListener()` · `getConnectionStatus()` | +| Key classes | `CometChatException` | +| Listener callbacks | `onConnected()` · `onConnecting()` · `onConnectionError()` · `onDisconnected()` · `onFeatureThrottled()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Connection Behaviour](/sdk/flutter/connection-behaviour) · [All Real Time Listeners](/sdk/flutter/real-time-listeners) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. To achieve this you need to use the `ConnectionListener` class provided by the CometChat SDK @@ -21,12 +38,14 @@ Once the connection is broken, the disconnected callback is triggered, the SDK a In order to use the ConnectionListeners, you need to add the ConnectionListeners using the `addConnectionListener` method provided by the SDK. You can add multiple listeners as shown below. Just make sure you add listeners with unique IDs. +Remove a listener with `removeConnectionListener(listenerId)` when the subscriber goes away — typically in `dispose()` — passing the same ID you registered with. + ```dart class Class_Name with ConnectionListener { //1. Register Connection listener -//CometChat.addConnctionListener("listenerId", this); +//CometChat.addConnectionListener("listenerId", this); //2. Ovveride the ConnectionListener methods @override diff --git a/sdk/flutter/create-group.mdx b/sdk/flutter/create-group.mdx index a7208e6d6..99bebbacc 100644 --- a/sdk/flutter/create-group.mdx +++ b/sdk/flutter/create-group.mdx @@ -3,6 +3,22 @@ title: "Create A Group" description: "Create CometChat public, private, and password-protected groups in Flutter apps with group GUID, name, type, and password." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Create CometChat public, private, and password-protected groups in Flutter apps with group GUID, name, type, and password. | +| Key methods | `createGroup()` · `createGroupWithMembers()` | +| Key classes | `Group` · `GroupMember` · `CometChatMemberScope` · `CometChatException` · `CometChatGroupType` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Join A Group](/sdk/flutter/join-group) · [Update A Group](/sdk/flutter/update-group) · [Delete A Group](/sdk/flutter/delete-group) · [Add Members To A Group](/sdk/flutter/group-add-members) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`GroupMember`](/sdk/reference/entities#groupmember) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Create a Group diff --git a/sdk/flutter/delete-conversation.mdx b/sdk/flutter/delete-conversation.mdx index a046d4330..3d3d66fd1 100644 --- a/sdk/flutter/delete-conversation.mdx +++ b/sdk/flutter/delete-conversation.mdx @@ -3,6 +3,22 @@ title: "Delete A Conversation" description: "Delete one-on-one or group conversations for the logged-in user in Flutter apps using conversation ID and type." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Delete one-on-one or group conversations for the logged-in user in Flutter apps using conversation ID and type. | +| Key methods | `deleteConversation()` | +| Key classes | `Conversation` · `CometChatException` · `CometChatConversationType` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Retrieve Conversations](/sdk/flutter/retrieve-conversations) | +| Full reference | [`Conversation`](/sdk/reference/entities#conversation) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + In case you want to delete a conversation, you can use the `deleteConversation()` method. diff --git a/sdk/flutter/delete-group.mdx b/sdk/flutter/delete-group.mdx index 6d64e0a20..aa7ef80bc 100644 --- a/sdk/flutter/delete-group.mdx +++ b/sdk/flutter/delete-group.mdx @@ -3,6 +3,22 @@ title: "Delete A Group" description: "Delete CometChat groups from Flutter apps by GUID when the logged-in user has admin permissions." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Delete CometChat groups from Flutter apps by GUID when the logged-in user has admin permissions. | +| Key methods | `deleteGroup()` | +| Key classes | `Group` · `CometChatException` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Create A Group](/sdk/flutter/create-group) · [Leave A Group](/sdk/flutter/leave-group) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Delete Group diff --git a/sdk/flutter/delete-message.mdx b/sdk/flutter/delete-message.mdx index 4e7965188..e5fd0f910 100644 --- a/sdk/flutter/delete-message.mdx +++ b/sdk/flutter/delete-message.mdx @@ -3,6 +3,23 @@ title: "Delete A Message" description: "Delete CometChat messages in Flutter apps and handle real-time or missed message deletion events." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Delete CometChat messages in Flutter apps and handle real-time or missed message deletion events. | +| Key methods | `addMessageListener()` · `deleteMessage()` | +| Key classes | `BaseMessage` · `CometChatException` | +| Listener callbacks | `onMessageDeleted()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [Edit A Message](/sdk/flutter/edit-message) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + While [deleting a message](/sdk/flutter/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: diff --git a/sdk/flutter/delivery-read-receipts.mdx b/sdk/flutter/delivery-read-receipts.mdx index d2fa4aa33..ae883b02e 100644 --- a/sdk/flutter/delivery-read-receipts.mdx +++ b/sdk/flutter/delivery-read-receipts.mdx @@ -3,6 +3,23 @@ title: "Delivery & Read Receipts" description: "Mark CometChat messages as delivered or read in Flutter apps and listen for real-time receipt events." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Mark CometChat messages as delivered or read in Flutter apps and listen for real-time receipt events. | +| Key methods | `addMessageListener()` · `getMessageReceipts()` · `markAsDelivered()` · `markAsRead()` · `markConversationAsDelivered()` · `markConversationAsRead()` · `markMessageAsUnread()` | +| Key classes | `MessageReceipt` · `CometChatException` | +| Listener callbacks | `onError()` · `onMessagesDelivered()` · `onMessagesDeliveredToAll()` · `onMessagesRead()` · `onMessagesReadByAll()` · `onSuccess()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Receive A Message](/sdk/flutter/receive-messages) · [All Real Time Listeners](/sdk/flutter/real-time-listeners) | +| Full reference | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Mark Messages as Delivered @@ -138,7 +155,8 @@ You can mark an entire conversation as delivered using the `markConversationAsDe ```dart CometChat.markConversationAsDelivered( - conversation, + "cometchat-uid-1", // UID for a 1:1 conversation, GUID for a group + CometChatConversationType.user, // or CometChatConversationType.group onSuccess: (success) { debugPrint("markConversationAsDelivered : $success"); }, @@ -162,7 +180,8 @@ You can mark an entire conversation as read using the `markConversationAsRead()` ```dart CometChat.markConversationAsRead( - conversation, + "cometchat-uid-1", // UID for a 1:1 conversation, GUID for a group + CometChatConversationType.user, // or CometChatConversationType.group onSuccess: (success) { debugPrint("markConversationAsRead : $success"); }, diff --git a/sdk/flutter/edit-message.mdx b/sdk/flutter/edit-message.mdx index 216ab688f..c3f80ef9f 100644 --- a/sdk/flutter/edit-message.mdx +++ b/sdk/flutter/edit-message.mdx @@ -3,6 +3,23 @@ title: "Edit A Message" description: "Edit CometChat text and custom messages in Flutter apps and handle real-time or missed edit events." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Edit CometChat text and custom messages in Flutter apps and handle real-time or missed edit events. | +| Key methods | `addMessageListener()` · `editMessage()` | +| Key classes | `BaseMessage` · `TextMessage` · `CometChatException` | +| Listener callbacks | `onMessageEdited()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [Delete A Message](/sdk/flutter/delete-message) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + While editing a message is straightforward, receiving events for edited messages with CometChat has two parts: diff --git a/sdk/flutter/flag-message.mdx b/sdk/flutter/flag-message.mdx index 1fee01677..f2ec79375 100644 --- a/sdk/flutter/flag-message.mdx +++ b/sdk/flutter/flag-message.mdx @@ -3,6 +3,22 @@ title: "Flag Message" description: "Get flag reasons and report inappropriate CometChat messages in Flutter apps for moderation review in the dashboard." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Get flag reasons and report inappropriate CometChat messages in Flutter apps for moderation review in the dashboard. | +| Key methods | `flagMessage()` · `getFlagReasons()` | +| Key classes | `CometChatException` · `User` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [AI Moderation](/sdk/flutter/ai-moderation) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`User`](/sdk/reference/entities#user) | + + + ## Overview Flagging messages allows users to report inappropriate content to moderators or administrators. When a message is flagged, it appears in the [CometChat Dashboard](https://app.cometchat.com) under **Moderation > Flagged Messages** for review. diff --git a/sdk/flutter/group-add-members.mdx b/sdk/flutter/group-add-members.mdx index 0d09fea10..8d68a8640 100644 --- a/sdk/flutter/group-add-members.mdx +++ b/sdk/flutter/group-add-members.mdx @@ -3,6 +3,23 @@ title: "Add Members To A Group" description: "Add CometChat users to Flutter group chats with member scopes and optional banned member handling." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Add CometChat users to Flutter group chats with member scopes and optional banned member handling. | +| Key methods | `addGroupListener()` · `addMembersToGroup()` | +| Key classes | `GroupMember` · `Group` · `User` · `CometChatMemberScope` · `Action` · `CometChatException` | +| Listener callbacks | `onMemberAddedToGroup()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Retrieve Group Members](/sdk/flutter/retrieve-group-members) · [Change Member Scope](/sdk/flutter/group-change-member-scope) · [Ban/Kick Member From A Group](/sdk/flutter/group-kick-member) | +| Full reference | [`GroupMember`](/sdk/reference/entities#groupmember) · [`Group`](/sdk/reference/entities#group) · [`User`](/sdk/reference/entities#user) · [`Action`](/sdk/reference/messages#action) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Add Members to Group diff --git a/sdk/flutter/group-change-member-scope.mdx b/sdk/flutter/group-change-member-scope.mdx index dedbba887..5d0d9e4f1 100644 --- a/sdk/flutter/group-change-member-scope.mdx +++ b/sdk/flutter/group-change-member-scope.mdx @@ -3,6 +3,23 @@ title: "Change Member Scope" description: "Update CometChat group member scopes in Flutter apps to change participants between admin, moderator, and participant roles." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Update CometChat group member scopes in Flutter apps to change participants between admin, moderator, and participant roles. | +| Key methods | `addGroupListener()` · `updateGroupMemberScope()` | +| Key classes | `Group` · `User` · `Action` · `CometChatException` · `CometChatMemberScope` | +| Listener callbacks | `onGroupMemberScopeChanged()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Retrieve Group Members](/sdk/flutter/retrieve-group-members) · [Transfer Group Ownership](/sdk/flutter/transfer-group-ownership) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`User`](/sdk/reference/entities#user) · [`Action`](/sdk/reference/messages#action) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Change Scope of a Group Member diff --git a/sdk/flutter/group-kick-member.mdx b/sdk/flutter/group-kick-member.mdx index 49ce8a038..8d186ad93 100644 --- a/sdk/flutter/group-kick-member.mdx +++ b/sdk/flutter/group-kick-member.mdx @@ -3,6 +3,23 @@ title: "Ban/Kick Member From A Group" description: "Kick, ban, and unban CometChat group members in Flutter apps when the logged-in user is an admin or moderator." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Kick, ban, and unban CometChat group members in Flutter apps when the logged-in user is an admin or moderator. | +| Key methods | `addGroupListener()` · `banGroupMember()` · `kickGroupMember()` · `unbanGroupMember()` | +| Key classes | `Group` · `User` · `CometChatException` · `Action` · `GroupMember` | +| Listener callbacks | `onGroupMemberBanned()` · `onGroupMemberKicked()` · `onGroupMemberUnbanned()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Retrieve Group Members](/sdk/flutter/retrieve-group-members) · [Leave A Group](/sdk/flutter/leave-group) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`Action`](/sdk/reference/messages#action) · [`GroupMember`](/sdk/reference/entities#groupmember) | + + + There are certain actions that can be performed on the group members: diff --git a/sdk/flutter/join-group.mdx b/sdk/flutter/join-group.mdx index 0a7827d6c..0d76ea546 100644 --- a/sdk/flutter/join-group.mdx +++ b/sdk/flutter/join-group.mdx @@ -3,6 +3,23 @@ title: "Join A Group" description: "Join CometChat public and password-protected groups in Flutter apps using group GUIDs and password validation." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Join CometChat public and password-protected groups in Flutter apps using group GUIDs and password validation. | +| Key methods | `addGroupListener()` · `joinGroup()` | +| Key classes | `Group` · `Action` · `CometChatException` · `User` · `CometChatGroupType` | +| Listener callbacks | `onGroupMemberJoined()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Create A Group](/sdk/flutter/create-group) · [Leave A Group](/sdk/flutter/leave-group) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`Action`](/sdk/reference/messages#action) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`User`](/sdk/reference/entities#user) | + + + ## Join a Group diff --git a/sdk/flutter/leave-group.mdx b/sdk/flutter/leave-group.mdx index 74e7b28ed..259ed10bf 100644 --- a/sdk/flutter/leave-group.mdx +++ b/sdk/flutter/leave-group.mdx @@ -3,6 +3,23 @@ title: "Leave A Group" description: "Leave CometChat groups from Flutter apps by GUID and listen for real-time group member left events." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Leave CometChat groups from Flutter apps by GUID and listen for real-time group member left events. | +| Key methods | `addGroupListener()` · `leaveGroup()` | +| Key classes | `Group` · `Action` · `CometChatException` · `User` | +| Listener callbacks | `onGroupMemberLeft()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Join A Group](/sdk/flutter/join-group) · [Ban/Kick Member From A Group](/sdk/flutter/group-kick-member) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`Action`](/sdk/reference/messages#action) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`User`](/sdk/reference/entities#user) | + + + ## Leave a Group diff --git a/sdk/flutter/llms-flutter-v5.mdx b/sdk/flutter/llms-flutter-v5.mdx new file mode 100644 index 000000000..391e32819 --- /dev/null +++ b/sdk/flutter/llms-flutter-v5.mdx @@ -0,0 +1,128 @@ +--- +title: "Flutter Chat SDK v5 — LLM docs index" +description: "Machine-readable, Flutter-SDK-v5-scoped index of every SDK page as a clean .md twin. Built for AI coding agents; kept out of the human sidebar." +--- + +{/* + SCOPED LLM INDEX for the Flutter Chat SDK v5. + - UNLISTED, NOT hidden: intentionally omitted from docs.json navigation so it never shows in + the human sidebar — but it IS built, served as a clean .md twin, and INDEXED for search + + AI assistants (so AI tools, and this pack's skill via its docs-map, can discover and read it). + - We deliberately do NOT use `hidden: true`/`noindex` here: in Mintlify `hidden` auto-applies + noindex, which would drop this page from search AND the auto global llms.txt / AI context. + We want it discoverable, so it stays indexable. + - Fetch this file's own .md twin as a lightweight, Flutter-SDK-only routing index instead of + the site-wide /docs/llms.txt (which spans every product and is far larger). +*/} + +# Flutter Chat SDK v5 — LLM docs index (Latest) + +> Low-level (headless) Flutter chat + calling client — no UI. Package `cometchat_sdk@5` +> (calling adds `cometchat_calls_sdk@5`). This page is a **Flutter-SDK-v5-only** routing index +> for AI agents — a scoped alternative to the site-wide `/docs/llms.txt`. + +## How to use this index +Each link points to the docs page; **append `.md`** to its URL to fetch the clean Markdown twin +(verbatim code + method signatures, parameters, and listener contracts). Pick the page for the +intent, then read the API there. +- Convention: any docs page URL + `.md` → raw Markdown. +- Fallback: if a `.md` twin 404s, fetch the same URL **without** `.md` (HTML). Never read the + installed Dart source in place of a doc, and never answer APIs from memory. + +## Platform rules — headless, and Dart +This is the **SDK**, not the UI Kit: it ships no widgets. You own every view. Also: +- **Callbacks, not futures, carry the result.** The message and group APIs take `onSuccess` and + `onError` callbacks and both are **required** — awaiting the call alone gives you nothing to + act on. Write the success path inside `onSuccess`. +- **Listeners must be removed.** Every `add*Listener(id, …)` needs the matching + `remove*Listener(id)`, normally in `dispose()`. Leaked listeners are the top source of + duplicate-message bugs. +- **You do not receive your own sends.** The realtime listeners deliver other people's messages. + A message you send is returned to you through `onSuccess` and nowhere else, so any local list + must append it yourself. +- **The UI Kit re-exports this SDK.** If the app already depends on `cometchat_chat_uikit`, the + SDK types resolve from the kit barrel — do not add a second, differently-versioned direct + dependency. +- Building UI from scratch is a lot of work. If the goal is "add chat", prefer the + [Flutter UI Kit](/ui-kit/flutter/overview) and drop to this SDK only for custom UI or + headless/background logic. + +## Hot path — usually no fetch needed +For a plain integration the install, `init → login`, and the core send / receive-listener flow +are stable; a well-built agent skill bakes them. Fetch below only for exhaustive parameters, +long-tail methods, group/user management, calling, or edge-case listeners. +- Setup: [Setup](/sdk/flutter/setup) +- Auth/lifecycle: [Authentication](/sdk/flutter/authentication-overview) +- Core send/receive: [Send A Message](/sdk/flutter/send-message) · [Receive A Message](/sdk/flutter/receive-messages) · [All Real Time Listeners](/sdk/flutter/real-time-listeners) + +## Getting started / integration +- [Overview](/sdk/flutter/overview) +- [Setup](/sdk/flutter/setup) +- [Authentication](/sdk/flutter/authentication-overview) +- [Login Listeners](/sdk/flutter/login-listeners) +- [Flutter Chat UI Kit](/sdk/flutter/flutter-overview) + +## Messaging — send & receive +- [Messaging Overview](/sdk/flutter/messaging-overview) +- [Send A Message](/sdk/flutter/send-message) +- [Receive A Message](/sdk/flutter/receive-messages) +- [Edit A Message](/sdk/flutter/edit-message) +- [Delete A Message](/sdk/flutter/delete-message) +- [Upload Files & Send Attachments](/sdk/flutter/upload-files) +- [Threaded Messages](/sdk/flutter/threaded-messages) +- [Transient Messages](/sdk/flutter/transient-messages) +- [Additional Message Filtering](/sdk/flutter/additional-message-filtering) + +## Messaging — signals & state +- [All Real Time Listeners](/sdk/flutter/real-time-listeners) +- [Typing Indicators](/sdk/flutter/typing-indicators) +- [Delivery & Read Receipts](/sdk/flutter/delivery-read-receipts) +- [Reactions](/sdk/flutter/reactions) +- [Mentions](/sdk/flutter/mentions) +- [Flag Message](/sdk/flutter/flag-message) + +## Conversations +- [Retrieve Conversations](/sdk/flutter/retrieve-conversations) +- [Delete A Conversation](/sdk/flutter/delete-conversation) + +## Users +- [Users Overview](/sdk/flutter/users-overview) +- [User Management](/sdk/flutter/user-management) +- [Retrieve Users](/sdk/flutter/retrieve-users) +- [User Presence](/sdk/flutter/user-presence) +- [Block Users](/sdk/flutter/block-users) + +## Groups +- [Groups Overview](/sdk/flutter/groups-overview) +- [Create A Group](/sdk/flutter/create-group) +- [Retrieve Groups](/sdk/flutter/retrieve-groups) +- [Join A Group](/sdk/flutter/join-group) +- [Leave A Group](/sdk/flutter/leave-group) +- [Update A Group](/sdk/flutter/update-group) +- [Delete A Group](/sdk/flutter/delete-group) +- [Add Members To A Group](/sdk/flutter/group-add-members) +- [Retrieve Group Members](/sdk/flutter/retrieve-group-members) +- [Change Member Scope](/sdk/flutter/group-change-member-scope) +- [Ban / Kick Member](/sdk/flutter/group-kick-member) +- [Transfer Group Ownership](/sdk/flutter/transfer-group-ownership) + +## Connection & lifecycle +- [Connection Status](/sdk/flutter/connection-status) +- [Connection Behaviour](/sdk/flutter/connection-behaviour) + +## AI & moderation +- [AI Overview](/sdk/flutter/ai-user-copilot-overview) +- [AI Agents](/sdk/flutter/ai-agents) +- [Bots](/sdk/flutter/ai-chatbots-overview) +- [AI Moderation](/sdk/flutter/ai-moderation) + +## Extend & operate +- [Extensions](/sdk/flutter/extensions-overview) +- [Webhooks](/sdk/flutter/webhooks-overview) +- [Campaigns](/sdk/flutter/campaigns) +- [Advanced](/sdk/flutter/advanced-overview) +- [Resources](/sdk/flutter/resources-overview) + +## Migration & misc +- [Upgrading from v4](/sdk/flutter/upgrading-from-v4-guide) +- [Changelog](/sdk/flutter/changelog) diff --git a/sdk/flutter/login-listeners.mdx b/sdk/flutter/login-listeners.mdx index 0f460ab98..7cdd331bc 100644 --- a/sdk/flutter/login-listeners.mdx +++ b/sdk/flutter/login-listeners.mdx @@ -3,6 +3,22 @@ title: "Login Listeners" description: "Listen for CometChat login and logout success or failure events in Flutter apps using LoginListener callbacks." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Listen for CometChat login and logout success or failure events in Flutter apps using LoginListener callbacks. | +| Key methods | `addloginListener()` · `removeLoginListener()` | +| Key classes | `CometChatException` · `User` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Authentication](/sdk/flutter/authentication-overview) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`User`](/sdk/reference/entities#user) | + + + The CometChat SDK provides you with real-time updates for the `login` and `logout` events. This can be achieved using the `LoginListener` class provided. LoginListener consists of 4 events that can be triggered. These are as follows: @@ -14,7 +30,11 @@ The CometChat SDK provides you with real-time updates for the `login` and `logou | logoutSuccess() | Informs you about the user being logged out successfully. | | logoutFailure(CometChatException e) | Informs you about the failure while logging out the user. The reason for the failure can be obtained from the object of the `CometChatException` class provided. | -To add the `LoginListener`, you need to use the `addLoginListener()` method provided by the SDK which takes a unique identifier for the listener and object of the `LoginListener` class itself. +To add the `LoginListener`, you need to use the `addloginListener()` method provided by the SDK which takes a unique identifier for the listener and object of the `LoginListener` class itself. + + +`addloginListener` is spelled with a **lowercase `l`** in `login`, while its counterpart `removeLoginListener` uses a capital `L`. The names are genuinely inconsistent — copying the capitalised form for both does not compile. + We suggest adding the listener in the `init` method of the Stateful class or at the initialization of class where you wish to receive these events in. @@ -24,7 +44,7 @@ We suggest adding the listener in the `init` method of the Stateful class or at class Class_Name with LoginListener { // String loginListenerId = "UNIQUE_LISTENER_ID"; -// CometChat.addLoginListener(loginListenerId, Class_Name()); // add this in init +// CometChat.addloginListener(loginListenerId, Class_Name()); // add this in init @override void loginSuccess(User user) { debugPrint("LoginListener loginSuccess $user"); diff --git a/sdk/flutter/mentions.mdx b/sdk/flutter/mentions.mdx index 40284f47a..b4948ffa1 100644 --- a/sdk/flutter/mentions.mdx +++ b/sdk/flutter/mentions.mdx @@ -3,6 +3,22 @@ title: "Mentions" description: "Send, receive, and inspect CometChat mentioned messages in Flutter apps using user UIDs in one-on-one and group conversations." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Send, receive, and inspect CometChat mentioned messages in Flutter apps using user UIDs in one-on-one and group conversations. | +| Key methods | `sendMessage()` | +| Key classes | `BaseMessage` · `User` · `CometChatException` · `TextMessage` · `CometChatMessageCategory` · `CometChatMessageType` · `CometChatReceiverType` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [Users](/sdk/flutter/users-overview) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`TextMessage`](/sdk/reference/messages#textmessage) | + + + Mentions are a powerful tool for enhancing communication in messaging platforms. They streamline interaction by allowing users to easily engage and collaborate with particular individuals, especially in group conversations. diff --git a/sdk/flutter/reactions.mdx b/sdk/flutter/reactions.mdx index c57cc4626..3834f6c46 100644 --- a/sdk/flutter/reactions.mdx +++ b/sdk/flutter/reactions.mdx @@ -3,6 +3,23 @@ title: "Reactions" description: "Add, remove, fetch, and listen for CometChat message reactions in Flutter apps for text, media, and custom messages." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Add, remove, fetch, and listen for CometChat message reactions in Flutter apps for text, media, and custom messages. | +| Key methods | `addMessageListener()` · `addReaction()` · `removeMessageListener()` · `removeReaction()` | +| Key classes | `BaseMessage` · `Reaction` · `ReactionEvent` · `ReactionCount` · `CometChatHelper` | +| Listener callbacks | `onMessageReactionAdded()` · `onMessageReactionRemoved()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [Receive A Message](/sdk/flutter/receive-messages) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`Reaction`](/sdk/reference/auxiliary#reaction) · [`ReactionEvent`](/sdk/reference/auxiliary#reactionevent) · [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) | + + + Enhance user engagement in your chat application with message reactions. Users can express their emotions using reactions to messages. This feature allows users to add or remove reactions, and to fetch all reactions on a message. You can also listen to reaction events in real-time. Let's see how to work with reactions in CometChat's Flutter SDK. @@ -16,7 +33,7 @@ Users can add a reaction to a message by calling `addReaction` with the message int messageId = 1; CometChat.addReaction(messageId, "😴", onSuccess: (message) { - debugPrint("Success : ${message.getReactions().last}"); + debugPrint("Success : ${message.reactions.last.reaction}"); }, onError: (e) { debugPrint("Error: ${e.message}"); }); @@ -39,7 +56,7 @@ Removing a reaction from a message can be done using the `removeReaction` method int messageId = 1; CometChat.removeReaction(messageId, "😴", onSuccess: (message) { - debugPrint("Success : ${message.getReactions().last}"); + debugPrint("Success : ${message.reactions.last.reaction}"); }, onError: (e) { debugPrint("Error: ${e.message}"); }); @@ -73,8 +90,8 @@ ReactionRequest reactionRequest = (ReactionRequestBuilder()..limit = 30..messag reactionRequest.fetchNext( onSuccess: (messageReactions) { - for (MessageReaction messageReaction in messageReactions) { - debugPrint("Success: ${messageReaction.getReactions()}"); + for (Reaction reaction in messageReactions) { + debugPrint("Success: ${reaction.reaction} by ${reaction.uid}"); } }, onError: (e) { @@ -98,8 +115,8 @@ ReactionRequest reactionRequest = (ReactionRequestBuilder()..limit = 30..messag reactionRequest.fetchPrevious( onSuccess: (messageReactions) { - for (MessageReaction messageReaction in messageReactions) { - debugPrint("Success: ${messageReaction.getReactions()}"); + for (Reaction reaction in messageReactions) { + debugPrint("Success: ${reaction.reaction} by ${reaction.uid}"); } }, onError: (e) { @@ -144,14 +161,14 @@ class MyClass with MessageListener { ## Removing a Reaction Listener -To stop listening for reaction events, remove the listener as follows: +Reaction events arrive through the **message** listener registered above, so removal uses `removeMessageListener` with the same ID — there is no separate reaction-listener API: ```dart String listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageReactionListener(listenerID); +CometChat.removeMessageListener(listenerID); ``` @@ -187,9 +204,9 @@ for (ReactionCount reactionCount in message.reactions) { ## Updated Message With Reaction Info When a user adds or removes a reaction, you will receive a real-time event. Once you receive the real time event you would want to update the message with the latest reaction information. To do so you can use the `updateMessageWithReactionInfo()` method. -The `updateMessageWithReactionInfo()` method provides a seamless way to update the reactions on a message instance (`BaseMessage`) in real-time. This method ensures that when a reaction is added or removed from a message, the BaseMessage object's `getReactions()` property reflects this change immediately. +The `updateMessageWithReactionInfo()` method provides a seamless way to update the reactions on a message instance (`BaseMessage`) in real-time. This method ensures that when a reaction is added or removed from a message, the `BaseMessage` object's `reactions` property reflects this change immediately. -When you receive a real-time reaction event (MessageReaction), call the `updateMessageWithReactionInfo()` method, passing the BaseMessage instance (message), event data (MessageReaction) and reaction event action type (`ReactionAction.REACTION_ADDED` or `ReactionAction.REACTION_REMOVED`) that corresponds to the message being reacted to. +When you receive a real-time reaction event (`Reaction`), call the `updateMessageWithReactionInfo()` method, passing the BaseMessage instance (message), event data (`Reaction`) and reaction event action type (`ReactionAction.REACTION_ADDED` or `ReactionAction.REACTION_REMOVED`) that corresponds to the message being reacted to. @@ -198,7 +215,7 @@ When you receive a real-time reaction event (MessageReaction), call the `updateM BaseMessage message = ...; // The reaction event data received in real-time -MessageReaction messageReaction = ...; +Reaction messageReaction = ...; // The recieved reaction event real-time action type. Can be CometChatConstants.REACTION_ADDED or CometChatConstants.REACTION_REMOVED var action = CometChatConstants.REACTION_ADDED; diff --git a/sdk/flutter/real-time-listeners.mdx b/sdk/flutter/real-time-listeners.mdx index 099c041ea..1177f8da2 100644 --- a/sdk/flutter/real-time-listeners.mdx +++ b/sdk/flutter/real-time-listeners.mdx @@ -3,6 +3,23 @@ title: "All Real Time Listeners" description: "Handle CometChat real-time events in Flutter apps with user, group, and message listeners for presence, membership, and messages." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Handle CometChat real-time events in Flutter apps with user, group, and message listeners for presence, membership, and messages. | +| Key methods | `addAIAssistantListener()` · `addGroupListener()` · `addMessageListener()` · `addUserListener()` · `removeAIAssistantListener()` · `removeGroupListener()` · `removeUserListener()` | +| Key classes | `User` · `Action` · `Group` · `BaseMessage` · `MessageReceipt` · `ReactionEvent` · `TypingIndicator` · `AIAssistantBaseEvent` | +| Listener callbacks | `onAIAssistantEventReceived()` · `onAIAssistantMessageReceived()` · `onAIToolArgumentsReceived()` · `onAIToolResultReceived()` · `onCardMessageReceived()` · `onCustomMessageReceived()` · `onGroupMemberBanned()` · `onGroupMemberJoined()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Receive A Message](/sdk/flutter/receive-messages) · [Connection Status](/sdk/flutter/connection-status) · [User Presence](/sdk/flutter/user-presence) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`Action`](/sdk/reference/messages#action) · [`Group`](/sdk/reference/entities#group) · [`BaseMessage`](/sdk/reference/messages#basemessage) · [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) · [`ReactionEvent`](/sdk/reference/auxiliary#reactionevent) | + + + CometChat provides 4 listeners viz. diff --git a/sdk/flutter/receive-messages.mdx b/sdk/flutter/receive-messages.mdx index 6675f136e..a53a066bd 100644 --- a/sdk/flutter/receive-messages.mdx +++ b/sdk/flutter/receive-messages.mdx @@ -3,6 +3,23 @@ title: "Receive A Message" description: "Receive CometChat messages in Flutter apps with real-time MessageListener callbacks and missed message retrieval." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Receive CometChat messages in Flutter apps with real-time MessageListener callbacks and missed message retrieval. | +| Key methods | `addMessageListener()` · `getUnreadMessageCount()` · `getUnreadMessageCountForAllGroups()` · `getUnreadMessageCountForAllUsers()` · `getUnreadMessageCountForGroup()` · `getUnreadMessageCountForUser()` · `removeMessageListener()` | +| Key classes | `MediaMessage` · `TextMessage` · `BaseMessage` · `CometChatException` · `CardMessage` · `CustomMessage` | +| Listener callbacks | `onCardMessageReceived()` · `onCustomMessageReceived()` · `onError()` · `onMediaMessageReceived()` · `onSuccess()` · `onTextMessageReceived()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [All Real Time Listeners](/sdk/flutter/real-time-listeners) · [Additional Message Filtering](/sdk/flutter/additional-message-filtering) · [Delivery & Read Receipts](/sdk/flutter/delivery-read-receipts) | +| Full reference | [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`BaseMessage`](/sdk/reference/messages#basemessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`CardMessage`](/sdk/reference/messages#cardmessage) · [`CustomMessage`](/sdk/reference/messages#custommessage) | + + + Receiving messages with CometChat has two parts: @@ -417,26 +434,38 @@ messageRequest.fetchPrevious(onSuccess: (List list) { *In other words, how do I find out the number of unread messages I have from a particular user?* -In order to get the unread message count for a particular user (with respect to the logged-in user), you can use the `getUnreadMessageCountForUser()`. - -This method has the two variants: +The Flutter SDK has no per-user method. Call `getUnreadMessageCountForAllUsers()` and read the +UID's entry from the returned map — the map is keyed by UID, and a UID with nothing unread is +simply absent. ```dart -CometChat.getUnreadMessageCountForUser(String UID, Callbacks); +CometChat.getUnreadMessageCountForAllUsers( + onSuccess: (Map counts) { + final int unread = counts["cometchat-uid-1"] ?? 0; + debugPrint("Unread from that user: $unread"); + }, + onError: (CometChatException e) { + // Handle failure + }, +); ``` -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to `true`: +Pass `hideMessagesFromBlockedUsers: true` to leave out messages from users you have blocked: ```dart -CometChat.getUnreadMessageCountForUser(String UID, boolean hideMessagesFromBlockedUsers, Callbacks); +CometChat.getUnreadMessageCountForAllUsers( + hideMessagesFromBlockedUsers: true, + onSuccess: (Map counts) {}, + onError: (CometChatException e) {}, +); ``` diff --git a/sdk/flutter/retrieve-conversations.mdx b/sdk/flutter/retrieve-conversations.mdx index a0ceccc9c..d105d6466 100644 --- a/sdk/flutter/retrieve-conversations.mdx +++ b/sdk/flutter/retrieve-conversations.mdx @@ -3,6 +3,22 @@ title: "Retrieve Conversations" description: "Fetch, filter, tag, and search CometChat conversations in Flutter apps using conversation request builders." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Fetch, filter, tag, and search CometChat conversations in Flutter apps using conversation request builders. | +| Key methods | `getConversation()` · `getConversationFromMessage()` · `tagConversation()` | +| Key classes | `Conversation` · `CometChatException` · `CometChatConversationType` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Delete A Conversation](/sdk/flutter/delete-conversation) · [Receive A Message](/sdk/flutter/receive-messages) | +| Full reference | [`Conversation`](/sdk/reference/entities#conversation) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Retrieve List of Conversations diff --git a/sdk/flutter/retrieve-group-members.mdx b/sdk/flutter/retrieve-group-members.mdx index 3321fbb89..ec820f39b 100644 --- a/sdk/flutter/retrieve-group-members.mdx +++ b/sdk/flutter/retrieve-group-members.mdx @@ -3,6 +3,20 @@ title: "Retrieve Group Members" description: "Fetch CometChat group members in Flutter apps with group GUID, pagination limits, search keywords, and member scopes." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Fetch CometChat group members in Flutter apps with group GUID, pagination limits, search keywords, and member scopes. | +| Key classes | `Group` · `CometChatUserStatus` · `CometChatException` · `GroupMember` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Related | [Add Members To A Group](/sdk/flutter/group-add-members) · [Change Member Scope](/sdk/flutter/group-change-member-scope) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`GroupMember`](/sdk/reference/entities#groupmember) | + + + ## Retrieve the List of Group Members diff --git a/sdk/flutter/retrieve-groups.mdx b/sdk/flutter/retrieve-groups.mdx index 210f531e7..dc7883a28 100644 --- a/sdk/flutter/retrieve-groups.mdx +++ b/sdk/flutter/retrieve-groups.mdx @@ -3,6 +3,22 @@ title: "Retrieve Groups" description: "Fetch CometChat groups in Flutter apps with pagination, search keywords, joined-only filters, tags, and group request builders." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Fetch CometChat groups in Flutter apps with pagination, search keywords, joined-only filters, tags, and group request builders. | +| Key methods | `getGroup()` · `getOnlineGroupMemberCount()` | +| Key classes | `Group` · `CometChatException` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Groups](/sdk/flutter/groups-overview) · [Join A Group](/sdk/flutter/join-group) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Retrieve List of Groups diff --git a/sdk/flutter/retrieve-users.mdx b/sdk/flutter/retrieve-users.mdx index a9f40a488..d323abcaa 100644 --- a/sdk/flutter/retrieve-users.mdx +++ b/sdk/flutter/retrieve-users.mdx @@ -3,6 +3,22 @@ title: "Retrieve Users" description: "Fetch CometChat users in Flutter apps, get logged-in user details, and filter user lists with request builder options." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Fetch CometChat users in Flutter apps, get logged-in user details, and filter user lists with request builder options. | +| Key methods | `getLoggedInUser()` · `getOnlineUserCount()` · `getUser()` | +| Key classes | `User` · `CometChatException` · `CometChatUserStatus` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [User Management](/sdk/flutter/user-management) · [User Presence](/sdk/flutter/user-presence) · [Block Users](/sdk/flutter/block-users) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Retrieve Logged In User Details diff --git a/sdk/flutter/send-message.mdx b/sdk/flutter/send-message.mdx index d6114b184..814d74bc8 100644 --- a/sdk/flutter/send-message.mdx +++ b/sdk/flutter/send-message.mdx @@ -3,6 +3,22 @@ title: "Send A Message" description: "Send CometChat text, media, and custom messages to users and groups from Flutter apps, and handle receive-only card messages." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Send CometChat text, media, and custom messages to users and groups from Flutter apps, and handle receive-only card messages. | +| Key methods | `sendCustomMessage()` · `sendMediaMessage()` · `sendMessage()` | +| Key classes | `CustomMessage` · `CometChatException` · `TextMessage` · `MediaMessage` · `CometChatConversationType` · `CometChatMessageType` · `Attachment` · `CometChatReceiverType` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Receive A Message](/sdk/flutter/receive-messages) · [Edit A Message](/sdk/flutter/edit-message) · [Delete A Message](/sdk/flutter/delete-message) · [Threaded Messages](/sdk/flutter/threaded-messages) · [Upload Files & Send Attachments](/sdk/flutter/upload-files) | +| Full reference | [`CustomMessage`](/sdk/reference/messages#custommessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`Attachment`](/sdk/reference/auxiliary#attachment) | + + + Using CometChat, you can work with four types of messages. The first three you can send directly: diff --git a/sdk/flutter/setup.mdx b/sdk/flutter/setup.mdx index 4d23df6d5..7a66ab0a0 100644 --- a/sdk/flutter/setup.mdx +++ b/sdk/flutter/setup.mdx @@ -3,6 +3,22 @@ title: "Setup" description: "Install, configure, initialize, and log in users with the CometChat Flutter SDK using app keys and region." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Install, configure, initialize, and log in users with the CometChat Flutter SDK using app keys and region. | +| Key methods | `init()` | +| Key classes | `CometChatException` · `CometChatSubscriptionType` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Authentication](/sdk/flutter/authentication-overview) · [Chat SDK](/sdk/flutter/overview) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ### Get your Application Keys [Signup for CometChat](https://app.cometchat.com/) and then: diff --git a/sdk/flutter/threaded-messages.mdx b/sdk/flutter/threaded-messages.mdx index c796bcd1b..760715f27 100644 --- a/sdk/flutter/threaded-messages.mdx +++ b/sdk/flutter/threaded-messages.mdx @@ -3,6 +3,23 @@ title: "Threaded Messages" description: "Send, receive, and fetch CometChat threaded messages in Flutter apps using parent message IDs." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Send, receive, and fetch CometChat threaded messages in Flutter apps using parent message IDs. | +| Key methods | `addMessageListener()` · `sendMessage()` | +| Key classes | `TextMessage` · `CometChatException` · `BaseMessage` · `CustomMessage` · `MediaMessage` · `CometChatConversationType` · `CometChatMessageType` | +| Listener callbacks | `onCustomMessageReceived()` · `onMediaMessageReceived()` · `onTextMessageReceived()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [Receive A Message](/sdk/flutter/receive-messages) | +| Full reference | [`TextMessage`](/sdk/reference/messages#textmessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`BaseMessage`](/sdk/reference/messages#basemessage) · [`CustomMessage`](/sdk/reference/messages#custommessage) · [`MediaMessage`](/sdk/reference/messages#mediamessage) | + + + Messages that are started from a particular message are called Threaded messages or simply threads. diff --git a/sdk/flutter/transfer-group-ownership.mdx b/sdk/flutter/transfer-group-ownership.mdx index 1f45e7f11..013143c60 100644 --- a/sdk/flutter/transfer-group-ownership.mdx +++ b/sdk/flutter/transfer-group-ownership.mdx @@ -3,6 +3,22 @@ title: "Transfer Group Ownership" description: "Transfer CometChat group ownership to another member in Flutter apps before the current owner leaves the group." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Transfer CometChat group ownership to another member in Flutter apps before the current owner leaves the group. | +| Key methods | `transferGroupOwnership()` | +| Key classes | `CometChatException` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Change Member Scope](/sdk/flutter/group-change-member-scope) · [Update A Group](/sdk/flutter/update-group) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + *In other words, as a logged-in user, how do I transfer the ownership of any group if I am the owner of the group?* diff --git a/sdk/flutter/transient-messages.mdx b/sdk/flutter/transient-messages.mdx index 4d2676079..9f7faf295 100644 --- a/sdk/flutter/transient-messages.mdx +++ b/sdk/flutter/transient-messages.mdx @@ -4,6 +4,23 @@ sidebarTitle: "Transient Messages" description: "Send and receive ephemeral real-time messages with the CometChat Flutter SDK for live reactions and temporary indicators." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Send and receive ephemeral real-time messages with the CometChat Flutter SDK for live reactions and temporary indicators. | +| Key methods | `addMessageListener()` · `sendTransientMessage()` | +| Key classes | `TransientMessage` · `CometChatException` · `CometChatReceiverType` | +| Listener callbacks | `onTransientMessageReceived()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [Typing Indicators](/sdk/flutter/typing-indicators) | +| Full reference | [`TransientMessage`](/sdk/reference/auxiliary#transientmessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + Transient messages are messages that are sent in real-time only and are not saved or tracked anywhere. The receiver of the message will only receive the message if he is online and these messages cannot be retrieved later. diff --git a/sdk/flutter/typing-indicators.mdx b/sdk/flutter/typing-indicators.mdx index 0bc6cabd5..5afc2c98f 100644 --- a/sdk/flutter/typing-indicators.mdx +++ b/sdk/flutter/typing-indicators.mdx @@ -3,6 +3,23 @@ title: "Typing Indicators" description: "Send and receive CometChat typing indicators in Flutter apps for one-on-one and group conversations." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Send and receive CometChat typing indicators in Flutter apps for one-on-one and group conversations. | +| Key methods | `addMessageListener()` · `endTyping()` · `startTyping()` | +| Key classes | `CometChatReceiverType` · `TypingIndicator` | +| Listener callbacks | `onTypingEnded()` · `onTypingStarted()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Transient Messages](/sdk/flutter/transient-messages) · [All Real Time Listeners](/sdk/flutter/real-time-listeners) | +| Full reference | [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) | + + + ## Send a Typing Indicator diff --git a/sdk/flutter/update-group.mdx b/sdk/flutter/update-group.mdx index 3200bd55c..5a8e0a143 100644 --- a/sdk/flutter/update-group.mdx +++ b/sdk/flutter/update-group.mdx @@ -3,6 +3,22 @@ title: "Update A Group" description: "Update CometChat group details from Flutter apps with updateGroup and a Group object containing changed fields." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Update CometChat group details from Flutter apps with updateGroup and a Group object containing changed fields. | +| Key methods | `updateGroup()` | +| Key classes | `Group` · `CometChatException` · `CometChatGroupType` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Create A Group](/sdk/flutter/create-group) · [Delete A Group](/sdk/flutter/delete-group) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Update Group diff --git a/sdk/flutter/upload-files.mdx b/sdk/flutter/upload-files.mdx index 1cd48be55..a0d1c0c35 100644 --- a/sdk/flutter/upload-files.mdx +++ b/sdk/flutter/upload-files.mdx @@ -4,6 +4,23 @@ sidebarTitle: "Upload Files" description: "Upload files directly to storage with per-file progress, remove, and retry through an UploadFileRequest — then send them as one or more media messages with multiple attachments." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Upload files directly to storage with per-file progress, remove, and retry through an UploadFileRequest — then send them as one or more media messages with multiple attachments. | +| Key methods | `createUploadFileRequest()` · `getMaxAttachmentCount()` · `getMaxAttachmentSize()` · `sendMediaMessage()` | +| Key classes | `CometChatException` · `MediaMessage` · `Attachment` · `CometChatConversationType` · `CometChatMessageType` | +| Listener callbacks | `onComplete()` · `onFileError()` · `onFileFailure()` · `onFileProgress()` · `onFileUploaded()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Send A Message](/sdk/flutter/send-message) · [Messaging](/sdk/flutter/messaging-overview) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`Attachment`](/sdk/reference/auxiliary#attachment) | + + + `CometChat.createUploadFileRequest(receiverId, receiverType)` returns an **`UploadFileRequest`** — the entry point for uploading files **directly to storage** with **per-file progress, success, and failure**. Upload is **decoupled from sending**: each uploaded file yields an `Attachment` (carrying a hosted URL), which you then attach to a `MediaMessage` and send with [`sendMediaMessage()`](/sdk/flutter/send-message#media-message). A request object is scoped to **one destination** (`receiverId` / `receiverType`) and **one upload batch**. This is the recommended way to build a **multi-attachment composer**: create a request, upload a batch of files, show a progress bar per file, let the user remove or retry individual files, then send them as a single media message with multiple attachments (or split across several). diff --git a/sdk/flutter/user-management.mdx b/sdk/flutter/user-management.mdx index 4da1892b3..7ae216b68 100644 --- a/sdk/flutter/user-management.mdx +++ b/sdk/flutter/user-management.mdx @@ -3,6 +3,22 @@ title: "User Management" description: "Create, update, and manage CometChat users in Flutter apps before login using user objects, auth keys, and REST API workflows." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Create, update, and manage CometChat users in Flutter apps before login using user objects, auth keys, and REST API workflows. | +| Key methods | `createUser()` · `updateCurrentUserDetails()` | +| Key classes | `User` · `CometChatException` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Users](/sdk/flutter/users-overview) · [Retrieve Users](/sdk/flutter/retrieve-users) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. diff --git a/sdk/flutter/user-presence.mdx b/sdk/flutter/user-presence.mdx index 8c567ea0c..c8af0f2d1 100644 --- a/sdk/flutter/user-presence.mdx +++ b/sdk/flutter/user-presence.mdx @@ -3,6 +3,23 @@ title: "User Presence" description: "Track CometChat user presence in Flutter apps with subscriptions for all users, roles, friends, and real-time user listeners." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_sdk` | +| Import | `import 'package:cometchat_sdk/cometchat_sdk.dart';` | +| Purpose | Track CometChat user presence in Flutter apps with subscriptions for all users, roles, friends, and real-time user listeners. | +| Key methods | `addUserListener()` · `removeUserListener()` | +| Key classes | `User` | +| Listener callbacks | `onUserOffline()` · `onUserOnline()` | +| Prerequisites | SDK initialised via [`CometChat.init()`](/sdk/flutter/setup) and a logged-in user via [`CometChat.login()`](/sdk/flutter/authentication-overview). | +| Constraints | `onSuccess` and `onError` are **both required** — omitting either is a compile error, and awaiting the call alone gives you nothing to act on. Put the success path inside `onSuccess`. | +| Related | [Retrieve Users](/sdk/flutter/retrieve-users) · [All Real Time Listeners](/sdk/flutter/real-time-listeners) | +| Full reference | [`User`](/sdk/reference/entities#user) | + + + User Presence helps us understand if a user is available to chat or not. diff --git a/sdk/ios/llms-ios-v4.mdx b/sdk/ios/llms-ios-v4.mdx new file mode 100644 index 000000000..e57f770b8 --- /dev/null +++ b/sdk/ios/llms-ios-v4.mdx @@ -0,0 +1,126 @@ +--- +title: "iOS Chat SDK v4 — LLM docs index" +description: "Machine-readable, iOS-SDK-v4-scoped index of every Chat SDK page as a clean .md twin. Built for AI coding agents; kept out of the human sidebar." +--- + +{/* + SCOPED LLM INDEX for the iOS Chat SDK v4. + - UNLISTED, NOT hidden: intentionally omitted from docs.json navigation so it never shows in + the human sidebar — but it IS built, served as a clean .md twin, and INDEXED for search + + AI assistants (so AI tools, and the skills pack via its docs-map, can discover and read it). + - We deliberately do NOT use `hidden: true`/`noindex` here: in Mintlify `hidden` auto-applies + noindex, which would drop this page from search AND the auto global llms.txt / AI context. + We want it discoverable, so it stays indexable. + - Scope is v4 ONLY. The 2.0/ and 3.0/ trees are deliberately excluded — linking them would + route agents at dead API surfaces. +*/} + +# iOS Chat SDK v4 — LLM docs index (Latest) + +> Headless Swift chat SDK. Package `CometChatSDK@4`. This page is an **iOS-SDK-v4-only** routing +> index for AI agents — a scoped alternative to the site-wide `/docs/llms.txt`. + +## How to use this index +Each link points to the docs page; **append `.md`** to its URL to fetch the clean Markdown twin. +Each page opens with an **"AI Integration Quick Reference"** block (package · import · key +methods) — read that FIRST, then the body for the full call. +- Convention: any docs page URL + `.md` → raw Markdown. +- Fallback: if a `.md` twin 404s, fetch the same URL **without** `.md` (HTML). +- Never answer a method signature from memory, and never read the framework binary's + `.swiftinterface` to decide *behaviour* — it proves a symbol exists, nothing more. + +## When to use this index +Two cases: +1. **Headless app** — no CometChat UI, you are building your own views on the SDK. +2. **UI Kit fallback** — the app uses the iOS UI Kit v5, but the feature you need ships **no UI + Kit component** (AI agents, campaigns, moderation, adding group members, transient messages, + low-level presence, webhooks). Check the kit first + ([iOS UI Kit v5 index](/ui-kit/ios/llms-ios-v5)); if there is no component, come here. + +## API facts an agent must not guess +- Callbacks use `.success` / `.onError` — **not** Swift's `Result.failure`. +- `CometChatException` does **not** conform to Swift's `Error`; read `errorDescription`, not + `localizedDescription`, and downcast with `error as? CometChatException`. +- Request objects use the **builder** pattern (`MessagesRequest.MessagesRequestBuilder`), and + listeners are registered per-class with a unique identifier you must later remove. +- In SwiftUI hosts, qualify SDK types (`CometChatSDK.User`, `CometChatSDK.Group`) — SwiftUI + declares its own `Group`. + +## Getting started +- [iOS SDK](/sdk/ios/overview) +- [Setup](/sdk/ios/setup) +- [Key Concepts](/sdk/ios/key-concepts) +- [Authentication](/sdk/ios/authentication-overview) +- [Changelog](/sdk/ios/changelog) +- [Upgrading From V3](/sdk/ios/upgrading-from-v3-to-v4) +- [Rate Limits](/sdk/ios/rate-limits) + +## Messaging +- [Send Messages](/sdk/ios/send-message) +- [Receive Messages](/sdk/ios/receive-message) +- [Edit Message](/sdk/ios/edit-message) +- [Delete Message](/sdk/ios/delete-message) +- [Flag Message](/sdk/ios/flag-message) +- [Message Filtering](/sdk/ios/additional-message-filtering) +- [Message Structure And Hierarchy](/sdk/ios/message-structure-and-hierarchy) +- [Threaded Messages](/sdk/ios/threaded-messages) +- [Transient Messages](/sdk/ios/transient-messages) +- [Upload Files & Send Attachments](/sdk/ios/upload-files) +- [Reactions](/sdk/ios/reactions) +- [Mentions](/sdk/ios/mentions) +- [Delivery & Read Receipts](/sdk/ios/delivery-read-receipts) +- [Typing Indicators](/sdk/ios/typing-indicators) + +## Conversations +- [Retrieve Conversations](/sdk/ios/retrieve-conversations) +- [Delete Conversation](/sdk/ios/delete-conversation) + +## Users +- [Users](/sdk/ios/users-overview) +- [User Management](/sdk/ios/user-management) +- [Retrieve Users](/sdk/ios/retrieve-users) +- [User Presence](/sdk/ios/user-presence) +- [Block Users](/sdk/ios/block-users) + +## Groups +- [Groups](/sdk/ios/groups-overview) +- [Create A Group](/sdk/ios/create-group) +- [Update A Group](/sdk/ios/update-group) +- [Delete A Group](/sdk/ios/delete-group) +- [Join A Group](/sdk/ios/join-group) +- [Leave A Group](/sdk/ios/leave-group) +- [Retrieve Groups](/sdk/ios/retrieve-groups) +- [Retrieve Group Members](/sdk/ios/retrieve-group-members) +- [Add Members To A Group](/sdk/ios/group-add-members) +- [Kick Member From A Group](/sdk/ios/group-kick-member) +- [Change Member Scope](/sdk/ios/group-change-member-scope) +- [Transfer Group Ownership](/sdk/ios/transfer-group-ownership) + +## Calling +- [Calling](/sdk/ios/calling-overview) + +## AI +- [AI](/sdk/ios/ai-user-copilot-overview) +- [AI Agents](/sdk/ios/ai-agents) +- [Bots](/sdk/ios/ai-chatbots-overview) +- [AI Moderation](/sdk/ios/ai-moderation) + +## Real-time, connection, and lifecycle +- [All Real Time Delegates (Listeners)](/sdk/ios/all-real-time-delegates-listeners) +- [Connection Status](/sdk/ios/connection-status) +- [Connection Behaviour](/sdk/ios/web-socket-connection-behaviour) +- [Managing Web Socket Connections Manually](/sdk/ios/managing-web-socket-connections-manually) + +## Push notifications +- [Prepare Your App For Background Updates](/sdk/ios/prepare-your-app-for-background-updates) +- [Launch Chat Window On Tap Of Push Notification](/sdk/ios/launch-chat-window-on-tap-of-push-notification) +- [Launch Call Screen On Tap Of Push Notification](/sdk/ios/launch-call-screen-on-tap-of-push-notification) +- [Marking Delivered From Push Notification](/sdk/ios/marking-delivered-with-push-notification) +- [Increment App Icon Badge Count](/sdk/ios/increment-app-icon-badge-count) +- [Remove Delivered Notifications](/sdk/ios/remove-delivered-notifications) + +## Platform extras +- [Extensions](/sdk/ios/extensions-overview) +- [Campaigns](/sdk/ios/campaigns) +- [Webhooks](/sdk/ios/webhooks-overview) +- [Publishing App On App Store](/sdk/ios/publishing-app-on-appstore) diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index 04056763f..df69e8c8d 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -3,6 +3,23 @@ title: "AI Agents" description: "Handle CometChat AI Agent events, tool calls, and agent messages in JavaScript apps." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.addAIAssistantListener(listenerId, ...)` · `CometChat.removeAIAssistantListener(listenerId)` · `CometChat.addMessageListener(listenerId, ...)` · `CometChat.removeMessageListener(listenerId)` | +| Key classes | `CometChat.AIAssistantBaseEvent` · `CometChat.AIAssistantMessage` · `CometChat.AIToolResultMessage` · `CometChat.AIToolArgumentMessage` · `CometChat.AIToolCall` | +| Primary output | Real-time run events are delivered as `CometChat.AIAssistantBaseEvent` objects to the `onAIAssistantEventReceived` callback; after the run completes, persisted `AIAssistantMessage` / `AIToolResultMessage` / `AIToolArgumentMessage` objects arrive on the `MessageListener` | +| Listeners registered | `AIAssistantListener` via `addAIAssistantListener` / `removeAIAssistantListener` (callback `onAIAssistantEventReceived`); `CometChat.MessageListener` via `addMessageListener` / `removeMessageListener` (callbacks `onAIAssistantMessageReceived`, `onAIToolResultReceived`, `onAIToolArgumentsReceived`) | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | Agents only respond to text messages. `Run Start` and `Run Finished` events are always emitted; Tool Call events only appear when tools are invoked | +| Related | [AI Moderation](/sdk/javascript/ai-moderation) · [AI User Copilot](/sdk/javascript/ai-user-copilot-overview) · [Card Messages](/sdk/javascript/card-messages) · [Send a Message](/sdk/javascript/send-message) | +| Full reference | [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) · [`AIAssistantMessage`](/sdk/reference/messages#aiassistantmessage) · [`AIToolResultMessage`](/sdk/reference/messages#aitoolresultmessage) · [`AIToolArgumentMessage`](/sdk/reference/messages#aitoolargumentmessage) | + + + ## AI Agents Overview AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index bd78c0c1e..0c7e3bad9 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -3,6 +3,23 @@ title: "All Real Time Listeners" description: "Use CometChat real-time listeners for user presence, groups, messages, calls, AI assistant events, and ongoing calls." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.addUserListener(id, new CometChat.UserListener({...}))` · `CometChat.addGroupListener(id, new CometChat.GroupListener({...}))` · `CometChat.addMessageListener(id, new CometChat.MessageListener({...}))` · `CometChat.addCallListener(id, new CometChat.CallListener({...}))` · `CometChat.addAIAssistantListener(id, new CometChat.AIAssistantListener({...}))` · `CometChat.addLoginListener(id, new CometChat.LoginListener({...}))` · `CometChat.addConnectionListener(id, new CometChat.ConnectionListener({...}))` | +| Key classes | `CometChat.UserListener` · `CometChat.GroupListener` · `CometChat.MessageListener` · `CometChat.CallListener` · `CometChat.AIAssistantListener` · `CometChat.LoginListener` · `CometChat.ConnectionListener` | +| Primary output | Each listener fires typed callbacks — e.g. `onUserOnline(user)`, `onGroupMemberJoined(action, user, group)`, `onTextMessageReceived(message)`, `onMessagesDelivered(receipt)`, `onIncomingCallReceived(call)`, `onAIAssistantEventReceived(event)`, `loginSuccess(user)`, `onConnected()` | +| Listeners registered | `UserListener` (`onUserOnline` · `onUserOffline`); `GroupListener` (`onGroupMemberJoined` · `onGroupMemberLeft` · `onGroupMemberKicked` · `onGroupMemberBanned` · `onGroupMemberUnbanned` · `onGroupMemberScopeChanged` · `onMemberAddedToGroup`); `MessageListener` (`onTextMessageReceived` · `onMediaMessageReceived` · `onCustomMessageReceived` · `onTypingStarted` · `onTypingEnded` · `onMessagesDelivered` · `onMessagesRead` · `onMessageEdited` · `onMessageDeleted` · `onMessageReactionAdded` · `onCardMessageReceived` · `onAIAssistantMessageReceived`); `CallListener` (`onIncomingCallReceived` · `onOutgoingCallAccepted` · `onOutgoingCallRejected` · `onIncomingCallCancelled` · `onCallEndedMessageReceived`); `AIAssistantListener` (`onAIAssistantEventReceived`); `LoginListener` (`loginSuccess` · `loginFailure` · `logoutSuccess` · `logoutFailure`); `ConnectionListener` (`onConnected` · `inConnecting` · `onDisconnected` · `onFeatureThrottled`). Remove each with the matching `remove*Listener(id)` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | Listener IDs must be unique per listener; use the same ID to remove it. Always call the matching `remove*Listener(id)` on unmount to avoid memory leaks and duplicate handling. `OngoingCallListener` belongs to the **Calls SDK** (not the Chat SDK) and is used via `CometChatCalls.addCallEventListener()` | +| Related | [Receive a Message](/sdk/javascript/receive-message) · [Delivery & Read Receipts](/sdk/javascript/delivery-read-receipts) · [Typing Indicators](/sdk/javascript/typing-indicators) · [User Presence](/sdk/javascript/user-presence) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) · [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + CometChat provides 4 listeners viz. 1. [User Listener](/sdk/javascript/all-real-time-listeners#user-listener) diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 1b5fc8728..07c417761 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -4,6 +4,23 @@ sidebarTitle: "Authentication" description: "Create users and authenticate them securely with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.login(UID, authKey)` · `CometChat.login(authToken)` · `CometChat.getLoggedinUser()` · `CometChat.logout()` · `CometChat.createUser(user, authKey)` | +| Key classes | `CometChat.User` · `CometChat.CometChatException` | +| Primary output | `login()` resolves to a `CometChat.User`; `getLoggedinUser()` resolves to the `CometChat.User` or `null` when no session exists; `logout()` resolves on success; all reject with `CometChat.CometChatException` | +| Listeners registered | `CometChat.LoginListener` via `CometChat.addLoginListener(listenerID, ...)` / `CometChat.removeLoginListener(listenerID)`; key callbacks `loginSuccess`, `loginFailure`, `logoutSuccess`, `logoutFailure` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk), and the user must already exist (create via the [Dashboard](https://app.cometchat.com) or the [Create User API](https://api-explorer.cometchat.com/reference/creates-user)) | +| Constraints | Auth Key login and `createUser()` with an Auth Key are for development/testing only — never ship an Auth Key in client code. For production, generate an [Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) server-side and pass it to `login(authToken)` | +| Related | [User Management](/sdk/javascript/user-management) · [Connection Status](/sdk/javascript/connection-status) · [All Real-Time Listeners](/sdk/javascript/all-real-time-listeners) · [Send a Message](/sdk/javascript/send-message) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + ## Create User Before you log in a user, you must add the user to CometChat. diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index c6295b621..b6a7d4713 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -3,6 +3,23 @@ title: "Block Users" description: "Block and unblock users in chat apps with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.blockUsers(usersList)` · `CometChat.unblockUsers(usersList)` · `blockedUsersRequest.fetchNext()` (build via `BlockedUsersRequestBuilder`) | +| Request builder | `CometChat.BlockedUsersRequestBuilder` — configure with `.setLimit()` · `.setSearchKeyword()` · `.setDirection()`; then `.build()` → `.fetchNext()` | +| Key classes | `CometChat.User` (access via `getBlockedByMe()`, `getHasBlockedMe()`); direction via `CometChat.BlockedUsersRequest.directions.BLOCKED_BY_ME` / `.HAS_BLOCKED_ME` / `.BOTH` | +| Primary output | `blockUsers()` / `unblockUsers()` resolve to a `{ uid: "success" \| "fail" }` object (each UID processed independently); `fetchNext()` resolves to `Promise`; all reject with `CometChat.CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | `setDirection()` default is `BOTH`; `blockUsers()` / `unblockUsers()` take an array of UIDs | +| Related | [Retrieve Users](/sdk/javascript/retrieve-users) · [User Presence](/sdk/javascript/user-presence) · [User Management](/sdk/javascript/user-management) · [Flag a Message](/sdk/javascript/flag-message) | +| Full reference | [`User`](/sdk/reference/entities#user) | + + + ## Block Users Block users to prevent all communication with them. Use `blockUsers()` with an array of UIDs. diff --git a/sdk/javascript/campaigns.mdx b/sdk/javascript/campaigns.mdx index 20253d779..fc5ef04b4 100644 --- a/sdk/javascript/campaigns.mdx +++ b/sdk/javascript/campaigns.mdx @@ -3,6 +3,23 @@ title: "Campaigns" description: "Fetch notification feed items, listen for real-time delivery, mark items as read/delivered, report engagement, and track push notifications using the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.markFeedItemAsRead(feedItem)` · `CometChat.markFeedItemAsDelivered(feedItem)` · `CometChat.markFeedItemsAsDelivered(feedItems)` · `CometChat.reportFeedEngagement(feedItem, interactionString)` · `CometChat.getNotificationFeedUnreadCount()` · `CometChat.getNotificationFeedItem(id)` · `CometChat.markPushNotificationDelivered(pushNotification)` · `CometChat.markPushNotificationClicked(pushNotification)` | +| Request builder | `new CometChat.NotificationFeedRequestBuilder().setLimit(limit).setReadState(state).setCategory(category).setChannelId(channelId).setTags(tags).build()` → `.fetchNext()` · also `NotificationCategoriesRequestBuilder().setLimit(limit).build()` → `.fetchNext()` | +| Key classes | `CometChat.NotificationFeedItem` · `CometChat.NotificationCategory` · `CometChat.PushNotification` · `CometChat.CardMessage` | +| Primary output | `NotificationFeedRequest.fetchNext()` resolves to `CometChat.NotificationFeedItem[]` (empty array when exhausted); `getNotificationFeedUnreadCount()` resolves to `{ count: number }`; mark/report methods resolve on success; all reject with `CometChat.CometChatException` | +| Listeners registered | Notification feed listener via `CometChat.addNotificationFeedListener("feedListener", ...)` / `CometChat.removeNotificationFeedListener("feedListener")`; key callback `onFeedItemReceived`. Card chat messages arrive on `CometChat.MessageListener`'s `onCardMessageReceived` callback | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview); channels, categories, templates, and campaigns configured in the [Dashboard](/campaigns#setup-flow). Render cards with `@cometchat/cards-react` | +| Constraints | Card messages are **receive-only** — created and sent exclusively via the Platform (REST) API or Dashboard Bubble Builder; the SDK exposes the raw Card Schema JSON via `getCard()`. The Cards library is a pure renderer and does not execute card actions — your app must handle action callbacks | +| Related | [Card Messages](/sdk/javascript/card-messages) · [Receive a Message](/sdk/javascript/receive-message) · [All Real-Time Listeners](/sdk/javascript/all-real-time-listeners) · [Send a Message](/sdk/javascript/send-message) | + + + CometChat Campaigns lets you deliver targeted, rich notifications to users via an in-app notification feed. Each notification is a **Card Schema JSON** — a structured layout rendered natively by the CometChat Cards library. The SDK provides APIs to fetch feed items, listen for real-time delivery, mark items as read/delivered, report engagement, and retrieve unread counts. diff --git a/sdk/javascript/card-messages.mdx b/sdk/javascript/card-messages.mdx index 91d4ccc2b..f1a108059 100644 --- a/sdk/javascript/card-messages.mdx +++ b/sdk/javascript/card-messages.mdx @@ -3,6 +3,23 @@ title: "Card Messages" description: "Receive and render rich card messages with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.addMessageListener(listenerID, new CometChat.MessageListener({...}))` · `CometChat.addAIAssistantListener(listenerID, new CometChat.AIAssistantListener({...}))` · `cardMessage.getCard()` · `message.getElements()` · `element.getType()` / `element.getData()` | +| Key classes | `CometChat.CardMessage` · `CometChat.MessageListener` · `CometChat.AIAssistantMessage` · `CometChat.AIAssistantElement` · `CometChat.AIAssistantListener` · `CometChat.AIAssistantBaseEvent` (`AIAssistantCardStartedEvent` · `AIAssistantCardReceivedEvent` · `AIAssistantCardEndedEvent`) | +| Primary output | Cards are receive-only. Standalone cards arrive as a `CardMessage` (`getCard()` returns the raw Card Schema JSON, or `undefined`); inline cards arrive as elements on an `AIAssistantMessage` (`getElements()` returns `AIAssistantElement[]`); streaming cards arrive as `card_start` / `card` / `card_end` events (`getCard()` on the `card` event) | +| Listeners registered | `MessageListener` — `onCardMessageReceived(cardMessage: CometChat.CardMessage)` and `onAIAssistantMessageReceived(message: CometChat.AIAssistantMessage)`; `AIAssistantListener` — `onAIAssistantEventReceived(event: CometChat.AIAssistantBaseEvent)` for `card_start` / `card` / `card_end`. Remove with `CometChat.removeMessageListener(id)` / `CometChat.removeAIAssistantListener(id)` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | Card support is **receive-only** — cards cannot be composed or sent from the SDK (they are authored server-side via the Platform REST API or Dashboard). Branch on `getCategory() === "card"` (a card's `getType()` returns `"text"`). The SDK never interprets the card body; rendering is your app's responsibility. Streaming and persisted cards for the same card share a `cardId` — correlate to avoid rendering twice. Always remove listeners on unmount | +| Related | [Receive a Message](/sdk/javascript/receive-message) · [AI Agents](/sdk/javascript/ai-agents) · [All Real Time Listeners](/sdk/javascript/all-real-time-listeners) · [Send a Message](/sdk/javascript/send-message) | +| Full reference | [`CardMessage`](/sdk/reference/messages#cardmessage) · [`AIAssistantMessage`](/sdk/reference/messages#aiassistantmessage) · [`AIAssistantElement`](/sdk/reference/messages#aiassistantelement) · [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) | + + + Card messages let your app display rich, structured content — such as product cards, confirmations, or AI-generated summaries — inside a conversation. In the JavaScript SDK, card support is **receive-only**: the SDK deserializes incoming cards and hands you their raw payload through typed accessors, and your app is responsible for turning that payload into UI. The body of a card is **Card Schema JSON** — the same structured layout used by [Campaigns notification feeds](/sdk/javascript/campaigns). Cards are authored server-side (they cannot be composed or sent from the SDK) via the [Platform (REST) API](/rest-api/messages/send-message) or the **Dashboard Bubble Builder**, and delivered to clients like any other message. diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index aa076ccb5..3e44da187 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -3,6 +3,23 @@ title: "Delivery & Read Receipts" description: "Mark messages as delivered or read and handle receipts with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.markAsDelivered(message)` · `CometChat.markAsRead(message)` · `CometChat.markConversationAsDelivered(conversationWith, conversationType)` · `CometChat.markConversationAsRead(conversationWith, conversationType)` · `CometChat.markAsUnread(message)` · `CometChat.getMessageReceipts(messageId)` | +| Key classes | `CometChat.MessageListener` · `CometChat.MessageReceipt` · `CometChat.BaseMessage` | +| Primary output | `markAsDelivered()` / `markAsRead()` are fire-and-forget (they resolve but do **not** return a `MessageReceipt`); `markConversationAsDelivered()` / `markConversationAsRead()` resolve with a `string`; `markAsUnread()` resolves with a `string`; `getMessageReceipts()` resolves to `Promise`; all reject with `CometChat.CometChatException` | +| Listeners registered | `MessageListener` via `CometChat.addMessageListener(listenerID, ...)` / `CometChat.removeMessageListener(listenerID)` — receipt callbacks: `onMessagesDelivered`, `onMessagesRead`, `onMessagesDeliveredToAll` (groups), `onMessagesReadByAll` (groups), each receiving a `CometChat.MessageReceipt` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | `onMessagesDeliveredToAll`, `onMessagesReadByAll`, group `deliveredAt` / `readAt`, and `markAsUnread()` require the **Enhanced Messaging Status** feature. Always remove listeners on unmount to avoid memory leaks | +| Related | [Receive a Message](/sdk/javascript/receive-message) · [Typing Indicators](/sdk/javascript/typing-indicators) · [Retrieve Conversations](/sdk/javascript/retrieve-conversations) · [All Real Time Listeners](/sdk/javascript/all-real-time-listeners) | +| Full reference | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) · [`User`](/sdk/reference/entities#user) · [`BaseMessage`](/sdk/reference/messages#basemessage) | + + + ## Mark Messages as Delivered _In other words, as a recipient, how do I inform the sender that I've received a message?_ diff --git a/sdk/javascript/group-kick-ban-members.mdx b/sdk/javascript/group-kick-ban-members.mdx index 8fd34655d..46c090bb5 100644 --- a/sdk/javascript/group-kick-ban-members.mdx +++ b/sdk/javascript/group-kick-ban-members.mdx @@ -3,6 +3,24 @@ title: "Ban Or Kick Member From A Group" description: "Kick, ban, and unban CometChat group members in JavaScript apps when the logged-in user is an admin or moderator." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.kickGroupMember(GUID, UID)` · `CometChat.banGroupMember(GUID, UID)` · `CometChat.unbanGroupMember(GUID, UID)` | +| Request builder | `new CometChat.BannedMembersRequestBuilder(GUID).setLimit(limit).setSearchKeyword(keyword).build()` → `.fetchNext()` | +| Key classes | `CometChat.GroupMember` · `CometChat.User` · `CometChat.Group` · `CometChat.Action` | +| Primary output | `kickGroupMember()` / `banGroupMember()` / `unbanGroupMember()` resolve to `boolean` (`true`) · `BannedMembersRequest.fetchNext()` resolves to `CometChat.GroupMember[]` · all reject with `CometChat.CometChatException` | +| Listeners registered | `CometChat.GroupListener` via `CometChat.addGroupListener(listenerID, ...)` / `CometChat.removeGroupListener(listenerID)`; key callbacks `onGroupMemberKicked`, `onGroupMemberBanned`, `onGroupMemberUnbanned` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | Kick, ban, and unban can only be performed by the group **Admin** or **Moderator**. A kicked user can rejoin; a banned user cannot rejoin until unbanned | +| Related | [Add Members](/sdk/javascript/group-add-members) · [Change Member Scope](/sdk/javascript/group-change-member-scope) · [Retrieve Group Members](/sdk/javascript/retrieve-group-members) · [Leave a Group](/sdk/javascript/leave-group) | +| Full reference | [`GroupMember`](/sdk/reference/entities#groupmember) · [`User`](/sdk/reference/entities#user) · [`Group`](/sdk/reference/entities#group) · [`Action`](/sdk/reference/messages#action) | + + + There are certain actions that can be performed on the group members: 1. Kick a member from the group diff --git a/sdk/javascript/leave-group.mdx b/sdk/javascript/leave-group.mdx index d3a9c32a1..9ec256558 100644 --- a/sdk/javascript/leave-group.mdx +++ b/sdk/javascript/leave-group.mdx @@ -49,6 +49,10 @@ Once a group is left, the user will no longer receive any updates or messages pe On success, the method resolves with `true` (boolean). + +The group **owner cannot leave** the group directly — `leaveGroup()` rejects for the owner. Transfer ownership to another member with [`transferGroupOwnership()`](/sdk/javascript/transfer-group-ownership) first, then call `leaveGroup()`. + + ## Real-time Group Member Left Events Register a `GroupListener` to receive events when members leave. diff --git a/sdk/javascript/llms-javascript-v4.mdx b/sdk/javascript/llms-javascript-v4.mdx new file mode 100644 index 000000000..98f212703 --- /dev/null +++ b/sdk/javascript/llms-javascript-v4.mdx @@ -0,0 +1,113 @@ +--- +title: "JavaScript Chat SDK v4 — LLM docs index" +description: "Machine-readable, JavaScript-SDK-v4-scoped index of every SDK page as a clean .md twin. Built for AI coding agents; kept out of the human sidebar." +--- + +{/* + SCOPED LLM INDEX for the JavaScript Chat SDK v4. + - UNLISTED, NOT hidden: intentionally omitted from docs.json navigation so it never shows in + the human sidebar — but it IS built, served as a clean .md twin, and INDEXED for search + + AI assistants (so AI tools, and this pack's skill via its docs-map, can discover and read it). + - We deliberately do NOT use `hidden: true`/`noindex` here: in Mintlify `hidden` auto-applies + noindex, which would drop this page from search AND the auto global llms.txt / AI context. + We want it discoverable, so it stays indexable. + - Fetch this file's own .md twin as a lightweight, JS-SDK-only routing index instead of the + site-wide /docs/llms.txt (which spans every product and is far larger). +*/} + +# JavaScript Chat SDK v4 — LLM docs index (Latest) + +> Low-level JavaScript/TypeScript chat + calling client. Package +> `@cometchat/chat-sdk-javascript@4`. This page is a **JavaScript-SDK-v4-only** routing index for +> AI agents — a scoped alternative to the site-wide `/docs/llms.txt`. + +## How to use this index +Each link points to the docs page; **append `.md`** to its URL to fetch the clean Markdown twin +(verbatim code + method signatures, parameters, and listener contracts). Pick the page for the +intent, then read the API there. +- Convention: any docs page URL + `.md` → raw Markdown. +- Fallback: if a `.md` twin 404s, fetch the same URL **without** `.md` (HTML). Never read a + package `.d.ts` and never answer APIs from memory. + +## Hot path — usually no fetch needed +For a plain "add chat" the install, `init → login`, and the core `sendMessage` / `receive-message` +listener flow are stable; a well-built agent skill bakes them. Fetch below only for exhaustive +parameters, long-tail methods, group/user management, calling, or edge-case listeners. +- Setup: [Integration / Setup](/sdk/javascript/setup-sdk) +- Auth/lifecycle: [Authentication](/sdk/javascript/authentication-overview) +- Core send/receive: [Send a Message](/sdk/javascript/send-message) · [Receive a Message](/sdk/javascript/receive-message) · [Real-time Listeners](/sdk/javascript/all-real-time-listeners) + +## Getting started / integration +- [Overview](/sdk/javascript/overview) +- [Integration / Setup](/sdk/javascript/setup-sdk) +- [Authentication](/sdk/javascript/authentication-overview) + +## Messaging +- [Send a Message](/sdk/javascript/send-message) +- [Media & File Messages](/sdk/javascript/upload-files) +- [Receive a Message](/sdk/javascript/receive-message) +- [Interactive / Card Messages](/sdk/javascript/card-messages) +- [Message Filtering](/sdk/javascript/message-filtering) +- [Retrieve Conversations](/sdk/javascript/retrieve-conversations) +- [Threaded Messages](/sdk/javascript/threaded-messages) +- [Edit a Message](/sdk/javascript/edit-message) +- [Delete a Message](/sdk/javascript/delete-message) +- [Flag a Message](/sdk/javascript/flag-message) +- [Delete a Conversation](/sdk/javascript/delete-conversation) +- [Typing Indicators](/sdk/javascript/typing-indicators) +- [Transient Messages](/sdk/javascript/transient-messages) +- [Delivery & Read Receipts](/sdk/javascript/delivery-read-receipts) +- [Mentions](/sdk/javascript/mentions) +- [Reactions](/sdk/javascript/reactions) + +## Calling +- [Calling — Overview](/sdk/javascript/calling-overview) + +## Users +- [Users — Overview](/sdk/javascript/users-overview) +- [Retrieve Users](/sdk/javascript/retrieve-users) +- [User Management](/sdk/javascript/user-management) +- [Block Users](/sdk/javascript/block-users) +- [User Presence](/sdk/javascript/user-presence) + +## Groups +- [Groups — Overview](/sdk/javascript/groups-overview) +- [Retrieve Groups](/sdk/javascript/retrieve-groups) +- [Create a Group](/sdk/javascript/create-group) +- [Update a Group](/sdk/javascript/update-group) +- [Join a Group](/sdk/javascript/join-group) +- [Leave a Group](/sdk/javascript/leave-group) +- [Delete a Group](/sdk/javascript/delete-group) +- [Retrieve Group Members](/sdk/javascript/retrieve-group-members) +- [Add Group Members](/sdk/javascript/group-add-members) +- [Kick / Ban Members](/sdk/javascript/group-kick-ban-members) +- [Change Member Scope](/sdk/javascript/group-change-member-scope) +- [Transfer Group Ownership](/sdk/javascript/transfer-group-ownership) + +## AI, campaigns & webhooks +- [AI Moderation](/sdk/javascript/ai-moderation) +- [AI Agents](/sdk/javascript/ai-agents) +- [AI Copilot](/sdk/javascript/ai-copilot) +- [Campaigns](/sdk/javascript/campaigns) +- [Webhooks](/sdk/javascript/webhooks) + +## Resources +- [Key Concepts](/sdk/javascript/key-concepts) +- [Message Structure & Hierarchy](/sdk/javascript/message-structure-and-hierarchy) +- [All Real-time Listeners](/sdk/javascript/all-real-time-listeners) +- [Rate Limits](/sdk/javascript/rate-limits) +- [Connection Status](/sdk/javascript/connection-status) +- [Managing WebSocket Connections Manually](/sdk/javascript/managing-web-sockets-connections-manually) + +## Best practices & troubleshooting +- [Best Practices](/sdk/javascript/best-practices) +- [Error Codes](/sdk/javascript/error-codes) +- [Troubleshooting](/sdk/javascript/troubleshooting) + +## Migration & overviews +- [Upgrading from v3](/sdk/javascript/upgrading-from-v3) +- [Extensions — Overview](/sdk/javascript/extensions-overview) +- [AI User Copilot — Overview](/sdk/javascript/ai-user-copilot-overview) +- [AI Chatbots — Overview](/sdk/javascript/ai-chatbots-overview) +- [Webhooks — Overview](/sdk/javascript/webhooks-overview) +- [Changelog](/sdk/javascript/changelog) diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index fc0accb02..0ce740378 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -3,6 +3,23 @@ title: "Mentions" description: "Add user mentions to CometChat messages in one-on-one and group chats using UID-based mention syntax." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.sendMessage(textMessage)` (mention with `<@uid:UID>` syntax in the text) · `messagesRequest.fetchPrevious()` (build via `MessagesRequestBuilder`) · `message.getMentionedUsers()` | +| Request builder | `CometChat.MessagesRequestBuilder` — scope with `.setUID()` / `.setGUID()`, add `.setLimit()`, then `.mentionsWithTagInfo(true)` or `.mentionsWithBlockedInfo(true)`; `.build()` → `.fetchPrevious()` / `.fetchNext()` | +| Key classes | `CometChat.TextMessage` (send), `CometChat.BaseMessage` (fetched results), `CometChat.User` (mentioned users, via `getTags()` / `getBlockedByMe()` / `getHasBlockedMe()`) | +| Primary output | `sendMessage()` resolves to the sent `CometChat.TextMessage`; `fetchPrevious()` resolves to `Promise`; `getMentionedUsers()` returns `CometChat.User[]` (empty when none); async calls reject with `CometChat.CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | Mention format is `<@uid:UID>`; mentions are supported in text messages and media message captions; `mentionsWithTagInfo()` and `mentionsWithBlockedInfo()` default to `false` | +| Related | [Send a Message](/sdk/javascript/send-message) · [Additional Message Filtering](/sdk/javascript/message-filtering) · [Reactions](/sdk/javascript/reactions) · [Threaded Messages](/sdk/javascript/threaded-messages) | +| Full reference | [`TextMessage`](/sdk/reference/messages#textmessage) · [`BaseMessage`](/sdk/reference/messages#basemessage) · [`User`](/sdk/reference/entities#user) | + + + Mentions in messages enable users to refer to specific individual within a conversation. This is done by using the `<@uid:UID>` format, where `UID` represents the user’s unique identification. Mentions are a powerful tool for enhancing communication in messaging platforms. They streamline interaction by allowing users to easily engage and collaborate with particular individuals, especially in group conversations. diff --git a/sdk/javascript/message-filtering.mdx b/sdk/javascript/message-filtering.mdx index 595b6964c..b5d155c72 100644 --- a/sdk/javascript/message-filtering.mdx +++ b/sdk/javascript/message-filtering.mdx @@ -3,6 +3,22 @@ title: "Additional Message Filtering" description: "Filter and paginate CometChat messages by user, group, type, category, tags, timestamps, and unread status." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `messagesRequest.fetchNext()` · `messagesRequest.fetchPrevious()` (build via `MessagesRequestBuilder`) | +| Request builder | `CometChat.MessagesRequestBuilder` — scope with `.setUID(uid)` / `.setGUID(guid)`; filter with `.setLimit()` · `.setMessageId()` · `.setTimestamp()` · `.setCategories()` · `.setTypes()` · `.setTags()` · `.setParentMessageId()`; then `.build()` → `.fetchNext()` (newer) / `.fetchPrevious()` (older) | +| Primary output | `Promise` — resolves to an array of message objects; rejects with `CometChat.CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview); `.setGUID()` requires the logged-in user to be a group member | +| Constraints | `.setLimit()` max is 100 messages per iteration; `hasLinks()`, `hasAttachments()`, `hasReactions()`, `hasMentions()`, `setMentionedUIDs()`, and `setAttachmentTypes()` require the Conversation & Advanced Search add-on (Advanced/Custom plans) | +| Related | [Send a Message](/sdk/javascript/send-message) · [Receive a Message](/sdk/javascript/receive-message) · [Message Structure & Hierarchy](/sdk/javascript/message-structure-and-hierarchy) · [Threaded Messages](/sdk/javascript/threaded-messages) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) | + + + The `MessagesRequest` class as you must be familiar with helps you to fetch messages based on the various parameters provided to it. This document will help you understand better the various options that are available using the `MessagesRequest` class. The `MessagesRequest` class is designed using the `Builder design pattern`. In order to obtain an object of the `MessagesRequest` class, you will have to make use of the `MessagesRequestBuilder` class in the `MessagesRequest` class. diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 0f42c7834..9e60b6b80 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -3,6 +3,23 @@ title: "Reactions" description: "Add, remove, fetch, and listen for message reactions with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.addReaction(messageId, emoji)` · `CometChat.removeReaction(messageId, emoji)` · `message.getReactions()` · `reactionCount.getReactedByMe()` · `CometChat.CometChatHelper.updateMessageWithReactionInfo(message, messageReaction, action)` | +| Request builder | `new CometChat.ReactionRequestBuilder().setMessageId(messageId).setReaction(emoji).setLimit(limit).build()` → `.fetchNext()` / `.fetchPrevious()` (max 100 per request) | +| Key classes | `CometChat.BaseMessage` · `CometChat.Reaction` · `CometChat.ReactionCount` · `CometChat.MessageReaction` · `CometChat.REACTION_ACTION` | +| Primary output | `addReaction()` / `removeReaction()` resolve to a `CometChat.BaseMessage` with updated reactions · `fetchNext()` / `fetchPrevious()` resolve to `CometChat.Reaction[]` · all reject with `CometChat.CometChatException` | +| Listeners registered | `CometChat.MessageListener` via `CometChat.addMessageListener(listenerID, ...)` / `CometChat.removeMessageListener(listenerID)`; key callbacks `onMessageReactionAdded` and `onMessageReactionRemoved` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Related | [Send a Message](/sdk/javascript/send-message) · [Receive a Message](/sdk/javascript/receive-message) · [Mentions](/sdk/javascript/mentions) · [Threaded Messages](/sdk/javascript/threaded-messages) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`Reaction`](/sdk/reference/auxiliary#reaction) · [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) · [`ReactionEvent`](/sdk/reference/auxiliary#reactionevent) | + + + Enhance user engagement in your chat application with message reactions. Users can express their emotions using reactions to messages. This feature allows users to add or remove reactions, and to fetch all reactions on a message. You can also listen to reaction events in real-time. Let's see how to work with reactions in CometChat's SDK. ## Add a Reaction diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 3ecb4256b..7e10973ab 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -3,6 +3,23 @@ title: "Receive A Message" description: "Receive real-time, unread, and historical messages with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.addMessageListener(listenerID, new CometChat.MessageListener({...}))` · `new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(limit).build()` · `messagesRequest.fetchPrevious()` · `CometChat.getUnreadMessageCount()` · `CometChat.getMessageDetails(messageId)` | +| Key classes | `CometChat.MessageListener` · `CometChat.MessagesRequestBuilder` · `CometChat.MessagesRequest` · `CometChat.BaseMessage` (`TextMessage` · `MediaMessage` · `CustomMessage`) | +| Primary output | Real-time callbacks deliver the specific message subclass (`TextMessage` / `MediaMessage` / `CustomMessage`); `fetchPrevious()` resolves to `Promise`; `getMessageDetails()` resolves to `Promise`; unread-count methods resolve to a `Promise` of an ID→count object; all reject with `CometChat.CometChatException` | +| Listeners registered | `MessageListener` via `CometChat.addMessageListener(listenerID, ...)` / `CometChat.removeMessageListener(listenerID)` — callbacks shown: `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | As a sender you do not receive your own message in a real-time event (though other devices of the same logged-in user do). Always remove listeners on unmount to avoid memory leaks and duplicate handling. Advanced search (file name, mentions, MIME type) requires the `Conversation & Advanced Search` feature | +| Related | [Send a Message](/sdk/javascript/send-message) · [Delivery & Read Receipts](/sdk/javascript/delivery-read-receipts) · [All Real Time Listeners](/sdk/javascript/all-real-time-listeners) · [Retrieve Conversations](/sdk/javascript/retrieve-conversations) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`CustomMessage`](/sdk/reference/messages#custommessage) | + + + Receiving messages with CometChat has two parts: 1. Adding a [real-time listener](#real-time-messages) to receive messages while your app is running diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index b014834de..63374ed5f 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -3,6 +3,23 @@ title: "Retrieve Conversations" description: "Fetch recent CometChat conversations for chat lists, with support for one-on-one and group conversation filters." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `conversationsRequest.fetchNext()` (build via `ConversationsRequestBuilder`) · `CometChat.getConversation(conversationWith, conversationType)` · `CometChat.tagConversation(conversationWith, conversationType, tags)` · `CometChat.CometChatHelper.getConversationFromMessage(message)` | +| Request builder | `CometChat.ConversationsRequestBuilder` — configure with `.setLimit()` · `.setConversationType()` · `.setUserTags()` · `.setGroupTags()` · `.setTags()` · `.setSearchKeyword()` · `.setUnread()`; then `.build()` → `.fetchNext()` (call repeatedly to paginate) | +| Key classes | `CometChat.Conversation` (access peer via `getConversationWith()`, tags via `getTags()`) | +| Primary output | `Promise` from `fetchNext()`; `getConversation()` / `tagConversation()` resolve to a single `CometChat.Conversation`; all reject with `CometChat.CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | `setLimit()` default is 30, max is 50; `setSearchKeyword()` and `setUnread()` require the Conversation & Advanced Search add-on (Advanced/Custom plans); `setHideAgentic()` and `setOnlyAgentic()` are mutually exclusive | +| Related | [Delete a Conversation](/sdk/javascript/delete-conversation) · [Receive a Message](/sdk/javascript/receive-message) · [Typing Indicators](/sdk/javascript/typing-indicators) · [Delivery & Read Receipts](/sdk/javascript/delivery-read-receipts) | +| Full reference | [`Conversation`](/sdk/reference/entities#conversation) | + + + Conversations provide the last messages for every one-on-one and group conversation the logged-in user is a part of. This makes it easy for you to build a **Recent Chat** list. ## Retrieve List of Conversations diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 0c1d34d5f..87ab6a857 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -3,6 +3,22 @@ title: "Retrieve Group Members" description: "Fetch and paginate group members using the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `groupMembersRequest.fetchNext()` (build via `GroupMembersRequestBuilder`) | +| Request builder | `CometChat.GroupMembersRequestBuilder(GUID)` — GUID is passed to the constructor; configure with `.setLimit()` · `.setSearchKeyword()` · `.setScopes()` · `.setStatus()`; then `.build()` → `.fetchNext()` (call repeatedly to paginate) | +| Key classes | `CometChat.GroupMember` extends `CometChat.User`; access scope via `getScope()` (`"admin"` / `"moderator"` / `"participant"`); status via `CometChat.USER_STATUS.ONLINE` / `.OFFLINE` | +| Primary output | `Promise` — resolves to an array of members; rejects with `CometChat.CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview); a valid GUID must be supplied to the builder constructor | +| Related | [Retrieve Groups](/sdk/javascript/retrieve-groups) · [Add Members to a Group](/sdk/javascript/group-add-members) · [Kick & Ban Members](/sdk/javascript/group-kick-ban-members) · [Create a Group](/sdk/javascript/create-group) | +| Full reference | [`GroupMember`](/sdk/reference/entities#groupmember) · [`User`](/sdk/reference/entities#user) | + + + ## Retrieve the List of Group Members Use `GroupMembersRequestBuilder` to fetch members of a [Group](/sdk/reference/entities#group). The GUID must be specified in the constructor. diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index bc79702f6..e8f1017c9 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -3,6 +3,23 @@ title: "Retrieve Groups" description: "Fetch, search, filter, and paginate groups using the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `groupsRequest.fetchNext()` (build via `GroupsRequestBuilder`) · `CometChat.getGroup(guid)` · `CometChat.getOnlineGroupMemberCount(guids)` | +| Request builder | `CometChat.GroupsRequestBuilder` — configure with `.setLimit()` · `.setSearchKeyword()` · `.joinedOnly()` · `.setTags()` · `.withTags()`; then `.build()` → `.fetchNext()` (call repeatedly to paginate) | +| Key classes | `CometChat.Group` (access tags via `getTags()`) | +| Primary output | `Promise` from `fetchNext()`; `getGroup()` resolves to a single `CometChat.Group`; `getOnlineGroupMemberCount()` resolves to a `{ guid: count }` object; all reject with `CometChat.CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | The list returns only public and password-protected groups; private groups appear only when the logged-in user is a member | +| Related | [Create a Group](/sdk/javascript/create-group) · [Retrieve Group Members](/sdk/javascript/retrieve-group-members) · [Add Members to a Group](/sdk/javascript/group-add-members) · [Retrieve Conversations](/sdk/javascript/retrieve-conversations) | +| Full reference | [`Group`](/sdk/reference/entities#group) | + + + ## Retrieve List of Groups _In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?_ diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index e3c05c4fc..03c856596 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -3,6 +3,23 @@ title: "Retrieve Users" description: "Retrieve users, logged-in user details, and online counts with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `usersRequest.fetchNext()` (build via `UsersRequestBuilder`) · `CometChat.getLoggedinUser()` · `CometChat.getUser(uid)` · `CometChat.getOnlineUserCount()` | +| Request builder | `CometChat.UsersRequestBuilder` — configure with `.setLimit()` · `.setSearchKeyword()` · `.searchIn()` · `.setStatus()` · `.hideBlockedUsers()` · `.setRoles()` · `.friendsOnly()` · `.setTags()` · `.withTags()` · `.setUIDs()` · `.sortBy()` · `.sortByOrder()`; then `.build()` → `.fetchNext()` (call repeatedly to paginate) | +| Key classes | `CometChat.User` (access via `getUid()`, `getName()`, `getStatus()`, `getRole()`, `getTags()`); status via `CometChat.USER_STATUS.ONLINE` / `.OFFLINE` | +| Primary output | `Promise` from `fetchNext()`; `getLoggedinUser()` / `getUser()` resolve to a single `CometChat.User`; `getOnlineUserCount()` resolves to a `number`; all reject with `CometChat.CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | `setUIDs()` fetches a maximum of 25 users per request; `searchIn()` defaults to both `uid` and `name`; default sort order is `status → name → UID`, ascending | +| Related | [User Presence](/sdk/javascript/user-presence) · [Block Users](/sdk/javascript/block-users) · [User Management](/sdk/javascript/user-management) · [Retrieve Conversations](/sdk/javascript/retrieve-conversations) | +| Full reference | [`User`](/sdk/reference/entities#user) | + + + ## Retrieve Logged In User Details You can get the details of the logged-in user using the `getLoggedInUser()` method. This method can also be used to check if the user is logged in or not. If the method returns `Promise` with reject callback, it indicates that the user is not logged in and you need to log the user into CometChat SDK. diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index b644b02c0..14cc60cd4 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -3,6 +3,24 @@ title: "Send A Message" description: "Send text, media, custom, and interactive chat messages with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.sendMessage(textMessage)` · `CometChat.sendMediaMessage(mediaMessage)` · `CometChat.sendCustomMessage(customMessage)` | +| Message classes | `CometChat.TextMessage`, `CometChat.MediaMessage`, `CometChat.CustomMessage` (use `CometChat.Attachment` for hosted-URL media) | +| Primary output | `Promise` — resolves to the sent `TextMessage` / `MediaMessage` / `CustomMessage`; rejects with `CometChat.CometChatException` | +| Receiver targeting | `receiverType`: `CometChat.RECEIVER_TYPE.USER` (pass a UID) or `CometChat.RECEIVER_TYPE.GROUP` (pass a GUID) | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview) | +| Constraints | Card messages are **receive-only** (no `sendCardMessage()`). Media messages carry ≤ `file.count.max` attachments (default 10) or reject with `ERR_FILE_COUNT_EXCEEDED`; read the limit at runtime with `CometChat.getMaxAttachmentCount()` | +| Receive counterpart | Sent messages reach peers through `MessageListener` — see [Receive a Message](/sdk/javascript/receive-message) | +| Related | [Upload Files](/sdk/javascript/upload-files) · [Threaded Messages](/sdk/javascript/threaded-messages) · [Edit a Message](/sdk/javascript/edit-message) · [Delete a Message](/sdk/javascript/delete-message) | +| Full reference | [`TextMessage`](/sdk/reference/messages#textmessage) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`CustomMessage`](/sdk/reference/messages#custommessage) | + + + Using CometChat, you can send three types of messages: 1. [Text Message](/sdk/javascript/send-message#text-message) is the most common and standard message type. diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 1d6af168f..9025ac95b 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -3,6 +3,23 @@ title: "Threaded Messages" description: "Send, receive, and fetch threaded messages with the CometChat JavaScript SDK." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `textMessage.setParentMessageId(messageId)` · `CometChat.sendMessage(textMessage)` · `CometChat.addMessageListener(listenerID, new CometChat.MessageListener({...}))` · `message.getParentMessageId()` · `new CometChat.MessagesRequestBuilder().setParentMessageId(parentMessageId).setLimit(limit).build()` · `messagesRequest.fetchPrevious()` · `.hideReplies(true)` | +| Key classes | `CometChat.MessageListener` · `CometChat.MessagesRequestBuilder` · `CometChat.MessagesRequest` · `CometChat.TextMessage` · `CometChat.MediaMessage` · `CometChat.CustomMessage` · `CometChat.BaseMessage` | +| Primary output | `sendMessage()` resolves to the sent message (e.g. `TextMessage`); `fetchPrevious()` resolves to `Promise` (thread replies, or top-level messages when `hideReplies(true)` is set); real-time thread messages arrive on the `MessageListener`; all reject with `CometChat.CometChatException` | +| Listeners registered | `MessageListener` via `CometChat.addMessageListener(listenerID, ...)` / `CometChat.removeMessageListener(listenerID)` — callbacks: `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived`; filter to the active thread with `getParentMessageId()` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview); a parent message ID to thread under | +| Constraints | `fetchPrevious()` returns at most 100 messages per request. Use `hideReplies(true)` on the builder to exclude thread replies and return only top-level messages. Always remove listeners on unmount to avoid memory leaks and duplicate handling | +| Related | [Send a Message](/sdk/javascript/send-message) · [Receive a Message](/sdk/javascript/receive-message) · [Message Filtering](/sdk/javascript/message-filtering) · [Reactions](/sdk/javascript/reactions) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`CustomMessage`](/sdk/reference/messages#custommessage) | + + + Messages that are started from a particular message are called Threaded messages or simply threads. Each Thread is attached to a message which is the Parent message for that thread. ## Send Message in a Thread diff --git a/sdk/javascript/upload-files.mdx b/sdk/javascript/upload-files.mdx index 531bbd496..ce4153c54 100644 --- a/sdk/javascript/upload-files.mdx +++ b/sdk/javascript/upload-files.mdx @@ -4,6 +4,23 @@ sidebarTitle: "Upload Files" description: "Upload files directly to storage with per-file progress, remove, and retry through an UploadFileRequest — then send them as one or more media messages with multiple attachments." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-javascript` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-javascript";` | +| Key methods | `CometChat.createUploadFileRequest(receiverId, receiverType)` · `request.uploadAttachments([{ fileId, file }], listener)` · `request.uploadAttachment(fileId, file, listener)` · `request.getAttachments()` / `request.getAttachmentsByType(type)` · `request.removeAttachment(fileId)` · `request.retryAttachment(fileId)` · `request.clearAll()` · `CometChat.sendMediaMessage(mediaMessage)` · `CometChat.getMaxAttachmentCount()` | +| Key classes | `CometChat.UploadFileRequest` · `CometChat.UploadFileListener` · `CometChat.Attachment` · `CometChat.MediaMessage` · `CometChat.UploadResult` | +| Primary output | `createUploadFileRequest()` returns an `UploadFileRequest` (upload is decoupled from send). Progress and outcomes arrive on the `UploadFileListener` callbacks; each success yields a ready-to-send `Attachment` (with a hosted `url`). `sendMediaMessage()` resolves to `Promise` and rejects with `CometChat.CometChatException` | +| Listeners registered | `UploadFileListener` (per-call, or global via `request.addUploadListener(listener)` / `request.removeUploadListener()`) — callbacks: `onFileProgress(fileId, loaded, total, percent)`, `onFileUploaded(fileId, attachment)`, `onFileError(fileId, error)` (rejected, not retryable), `onFileFailure(fileId, error)` (failed, retryable), `onComplete(result)`. Not registered globally with a string id — it lives for the upload batch | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/javascript/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/javascript/authentication-overview); the request `receiverId` / `receiverType` must match the `MediaMessage` you eventually send | +| Constraints | `fileId` is caller-supplied and required (dedup: a repeated `fileId` is silently skipped). Per-file size limit `file.size.max` (default 100 MB) is enforced at upload → `ERR_FILE_SIZE_EXCEEDED` via `onFileError`; attachments-per-message limit `file.count.max` (default 10) is enforced by `sendMediaMessage()` → `ERR_FILE_COUNT_EXCEEDED`. Send from an explicit button, **not** from `onComplete` (which fires on every batch drain). Call `clearAll()` after a successful send | +| Related | [Send a Message](/sdk/javascript/send-message) · [Receive a Message](/sdk/javascript/receive-message) · [Threaded Messages](/sdk/javascript/threaded-messages) · [Error Codes](/sdk/javascript/error-codes) | +| Full reference | [`Attachment`](/sdk/reference/auxiliary#attachment) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + + `CometChat.createUploadFileRequest(receiverId, receiverType)` returns an **`UploadFileRequest`** — the entry point for uploading files **directly to storage** with **per-file progress, success, and failure**. Upload is **decoupled from sending**: each uploaded file yields an [`Attachment`](/sdk/reference/auxiliary#attachment) (carrying a hosted `url`), which you then attach to a [`MediaMessage`](/sdk/reference/messages#mediamessage) and send with [`sendMediaMessage()`](/sdk/javascript/send-message#media-message). A request object is scoped to **one destination** (`receiverId` / `receiverType`) and **one upload batch**. This is the recommended way to build a **multi-attachment composer**: create a request, upload a batch of files, show a progress bar per file, let the user remove or retry individual files, then send them as a single media message with multiple attachments (or split across several). diff --git a/sdk/react-native/additional-message-filtering.mdx b/sdk/react-native/additional-message-filtering.mdx index 74ce76e6e..17eb535b5 100644 --- a/sdk/react-native/additional-message-filtering.mdx +++ b/sdk/react-native/additional-message-filtering.mdx @@ -7,37 +7,19 @@ description: "Advanced filtering options for fetching messages using MessagesReq {/* TL;DR for Agents and Quick Reference */} -```javascript -let parentId = 100; - -// Filter by category and type -let mediaRequest = new CometChat.MessagesRequestBuilder() - .setUID("UID") - .setCategories(["message"]) - .setTypes(["image", "video", "audio", "file"]) - .setLimit(50) - .build(); - -// Unread messages only -let unreadRequest = new CometChat.MessagesRequestBuilder() - .setUID("UID") - .setUnread(true) - .setLimit(50) - .build(); - -// Threaded messages -let threadRequest = new CometChat.MessagesRequestBuilder() - .setUID("UID") - .setParentMessageId(parentId) - .setLimit(50) - .build(); - -// Fetch with pagination -mediaRequest.fetchPrevious().then(messages => { }); -mediaRequest.fetchNext().then(messages => { }); -``` +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Classes | `MessagesRequest`, `MessagesRequestBuilder`, `AttachmentType` | +| Key Methods | `fetchNext()`, `fetchPrevious()` — build the request via `MessagesRequestBuilder` | +| Request Builder | Scope with `.setUID()` **or** `.setGUID()`, then filter with `.setTypes()`, `.setCategories()`, `.setUnread()`, `.setUpdatedAfter()`, `.setParentMessageId()`, `.setSearchKeyword()`, `.setLimit()`, then `.build()` | +| Primary output | `Promise` — rejects with `CometChatException` | +| Prerequisites | SDK initialized via `CometChat.init()`, user logged in via `CometChat.login()` | +| Related | [Receive Messages](/sdk/react-native/receive-messages), [Threaded Messages](/sdk/react-native/threaded-messages), [Retrieve Conversations](/sdk/react-native/retrieve-conversations) | +| Constraints | Scope with `.setUID()` **or** `.setGUID()`, never both. The builder is passed to the request, not `.build()`'s result twice — rebuild for each new filter set. | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | -**Key methods:** `setUID()`, `setGUID()`, `setLimit()`, `setCategories()`, `setTypes()`, `setTags()`, `setUnread()`, `setParentMessageId()`, `setMessageId()`, `setTimestamp()`, `hideReplies()`, `hideDeletedMessages()` The `MessagesRequest` class fetches messages based on various parameters. It uses the Builder design pattern via `MessagesRequestBuilder`. diff --git a/sdk/react-native/ai-agents.mdx b/sdk/react-native/ai-agents.mdx index 32452827c..711ff359b 100644 --- a/sdk/react-native/ai-agents.mdx +++ b/sdk/react-native/ai-agents.mdx @@ -6,31 +6,19 @@ description: "Integrate AI Agents into your React Native app using the CometChat -| Feature | Description | +| Field | Value | | --- | --- | -| [AI Agents](#agent-run-lifecycle-and-message-flow) | Intelligent automated conversations with real-time streaming | -| [AI Moderation](/sdk/react-native/ai-moderation) | Automatic content moderation with `PENDING` → `APPROVED` / `DISAPPROVED` flow | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Classes | `AIAssistantMessage`, `AIToolResultMessage`, `AIToolArgumentMessage`, `AIAssistantBaseEvent`, `AIAssistantCardStartedEvent`, `AIAssistantCardReceivedEvent`, `AIAssistantCardEndedEvent`, `AIAssistantElement`, `MessageListener` | +| Key Methods | `addAIAssistantListener()`, `removeAIAssistantListener()`, `addMessageListener()`, `removeMessageListener()` | +| Listener Events | `onAIAssistantEventReceived` (streaming run events); `onAIAssistantMessageReceived`, `onAIToolResultReceived`, `onAIToolArgumentsReceived` (persisted messages) | +| Primary output | Live run events arrive on `onAIAssistantEventReceived` as `AIAssistantBaseEvent` subclasses; once the run completes the persisted messages arrive on the `MessageListener` | +| Prerequisites | SDK initialized via `CometChat.init()`, user logged in via `CometChat.login()`; an agent with the `@agentic` role configured in the [dashboard](https://app.cometchat.com/) | +| Related | [AI Moderation](/sdk/react-native/ai-moderation), [Receive Messages](/sdk/react-native/receive-messages) | +| Constraints | `AIAssistantCardEndedEvent` and `AIAssistantElement` ship only in newer SDK builds — they are absent from 4.0.21. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Full reference | [`AIAssistantMessage`](/sdk/reference/messages#aiassistantmessage) · [`AIToolResultMessage`](/sdk/reference/messages#aitoolresultmessage) · [`AIToolArgumentMessage`](/sdk/reference/messages#aitoolargumentmessage) · [`AIAssistantBaseEvent`](/sdk/reference/messages#aiassistantbaseevent) | -```javascript -// Listen for real-time AI Agent events (streaming) -CometChat.addAIAssistantListener("LISTENER_ID", { - onAIAssistantEventReceived: (event) => console.log("Event:", event) -}); - -// Listen for persisted agentic messages -CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ - onAIAssistantMessageReceived: (msg) => console.log("Assistant reply:", msg), - onAIToolResultReceived: (msg) => console.log("Tool result:", msg), - onAIToolArgumentsReceived: (msg) => console.log("Tool args:", msg) -})); - -// Cleanup -CometChat.removeAIAssistantListener("LISTENER_ID"); -CometChat.removeMessageListener("LISTENER_ID"); -``` - -**Prerequisites:** `CometChat.init()` + `CometChat.login()` completed, AI features enabled in [Dashboard](https://app.cometchat.com) -**Event flow:** Run Start → Tool Call(s) → Text Message Stream → Run Finished AI Agents enable intelligent, automated interactions within your application. They process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). diff --git a/sdk/react-native/ai-moderation.mdx b/sdk/react-native/ai-moderation.mdx index 7d1139da8..4bd78f344 100644 --- a/sdk/react-native/ai-moderation.mdx +++ b/sdk/react-native/ai-moderation.mdx @@ -6,6 +6,19 @@ description: "Automatically moderate chat messages using AI to detect and block +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addMessageListener()`, `removeMessageListener()`, `sendMessage()` | +| Key Classes | `BaseMessage`, `CometChatException`, `MediaMessage`, `MessageListener`, `TextMessage` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | Moderation is applied server-side; `sendMessage()` still resolves to the sent message, which then transitions `PENDING` → `APPROVED` / `DISAPPROVED` | +| Constraints | A disapproved message never reaches recipients — the sender's own promise still resolves. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Send a Message](/sdk/react-native/send-message) · [Receive Messages](/sdk/react-native/receive-messages) · [AI Agents](/sdk/react-native/ai-agents) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript let textMessage = new CometChat.TextMessage("UID", "Hello", CometChat.RECEIVER_TYPE.USER); @@ -26,6 +39,7 @@ CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({ **Supported types:** Text, Image, Video messages only **Statuses:** `PENDING` → `APPROVED` or `DISAPPROVED` + AI Moderation automatically reviews messages for inappropriate content in real-time. When a user sends a text, image, or video message, it's held in a `PENDING` state while the moderation service analyzes it, then marked as `APPROVED` or `DISAPPROVED` via the `onMessageModerated` event. diff --git a/sdk/react-native/authentication-overview.mdx b/sdk/react-native/authentication-overview.mdx index eaad222a0..1f13b943c 100644 --- a/sdk/react-native/authentication-overview.mdx +++ b/sdk/react-native/authentication-overview.mdx @@ -7,6 +7,18 @@ description: "Create users, log in with Auth Key or Auth Token, check login stat {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `createUser()`, `getLoggedinUser()`, `login()`, `logout()` | +| Key Classes | `CometChatException`, `User` | +| Primary output | `login()` → `Promise`; `getLoggedinUser()` → `Promise`; `logout()` → `Promise` | +| Constraints | Auth Key is **development only** — it can create and log in any user. Production must mint an Auth Token server-side. `login()` rejects if `init()` has not resolved. | +| Related | [Setup SDK](/sdk/react-native/setup-sdk) · [User Management](/sdk/react-native/user-management) · [Connection Status](/sdk/react-native/connection-status) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Check existing session const user = await CometChat.getLoggedinUser(); @@ -23,6 +35,7 @@ CometChat.logout().then(() => console.log("Logged out")); **Create users via:** [Dashboard](https://app.cometchat.com) (testing) | [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production) **Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` + After [initializing](/sdk/react-native/setup-sdk) the SDK, the next step is to authenticate your user. CometChat provides two login methods — Auth Key for quick development, and Auth Token for production — both accessed through the `login()` method. diff --git a/sdk/react-native/block-users.mdx b/sdk/react-native/block-users.mdx index 33a1bc088..087285cd9 100644 --- a/sdk/react-native/block-users.mdx +++ b/sdk/react-native/block-users.mdx @@ -6,6 +6,19 @@ description: "Block and unblock users, and retrieve the list of blocked users us +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `blockUsers()`, `unblockUsers()` | +| Key Classes | `BlockedUsersRequest`, `BlockedUsersRequestBuilder`, `CometChatException`, `User` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — a map of UID → `"success"` / failure reason; rejects with `CometChatException` | +| Constraints | Both methods take an **array** of UIDs, never a bare string. Blocking is one-directional: the blocked user is not told. | +| Related | [Retrieve Users](/sdk/react-native/retrieve-users) · [User Management](/sdk/react-native/user-management) · [User Presence](/sdk/react-native/user-presence) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Block users await CometChat.blockUsers(["UID1", "UID2"]); @@ -19,6 +32,7 @@ let blockedUsers = await request.fetchNext(); ``` **Directions:** `BLOCKED_BY_ME` | `HAS_BLOCKED_ME` | `BOTH` (default) + Blocking a user prevents all communication between them and the logged-in user — messages, calls, and presence updates are all suppressed. You can block and unblock users by UID, and fetch the blocked users list with filtering and pagination. diff --git a/sdk/react-native/connection-status.mdx b/sdk/react-native/connection-status.mdx index afb0ab66c..a8dadf681 100644 --- a/sdk/react-native/connection-status.mdx +++ b/sdk/react-native/connection-status.mdx @@ -5,6 +5,19 @@ description: "Monitor real-time WebSocket connection status and respond to conne +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addConnectionListener()`, `getConnectionStatus()`, `init()` | +| Key Classes | `ConnectionListener` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `getConnectionStatus()` returns a `string` **synchronously** (not a Promise); `addConnectionListener()` returns `void` | +| Constraints | `getConnectionStatus()` is synchronous — do not `await` it. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Setup SDK](/sdk/react-native/setup-sdk) · [Managing WebSockets Manually](/sdk/react-native/managing-web-sockets-connections-manually) · [Real-Time Listeners](/sdk/react-native/real-time-listeners) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Get current status: "connecting" | "connected" | "disconnected" const status = CometChat.getConnectionStatus(); @@ -19,6 +32,7 @@ CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener( // Cleanup CometChat.removeConnectionListener("LISTENER_ID"); ``` + The CometChat SDK maintains a WebSocket connection to CometChat servers for real-time events. You can check the current connection state and listen for changes — useful for showing connectivity indicators in your UI or queuing operations while offline. diff --git a/sdk/react-native/create-group.mdx b/sdk/react-native/create-group.mdx index 5b7c622d6..aa90b86ba 100644 --- a/sdk/react-native/create-group.mdx +++ b/sdk/react-native/create-group.mdx @@ -6,6 +6,19 @@ description: "Create public, private, or password-protected groups and optionall +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `createGroup()`, `createGroupWithMembers()` | +| Key Classes | `CometChatException`, `GROUP_MEMBER_SCOPE`, `GROUP_TYPE`, `Group`, `GroupMember` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `createGroup()` → `Promise`; `createGroupWithMembers()` → `Promise` (a per-member success/failure map) | +| Constraints | GUIDs are immutable once created. A `password` group requires a password at creation; `public` and `private` must not carry one. `GROUP_TYPE.PROTECTED` and `GROUP_TYPE.PASSWORD` are **aliases** — both resolve to `"password"`. | +| Related | [Join a Group](/sdk/react-native/join-group) · [Update a Group](/sdk/react-native/update-group) · [Add Members](/sdk/react-native/group-add-members) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`GroupMember`](/sdk/reference/entities#groupmember) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Create a group let group = new CometChat.Group("GUID", "Group Name", CometChat.GROUP_TYPE.PUBLIC, ""); @@ -18,6 +31,7 @@ let result = await CometChat.createGroupWithMembers(group, members, []); **Group types:** `PUBLIC` | `PASSWORD` | `PRIVATE` **Member scopes:** `ADMIN` | `MODERATOR` | `PARTICIPANT` + Create groups for multi-user conversations. You can create a group on its own with `createGroup()`, or create one and add members in a single call with `createGroupWithMembers()`. See the [Group Class](#group-class) reference at the bottom for all available fields. diff --git a/sdk/react-native/delete-conversation.mdx b/sdk/react-native/delete-conversation.mdx index d90665e09..b7f2c7f35 100644 --- a/sdk/react-native/delete-conversation.mdx +++ b/sdk/react-native/delete-conversation.mdx @@ -7,6 +7,19 @@ description: "Delete one-on-one or group conversations for the logged-in user wi {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `deleteConversation()` | +| Key Classes | `CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — the deleted conversation's identifier; rejects with `CometChatException` | +| Constraints | Deletion is **per-user**: the other participant keeps their copy. Deleting does not delete the underlying messages. | +| Related | [Retrieve Conversations](/sdk/react-native/retrieve-conversations) · [Delete a Message](/sdk/react-native/delete-message) | +| Full reference | [`Conversation`](/sdk/reference/entities#conversation) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Delete user conversation await CometChat.deleteConversation("UID", "user"); @@ -16,6 +29,7 @@ await CometChat.deleteConversation("GUID", "group"); ``` **Note:** Deletes only for the logged-in user. Use [REST API](https://api-explorer.cometchat.com/reference/resets-user-conversation) to delete for all participants. + diff --git a/sdk/react-native/delete-group.mdx b/sdk/react-native/delete-group.mdx index 5c63cf888..b29d074ab 100644 --- a/sdk/react-native/delete-group.mdx +++ b/sdk/react-native/delete-group.mdx @@ -6,12 +6,26 @@ description: "Delete a group permanently using the CometChat React Native SDK. O +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `deleteGroup()` | +| Key Classes | `CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — `true` on success; rejects with `CometChatException` | +| Constraints | Owner-only. Deletion is permanent and removes the group for every member. | +| Related | [Create a Group](/sdk/react-native/create-group) · [Leave a Group](/sdk/react-native/leave-group) · [Transfer Ownership](/sdk/react-native/transfer-group-ownership) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Delete a group (owner only) await CometChat.deleteGroup("GUID"); ``` **Requirement:** Logged-in user must be the owner of the group. + Permanently delete a group and all its messages. Only the group owner can perform this operation. diff --git a/sdk/react-native/delete-message.mdx b/sdk/react-native/delete-message.mdx index 36717d47c..feef1ab6d 100644 --- a/sdk/react-native/delete-message.mdx +++ b/sdk/react-native/delete-message.mdx @@ -7,6 +7,19 @@ description: "Delete CometChat messages in React Native apps by message ID and l {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addMessageListener()`, `deleteMessage()` | +| Key Classes | `BaseMessage`, `CometChatException`, `MessageListener` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — the message in its deleted state (a tombstone, not removal); rejects with `CometChatException` | +| Constraints | The message object survives with `getDeletedAt()` set — render a deleted-state bubble rather than dropping it from the list. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Edit a Message](/sdk/react-native/edit-message) · [Send a Message](/sdk/react-native/send-message) · [Receive Messages](/sdk/react-native/receive-messages) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript let messageId = "MESSAGE_ID"; @@ -23,6 +36,7 @@ CometChat.addMessageListener("ID", new CometChat.MessageListener({ **Who can delete:** Message sender, Group admin, Group moderator **Deleted fields:** `deletedAt` (timestamp), `deletedBy` (user who deleted) + diff --git a/sdk/react-native/delivery-read-receipts.mdx b/sdk/react-native/delivery-read-receipts.mdx index 3ba997cd9..f1d0f0452 100644 --- a/sdk/react-native/delivery-read-receipts.mdx +++ b/sdk/react-native/delivery-read-receipts.mdx @@ -6,31 +6,19 @@ description: "Mark messages as delivered, read, or unread and receive real-time -| Method | Description | +| Field | Value | | --- | --- | -| `markAsDelivered(message)` | Mark a message as delivered | -| `markAsRead(message)` | Mark a message as read | -| `markConversationAsDelivered(id, type)` | Mark entire conversation as delivered | -| `markConversationAsRead(id, type)` | Mark entire conversation as read | -| `markMessageAsUnread(message)` | Mark a message as unread | -| `getMessageReceipts(messageId)` | Get delivery/read receipts for a message | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Classes | `MessageReceipt`, `MessageListener`, `Conversation`, `CometChatException` | +| Key Methods | `markAsDelivered()`, `markAsRead()`, `markConversationAsDelivered()`, `markConversationAsRead()`, `markMessageAsUnread()`, `getMessageReceipts()`, `addMessageListener()`, `removeMessageListener()` | +| Listener Events | `onMessagesDelivered`, `onMessagesRead`, `onMessagesDeliveredToAll`, `onMessagesReadByAll` | +| Primary output | `markAsDelivered()` / `markAsRead()` are fire-and-forget — they resolve but return no receipt; `getMessageReceipts()` resolves to `MessageReceipt[]` | +| Prerequisites | SDK initialized via `CometChat.init()`, user logged in via `CometChat.login()` | +| Related | [Receive Messages](/sdk/react-native/receive-messages), [Typing Indicators](/sdk/react-native/typing-indicators), [Retrieve Conversations](/sdk/react-native/retrieve-conversations) | +| Constraints | `markAsDelivered()` / `markAsRead()` are typed `any` and are fire-and-forget — do not rely on a resolved value. `onMessagesDeliveredToAll` / `onMessagesReadByAll` need the **Enhanced Messaging Status** feature. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Full reference | [`MessageReceipt`](/sdk/reference/auxiliary#messagereceipt) · [`Conversation`](/sdk/reference/entities#conversation) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | -```javascript -// Mark as delivered/read (pass message object) -CometChat.markAsDelivered(message); -CometChat.markAsRead(message); - -// Mark entire conversation -CometChat.markConversationAsRead("UID", "user"); - -// Listen for receipt events -CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ - onMessagesDelivered: (receipt) => { }, - onMessagesRead: (receipt) => { }, - onMessagesDeliveredToAll: (receipt) => { }, // Groups only - onMessagesReadByAll: (receipt) => { } // Groups only -})); -``` Delivery and read receipts track whether messages have been delivered to and read by recipients. diff --git a/sdk/react-native/edit-message.mdx b/sdk/react-native/edit-message.mdx index d1f08e431..ad53d45fe 100644 --- a/sdk/react-native/edit-message.mdx +++ b/sdk/react-native/edit-message.mdx @@ -7,6 +7,19 @@ description: "Edit CometChat text and custom messages in React Native apps by me {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addMessageListener()`, `editMessage()`, `removeMessageListener()` | +| Key Classes | `BaseMessage`, `CometChatException`, `MessageListener`, `TextMessage` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — the edited message; rejects with `CometChatException` | +| Constraints | Sender-only. The edited message carries `getEditedAt()`; peers are notified via `onMessageEdited`. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Delete a Message](/sdk/react-native/delete-message) · [Send a Message](/sdk/react-native/send-message) · [Receive Messages](/sdk/react-native/receive-messages) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript let receiverID = "UID"; let receiverType = CometChat.RECEIVER_TYPE.USER; @@ -22,6 +35,7 @@ CometChat.addMessageListener("edits", new CometChat.MessageListener({ onMessageEdited: (message) => console.log("Edited:", message) })); ``` + Editing a message is straightforward. Receiving edit events has two parts: diff --git a/sdk/react-native/flag-message.mdx b/sdk/react-native/flag-message.mdx index f84498e88..a249be77e 100644 --- a/sdk/react-native/flag-message.mdx +++ b/sdk/react-native/flag-message.mdx @@ -7,6 +7,19 @@ description: "Get flag reasons and flag inappropriate CometChat messages in Reac {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `flagMessage()`, `getFlagReasons()` | +| Key Classes | `CometChatException`, `FlagMessageResponse`, `FlagReason` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `flagMessage()` → `Promise`; `getFlagReasons()` → `Promise` | +| Constraints | Fetch reasons with `getFlagReasons()` first — reason IDs are dashboard-configured, not hard-coded constants. | +| Related | [Delete a Message](/sdk/react-native/delete-message) · [AI Moderation](/sdk/react-native/ai-moderation) · [Receive Messages](/sdk/react-native/receive-messages) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Get available flag reasons const reasons = await CometChat.getFlagReasons(); @@ -17,6 +30,7 @@ await CometChat.flagMessage("MESSAGE_ID", { remark: "Promotional content" }); ``` + ## Overview diff --git a/sdk/react-native/group-add-members.mdx b/sdk/react-native/group-add-members.mdx index 80270208f..cb98c3231 100644 --- a/sdk/react-native/group-add-members.mdx +++ b/sdk/react-native/group-add-members.mdx @@ -6,6 +6,19 @@ description: "Learn how to add members to a group, receive real-time member adde +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addGroupListener()`, `addMembersToGroup()`, `removeGroupListener()` | +| Key Classes | `Action`, `CometChatException`, `GROUP_MEMBER_SCOPE`, `Group`, `GroupListener`, `GroupMember` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — a per-UID success/failure map; rejects with `CometChatException` | +| Constraints | Takes an array of `CometChat.GroupMember` objects, not bare UIDs. Partial success is normal — inspect the returned map per UID. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Create a Group](/sdk/react-native/create-group) · [Kick & Ban Members](/sdk/react-native/group-kick-ban-members) · [Retrieve Group Members](/sdk/react-native/retrieve-group-members) | +| Full reference | [`GroupMember`](/sdk/reference/entities#groupmember) · [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Add members to a group const members = [ @@ -18,6 +31,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ onMemberAddedToGroup: (message, userAdded, userAddedBy, userAddedIn) => { } })); ``` + Add users to a group programmatically. Only admins and moderators can add members. The added users receive a notification and are immediately part of the group. diff --git a/sdk/react-native/group-change-member-scope.mdx b/sdk/react-native/group-change-member-scope.mdx index 63c26c231..8dc02b29c 100644 --- a/sdk/react-native/group-change-member-scope.mdx +++ b/sdk/react-native/group-change-member-scope.mdx @@ -6,6 +6,19 @@ description: "Learn how to change group member scope (admin, moderator, particip +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addGroupListener()`, `removeGroupListener()`, `updateGroupMemberScope()` | +| Key Classes | `Action`, `CometChatException`, `GROUP_MEMBER_SCOPE`, `Group`, `GroupListener`, `User` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — `true` on success; rejects with `CometChatException` | +| Constraints | Scopes are `admin` / `moderator` / `participant`. Only an owner or admin may promote; the owner's scope cannot be changed here — use ownership transfer. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Transfer Ownership](/sdk/react-native/transfer-group-ownership) · [Retrieve Group Members](/sdk/react-native/retrieve-group-members) · [Kick & Ban Members](/sdk/react-native/group-kick-ban-members) | +| Full reference | [`GroupMember`](/sdk/reference/entities#groupmember) · [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Change member scope to admin await CometChat.updateGroupMemberScope("GUID", "UID", CometChat.GROUP_MEMBER_SCOPE.ADMIN); @@ -15,6 +28,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => { } })); ``` + Promote or demote group members between admin, moderator, and participant scopes. Only admins can change member scopes, and only the group owner can change admin scopes. diff --git a/sdk/react-native/group-kick-ban-members.mdx b/sdk/react-native/group-kick-ban-members.mdx index ca32fb722..552810327 100644 --- a/sdk/react-native/group-kick-ban-members.mdx +++ b/sdk/react-native/group-kick-ban-members.mdx @@ -6,6 +6,19 @@ description: "Learn how to kick, ban, and unban group members, fetch banned memb +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addGroupListener()`, `banGroupMember()`, `kickGroupMember()`, `removeGroupListener()`, `unbanGroupMember()` | +| Key Classes | `Action`, `BannedMembersRequest`, `BannedMembersRequestBuilder`, `CometChatException`, `Group`, `GroupListener` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — `true` on success; rejects with `CometChatException` | +| Constraints | Kick removes but allows rejoining; ban blocks rejoining until `unbanGroupMember()`. Banned members need `BannedMembersRequest` to enumerate, not `GroupMembersRequest`. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Add Members](/sdk/react-native/group-add-members) · [Change Member Scope](/sdk/react-native/group-change-member-scope) · [Retrieve Group Members](/sdk/react-native/retrieve-group-members) | +| Full reference | [`GroupMember`](/sdk/reference/entities#groupmember) · [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Kick a member await CometChat.kickGroupMember("GUID", "UID"); @@ -20,6 +33,7 @@ await CometChat.unbanGroupMember("GUID", "UID"); const request = new CometChat.BannedMembersRequestBuilder("GUID").setLimit(30).build(); const bannedMembers = await request.fetchNext(); ``` + Remove members from a group by kicking or banning them. Kicked users can rejoin; banned users cannot until they're unbanned. Only admins and moderators can perform these actions. diff --git a/sdk/react-native/groups-overview.mdx b/sdk/react-native/groups-overview.mdx index 7054f36b9..58230b4da 100644 --- a/sdk/react-native/groups-overview.mdx +++ b/sdk/react-native/groups-overview.mdx @@ -8,6 +8,7 @@ description: "Overview of group management in the CometChat React Native SDK inc | Field | Value | | --- | --- | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | | Package | `@cometchat/chat-sdk-react-native` | | Key Classes | `CometChat.Group` | | Group Types | `PUBLIC`, `PRIVATE`, `PASSWORD` | @@ -15,6 +16,9 @@ description: "Overview of group management in the CometChat React Native SDK inc | Key Methods | `createGroup()`, `joinGroup()`, `leaveGroup()`, `deleteGroup()` | | Prerequisites | SDK initialized, user logged in | | Related | [Create Group](/sdk/react-native/create-group), [Join Group](/sdk/react-native/join-group), [Retrieve Groups](/sdk/react-native/retrieve-groups) | +| Primary output | `createGroup()` / `joinGroup()` → `Promise`; `leaveGroup()` / `deleteGroup()` → `Promise` | +| Constraints | Three group types on the wire — `public`, `private`, `password` — exposed as four constants: `GROUP_TYPE.PROTECTED` and `GROUP_TYPE.PASSWORD` both resolve to `"password"`. Only that type accepts a password argument. GUIDs are immutable. | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`GroupMember`](/sdk/reference/entities#groupmember) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | diff --git a/sdk/react-native/join-group.mdx b/sdk/react-native/join-group.mdx index 47faf1f66..c7cc3b3ca 100644 --- a/sdk/react-native/join-group.mdx +++ b/sdk/react-native/join-group.mdx @@ -6,6 +6,19 @@ description: "Learn how to join public, password-protected, and private groups, +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addGroupListener()`, `joinGroup()`, `removeGroupListener()` | +| Key Classes | `Action`, `CometChatException`, `GROUP_TYPE`, `Group`, `GroupListener`, `User` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — the joined group; rejects with `CometChatException` | +| Constraints | `public` groups need no password; `password` groups reject without the correct one; `private` groups cannot be joined this way — a member must add you. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Create a Group](/sdk/react-native/create-group) · [Leave a Group](/sdk/react-native/leave-group) · [Retrieve Groups](/sdk/react-native/retrieve-groups) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`GroupMember`](/sdk/reference/entities#groupmember) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Join a public group await CometChat.joinGroup("GUID", CometChat.GROUP_TYPE.PUBLIC, ""); @@ -18,6 +31,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ onGroupMemberJoined: (message, joinedUser, joinedGroup) => { } })); ``` + Join a group to start sending and receiving messages in it. Public groups can be joined freely, password groups require the correct password, and private groups require an admin to add you (no direct join). diff --git a/sdk/react-native/leave-group.mdx b/sdk/react-native/leave-group.mdx index 2d8902d4a..c006708ea 100644 --- a/sdk/react-native/leave-group.mdx +++ b/sdk/react-native/leave-group.mdx @@ -6,6 +6,19 @@ description: "Learn how to leave a group and receive real-time events when membe +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addGroupListener()`, `leaveGroup()`, `removeGroupListener()` | +| Key Classes | `Action`, `CometChatException`, `Group`, `GroupListener`, `User` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — `true` on success; rejects with `CometChatException` | +| Constraints | The owner cannot leave without transferring ownership first. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Join a Group](/sdk/react-native/join-group) · [Transfer Ownership](/sdk/react-native/transfer-group-ownership) · [Delete a Group](/sdk/react-native/delete-group) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Leave a group await CometChat.leaveGroup("GUID"); @@ -15,6 +28,7 @@ CometChat.addGroupListener("listener", new CometChat.GroupListener({ onGroupMemberLeft: (message, leavingUser, group) => { } })); ``` + Leave a group to stop receiving messages and updates from it. Once you leave, you'll need to rejoin to participate again. diff --git a/sdk/react-native/llms-react-native-v4.mdx b/sdk/react-native/llms-react-native-v4.mdx new file mode 100644 index 000000000..cb7a843d8 --- /dev/null +++ b/sdk/react-native/llms-react-native-v4.mdx @@ -0,0 +1,121 @@ +--- +title: "React Native Chat SDK v4 — LLM docs index" +description: "Machine-readable, React-Native-SDK-v4-scoped index of every SDK page as a clean .md twin. Built for AI coding agents; kept out of the human sidebar." +--- + +{/* + SCOPED LLM INDEX for the React Native Chat SDK v4. + - UNLISTED, NOT hidden: intentionally omitted from docs.json navigation so it never shows in + the human sidebar — but it IS built, served as a clean .md twin, and INDEXED for search + + AI assistants (so AI tools, and this pack's skill via its docs-map, can discover and read it). + - We deliberately do NOT use `hidden: true`/`noindex` here: in Mintlify `hidden` auto-applies + noindex, which would drop this page from search AND the auto global llms.txt / AI context. + We want it discoverable, so it stays indexable. + - Fetch this file's own .md twin as a lightweight, RN-SDK-only routing index instead of the + site-wide /docs/llms.txt (which spans every product and is far larger). +*/} + +# React Native Chat SDK v4 — LLM docs index (Latest) + +> Low-level (headless) React Native chat + calling client — no UI. Package +> `@cometchat/chat-sdk-react-native@4`. This page is a **React-Native-SDK-v4-only** routing index +> for AI agents — a scoped alternative to the site-wide `/docs/llms.txt`. + +## How to use this index +Each link points to the docs page; **append `.md`** to its URL to fetch the clean Markdown twin +(verbatim code + method signatures, parameters, and listener contracts). Pick the page for the +intent, then read the API there. +- Convention: any docs page URL + `.md` → raw Markdown. +- Fallback: if a `.md` twin 404s, fetch the same URL **without** `.md` (HTML). Never read a + package `.d.ts` and never answer APIs from memory. + +## Platform rules — headless, and React Native +This is the **SDK**, not the UI Kit: it ships no components. You own every view. Also: +- **`@react-native-async-storage/async-storage` is required** — the SDK persists session state + through it and ships it as a direct dependency, so RN autolinking needs it present and + pod-installed. On Android, async-storage v3 also needs the `local_repo` Maven entry in + `android/build.gradle` or the build fails. +- **No DOM.** There is no `window`/`document`/`localStorage`; render with React Native + primitives and drive them from the listener callbacks below. +- **Listeners must be removed on unmount.** Every `add*Listener(id, …)` needs the matching + `remove*Listener(id)` — leaked listeners are the top source of duplicate-message bugs. +- Building UI from scratch is a lot of work. If the goal is "add chat", prefer the + [React Native UI Kit](/ui-kit/react-native/overview) and drop to this SDK only for custom UI + or headless/background logic. + +## Hot path — usually no fetch needed +For a plain integration the install, `init → login`, and the core `sendMessage` / +`receive-message` listener flow are stable; a well-built agent skill bakes them. Fetch below only +for exhaustive parameters, long-tail methods, group/user management, calling, or edge-case +listeners. +- Setup: [Setup](/sdk/react-native/setup-sdk) +- Auth/lifecycle: [Authentication](/sdk/react-native/authentication-overview) +- Core send/receive: [Send Messages](/sdk/react-native/send-message) · [Receive Messages](/sdk/react-native/receive-messages) · [All Real Time Listeners](/sdk/react-native/real-time-listeners) + +## Getting started / integration +- [Overview](/sdk/react-native/overview) +- [Setup](/sdk/react-native/setup-sdk) +- [Authentication](/sdk/react-native/authentication-overview) +- [Key Concepts](/sdk/react-native/key-concepts) + +## Messaging +- [Send Messages](/sdk/react-native/send-message) +- [Upload Files & Send Attachments](/sdk/react-native/upload-files) +- [Receive Messages](/sdk/react-native/receive-messages) +- [Message Filtering](/sdk/react-native/additional-message-filtering) +- [Retrieve Conversations](/sdk/react-native/retrieve-conversations) +- [Threaded Messages](/sdk/react-native/threaded-messages) +- [Edit Message](/sdk/react-native/edit-message) +- [Delete Message](/sdk/react-native/delete-message) +- [Flag Message](/sdk/react-native/flag-message) +- [Delete Conversation](/sdk/react-native/delete-conversation) +- [Typing Indicators](/sdk/react-native/typing-indicators) +- [Transient Messages](/sdk/react-native/transient-messages) +- [Delivery & Read Receipts](/sdk/react-native/delivery-read-receipts) +- [Mentions](/sdk/react-native/mentions) +- [Reactions](/sdk/react-native/reactions) + +## Calling +- [Calling — Overview](/sdk/react-native/calling-overview) + +## Users +- [Users — Overview](/sdk/react-native/users-overview) +- [Retrieve Users](/sdk/react-native/retrieve-users) +- [User Management](/sdk/react-native/user-management) +- [Block Users](/sdk/react-native/block-users) +- [User Presence](/sdk/react-native/user-presence) + +## Groups +- [Groups — Overview](/sdk/react-native/groups-overview) +- [Retrieve Groups](/sdk/react-native/retrieve-groups) +- [Create A Group](/sdk/react-native/create-group) +- [Update A Group](/sdk/react-native/update-group) +- [Join A Group](/sdk/react-native/join-group) +- [Leave A Group](/sdk/react-native/leave-group) +- [Delete A Group](/sdk/react-native/delete-group) +- [Retrieve Group Members](/sdk/react-native/retrieve-group-members) +- [Add Members To A Group](/sdk/react-native/group-add-members) +- [Ban / Kick Members](/sdk/react-native/group-kick-ban-members) +- [Change Member Scope](/sdk/react-native/group-change-member-scope) +- [Transfer Group Ownership](/sdk/react-native/transfer-group-ownership) + +## AI, campaigns & push +- [AI Moderation](/sdk/react-native/ai-moderation) +- [AI Agents](/sdk/react-native/ai-agents) +- [Campaigns](/sdk/react-native/campaigns) +- [Push Notification Content Customization](/sdk/react-native/push-notification-html-stripping) + +## Resources +- [Message Structure and Hierarchy](/sdk/react-native/message-structure-and-hierarchy) +- [All Real Time Listeners](/sdk/react-native/real-time-listeners) +- [Rate Limits](/sdk/react-native/rate-limits) +- [Connection Status](/sdk/react-native/connection-status) +- [Managing Web Sockets Connections Manually](/sdk/react-native/managing-web-sockets-connections-manually) + +## Migration & overviews +- [Upgrading From V3](/sdk/react-native/upgrading-from-v3) +- [Extensions — Overview](/sdk/react-native/extensions-overview) +- [AI User Copilot — Overview](/sdk/react-native/ai-user-copilot-overview) +- [Bots — Overview](/sdk/react-native/ai-chatbots-overview) +- [Webhooks — Overview](/sdk/react-native/webhooks-overview) +- [Changelog](/sdk/react-native/changelog) diff --git a/sdk/react-native/managing-web-sockets-connections-manually.mdx b/sdk/react-native/managing-web-sockets-connections-manually.mdx index e2f642408..2db6108f0 100644 --- a/sdk/react-native/managing-web-sockets-connections-manually.mdx +++ b/sdk/react-native/managing-web-sockets-connections-manually.mdx @@ -5,6 +5,19 @@ description: "Learn how to manage WebSocket connections in the CometChat React N +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `connect()`, `disconnect()`, `getLoggedinUser()`, `init()`, `login()`, `ping()` | +| Key Classes | `AppSettings`, `AppSettingsBuilder`, `CometChatException` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `connect()`, `disconnect()` and `ping()` all return **`void`** — they are fire-and-forget, not awaitable | +| Constraints | Manual mode requires `autoEstablishSocketConnection(false)` at `init()`. Calling `connect()` before `login()` resolves has no effect. | +| Related | [Setup SDK](/sdk/react-native/setup-sdk) · [Connection Status](/sdk/react-native/connection-status) · [Authentication](/sdk/react-native/authentication-overview) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Disable auto WebSocket connection during init const appSettings = new CometChat.AppSettingsBuilder() @@ -18,6 +31,7 @@ CometChat.connect(); CometChat.disconnect(); CometChat.ping(); // Keep alive in background (call within 30s) ``` + By default, the SDK automatically establishes and manages the WebSocket connection — it connects on login, reconnects on `init()` when a session exists, and handles reconnection on network drops. This page covers how to disable that and manage the connection yourself. diff --git a/sdk/react-native/mentions.mdx b/sdk/react-native/mentions.mdx index d79b7c4a0..63af1cad6 100644 --- a/sdk/react-native/mentions.mdx +++ b/sdk/react-native/mentions.mdx @@ -6,6 +6,19 @@ description: "Send messages with user mentions, retrieve mentioned users, and fi +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `sendMessage()` | +| Key Classes | `BaseMessage`, `CometChatException`, `MessagesRequest`, `MessagesRequestBuilder`, `TextMessage`, `User` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — the sent message carrying its mentions metadata | +| Constraints | Mentions ride on the message's metadata; the recipient list is resolved server-side. Mention rendering is the UI Kit's job, not the SDK's. | +| Related | [Send a Message](/sdk/react-native/send-message) · [Receive Messages](/sdk/react-native/receive-messages) · [Threaded Messages](/sdk/react-native/threaded-messages) | +| Full reference | [`TextMessage`](/sdk/reference/messages#textmessage) · [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript let message = {}; // obtained from MessageListener or fetchPrevious/fetchNext @@ -21,6 +34,7 @@ const request = new CometChat.MessagesRequestBuilder() .setUID("UID").setLimit(30).mentionsWithTagInfo(true).build(); const messages = await request.fetchPrevious(); ``` + Mentions in messages enable users to refer to specific individual within a conversation. This is done by using the `<@uid:UID>` format, where `UID` represents the user's unique identification. diff --git a/sdk/react-native/push-notification-html-stripping.mdx b/sdk/react-native/push-notification-html-stripping.mdx index 8e8ccdc6a..d08f3dde9 100644 --- a/sdk/react-native/push-notification-html-stripping.mdx +++ b/sdk/react-native/push-notification-html-stripping.mdx @@ -7,11 +7,17 @@ description: "Customize CometChat React Native push notification content by stri | Field | Value | | --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | | Platform | Android (FCM) + iOS (APNs) | | Key Concepts | HTML tag stripping, Notification Service Extension, `stripHtmlTags()` | | Android Approach | Intercept in `displayLocalNotification()` via `messaging().onMessage()` / `setBackgroundMessageHandler()` | | iOS Approach | Native `UNNotificationServiceExtension` intercepts APNs payloads before display | | Prerequisites | Push notifications configured, `@notifee/react-native` (Android), Xcode Notification Service Extension (iOS) | +| Primary output | A helper concern — no SDK call; affects the notification payload text only | +| Constraints | Applies to the push payload, not to the message stored by the SDK — `getText()` still returns the original. | +| Related | [Send a Message](/sdk/react-native/send-message) · [Receive Messages](/sdk/react-native/receive-messages) | +| Full reference | [`TextMessage`](/sdk/reference/messages#textmessage) · [`BaseMessage`](/sdk/reference/messages#basemessage) | diff --git a/sdk/react-native/reactions.mdx b/sdk/react-native/reactions.mdx index 9e321898e..c4d9242c9 100644 --- a/sdk/react-native/reactions.mdx +++ b/sdk/react-native/reactions.mdx @@ -6,6 +6,19 @@ description: "Add, remove, and fetch message reactions in real-time using the Co +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addMessageListener()`, `addReaction()`, `removeMessageListener()`, `removeReaction()` | +| Key Classes | `BaseMessage`, `CometChatException`, `CometChatHelper`, `MessageListener`, `REACTION_ACTION`, `ReactionCount` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `addReaction()` / `removeReaction()` → `Promise` — the message with its updated reaction set | +| Constraints | Reactions resolve to the **message**, not a reaction object. Enumerate with `ReactionsRequest` (`fetchNext()` → `Promise`). Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Send a Message](/sdk/react-native/send-message) · [Receive Messages](/sdk/react-native/receive-messages) · [Real-Time Listeners](/sdk/react-native/real-time-listeners) | +| Full reference | [`Reaction`](/sdk/reference/auxiliary#reaction) · [`ReactionCount`](/sdk/reference/auxiliary#reactioncount) · [`ReactionEvent`](/sdk/reference/auxiliary#reactionevent) · [`BaseMessage`](/sdk/reference/messages#basemessage) | + + ```javascript let messageId = "MESSAGE_ID"; @@ -26,6 +39,7 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ onMessageReactionRemoved: (reaction) => {} })); ``` + Reactions let users respond to messages with emoji. You can add or remove reactions, fetch all reactions on a message, listen for reaction events in real time, and update your UI when reactions change. diff --git a/sdk/react-native/real-time-listeners.mdx b/sdk/react-native/real-time-listeners.mdx index 1a8a385c1..fd5d9f569 100644 --- a/sdk/react-native/real-time-listeners.mdx +++ b/sdk/react-native/real-time-listeners.mdx @@ -5,6 +5,19 @@ description: "Complete reference for all CometChat real-time listeners in the Re +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addCallListener()`, `addGroupListener()`, `addMessageListener()`, `addUserListener()`, `removeCallListener()`, `removeGroupListener()`, `removeMessageListener()`, `removeUserListener()` | +| Key Classes | `Action`, `BaseMessage`, `Call`, `CallListener`, `CardMessage`, `CustomMessage` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | Every `add*Listener()` / `remove*Listener()` returns **`void`** — events arrive on the callbacks you register, never as a return value | +| Constraints | Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. Listener IDs are global — reusing one silently replaces the earlier listener. | +| Related | [Receive Messages](/sdk/react-native/receive-messages) · [Connection Status](/sdk/react-native/connection-status) · [User Presence](/sdk/react-native/user-presence) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`User`](/sdk/reference/entities#user) · [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // User Listener — online/offline presence CometChat.addUserListener("ID", new CometChat.UserListener({ @@ -38,6 +51,7 @@ CometChat.removeMessageListener("ID"); CometChat.removeGroupListener("ID"); CometChat.removeCallListener("ID"); ``` + Real-time listeners let you receive live events — messages, presence changes, group updates, and call signals — as they happen. The pattern is the same for all four listener types: diff --git a/sdk/react-native/receive-messages.mdx b/sdk/react-native/receive-messages.mdx index 13328bc50..f8078cda9 100644 --- a/sdk/react-native/receive-messages.mdx +++ b/sdk/react-native/receive-messages.mdx @@ -8,10 +8,16 @@ description: "Receive real-time messages, fetch unread messages, retrieve messag | Field | Value | | --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | | Key Classes | `CometChat.MessageListener`, `CometChat.MessagesRequestBuilder` | -| Key Methods | `addMessageListener()`, `fetchPrevious()`, `fetchNext()`, `getUnreadMessageCount()` | +| Key Methods | `addMessageListener()`, `fetchPrevious()`, `fetchNext()`, `getUnreadMessageCount()`, `getLastDeliveredMessageId()`, `getMessageDetails()`, `getUnreadMessageCountForAllGroups()`, `getUnreadMessageCountForAllUsers()`, `getUnreadMessageCountForGroup()`, `getUnreadMessageCountForUser()`, `removeMessageListener()` | | Listener Events | `onTextMessageReceived`, `onMediaMessageReceived`, `onCustomMessageReceived` | | Prerequisites | SDK initialized, user logged in | +| Primary output | `fetchNext()` / `fetchPrevious()` → `Promise`; listeners return `void` and deliver via callbacks | +| Constraints | `fetchPrevious()` walks backwards through history; `fetchNext()` walks forward. Mixing them on one request object interleaves pages confusingly. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Send a Message](/sdk/react-native/send-message) · [Message Filtering](/sdk/react-native/additional-message-filtering) · [Delivery & Read Receipts](/sdk/react-native/delivery-read-receipts) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | diff --git a/sdk/react-native/retrieve-conversations.mdx b/sdk/react-native/retrieve-conversations.mdx index 5a198da04..f5af80c52 100644 --- a/sdk/react-native/retrieve-conversations.mdx +++ b/sdk/react-native/retrieve-conversations.mdx @@ -7,6 +7,19 @@ description: "Fetch, filter, tag, and search CometChat conversations in React Na {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `getConversation()`, `tagConversation()` | +| Key Classes | `CometChatException`, `CometChatHelper`, `Conversation`, `ConversationsRequest`, `ConversationsRequestBuilder`, `CustomMessage` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `getConversation()` / `tagConversation()` → `Promise`; `ConversationsRequest.fetchNext()` → `Promise` | +| Constraints | Pass the **builder** to the request, not `.build()`'s result twice. A conversation exists only after the first message. | +| Related | [Receive Messages](/sdk/react-native/receive-messages) · [Delete a Conversation](/sdk/react-native/delete-conversation) · [Delivery & Read Receipts](/sdk/react-native/delivery-read-receipts) | +| Full reference | [`Conversation`](/sdk/reference/entities#conversation) · [`BaseMessage`](/sdk/reference/messages#basemessage) · [`User`](/sdk/reference/entities#user) · [`Group`](/sdk/reference/entities#group) | + + ```javascript // Fetch conversations list const request = new CometChat.ConversationsRequestBuilder() @@ -23,6 +36,7 @@ await CometChat.tagConversation("UID", "user", ["archived"]); let message = {}; // obtained from MessageListener or fetchPrevious/fetchNext const conv = await CometChat.CometChatHelper.getConversationFromMessage(message); ``` + Conversations provide the last message for every one-on-one and group conversation the logged-in user is part of. Each [`Conversation`](/sdk/reference/entities#conversation) object includes the other participant (user or group), the last message, unread counts, and optional tags. Use this to build a Recent Chats list. diff --git a/sdk/react-native/retrieve-group-members.mdx b/sdk/react-native/retrieve-group-members.mdx index 8a017ebc2..8970f4824 100644 --- a/sdk/react-native/retrieve-group-members.mdx +++ b/sdk/react-native/retrieve-group-members.mdx @@ -6,20 +6,19 @@ description: "Fetch and filter group members by scope, status, and search keywor -```javascript -// Fetch group members -const request = new CometChat.GroupMembersRequestBuilder("GUID") - .setLimit(30).build(); -const members = await request.fetchNext(); - -// Filter by scope -const scopeRequest = new CometChat.GroupMembersRequestBuilder("GUID") - .setLimit(30).setScopes(["admin", "moderator"]).build(); - -// Search members -const searchRequest = new CometChat.GroupMembersRequestBuilder("GUID") - .setLimit(30).setSearchKeyword("john").build(); -``` +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Classes | `GroupMember` (extends `User`), `GroupMembersRequest`, `GroupMembersRequestBuilder`, `CometChatException` | +| Key Methods | `fetchNext()`, `fetchPrevious()` — build the request via `GroupMembersRequestBuilder` | +| Request Builder | `new CometChat.GroupMembersRequestBuilder(GUID)` — GUID goes to the constructor; chain `.setLimit()`, `.setSearchKeyword()`, `.setScopes()`, `.setStatus()`, then `.build()` | +| Primary output | `Promise` — rejects with `CometChatException`. Read a member's role with `getScope()` (`admin` / `moderator` / `participant`) | +| Prerequisites | SDK initialized via `CometChat.init()`, user logged in via `CometChat.login()`; a valid GUID for a group the logged-in user is a member of | +| Related | [Retrieve Groups](/sdk/react-native/retrieve-groups), [Add Members](/sdk/react-native/group-add-members), [Kick & Ban Members](/sdk/react-native/group-kick-ban-members) | +| Constraints | Pass the GUID to the **builder's constructor**, not to `fetchNext()`. Banned members do not appear here — use `BannedMembersRequest`. | +| Full reference | [`GroupMember`](/sdk/reference/entities#groupmember) · [`User`](/sdk/reference/entities#user) · [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + Fetch the members of a group with filtering by scope, online status, and search keyword. Results are returned as [`GroupMember`](/sdk/reference/entities#groupmember) objects, which extend [`User`](/sdk/reference/entities#user) with group-specific fields like scope. diff --git a/sdk/react-native/retrieve-groups.mdx b/sdk/react-native/retrieve-groups.mdx index 7e9d4be48..81e310ef9 100644 --- a/sdk/react-native/retrieve-groups.mdx +++ b/sdk/react-native/retrieve-groups.mdx @@ -7,6 +7,19 @@ description: "Fetch, filter, and search groups using the CometChat React Native {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `getGroup()`, `getOnlineGroupMemberCount()` | +| Key Classes | `CometChatException`, `Group`, `GroupsRequest`, `GroupsRequestBuilder` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `getGroup()` → `Promise`; `GroupsRequest.fetchNext()` → `Promise`; `getOnlineGroupMemberCount()` → `Promise` | +| Constraints | Joined-only vs all-groups is a builder flag, not a separate method. `getOnlineGroupMemberCount()` takes an array of GUIDs and returns a map. | +| Related | [Create a Group](/sdk/react-native/create-group) · [Join a Group](/sdk/react-native/join-group) · [Retrieve Group Members](/sdk/react-native/retrieve-group-members) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`GroupMember`](/sdk/reference/entities#groupmember) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Fetch groups list const request = new CometChat.GroupsRequestBuilder() @@ -23,6 +36,7 @@ const joinedRequest = new CometChat.GroupsRequestBuilder() // Get online member count const count = await CometChat.getOnlineGroupMemberCount(["GUID"]); ``` + Fetch the list of [`Group`](/sdk/reference/entities#group) objects the logged-in user can see, get details for a specific group, or check online member counts. diff --git a/sdk/react-native/retrieve-users.mdx b/sdk/react-native/retrieve-users.mdx index 776f0f5b8..bbb1d1070 100644 --- a/sdk/react-native/retrieve-users.mdx +++ b/sdk/react-native/retrieve-users.mdx @@ -6,6 +6,19 @@ description: "Fetch, filter, search, and sort users using the CometChat React Na +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `getOnlineUserCount()`, `getUser()` | +| Key Classes | `CometChatException`, `User`, `UsersRequest`, `UsersRequestBuilder` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `getUser()` → `Promise`; `UsersRequest.fetchNext()` → `Promise`; `getOnlineUserCount()` → `Promise` | +| Constraints | Blocked users are filtered out unless the builder asks for them. Pass the builder to the request, not `.build()`'s result twice. | +| Related | [User Management](/sdk/react-native/user-management) · [User Presence](/sdk/react-native/user-presence) · [Block Users](/sdk/react-native/block-users) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Fetch users list const request = new CometChat.UsersRequestBuilder() @@ -21,6 +34,7 @@ const me = await CometChat.getLoggedinUser(); // Get online user count const count = await CometChat.getOnlineUserCount(); ``` + The CometChat SDK provides methods to retrieve the logged-in user, fetch filtered user lists, look up individual users by UID, and get online user counts. All user methods return [`User`](/sdk/reference/entities#user) objects. diff --git a/sdk/react-native/send-message.mdx b/sdk/react-native/send-message.mdx index ecabff88f..19719eb43 100644 --- a/sdk/react-native/send-message.mdx +++ b/sdk/react-native/send-message.mdx @@ -8,11 +8,17 @@ description: "Send CometChat text, media, and custom messages to users and group | Field | Value | | --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | | Key Classes | [`TextMessage`](/sdk/reference/messages#textmessage), [`MediaMessage`](/sdk/reference/messages#mediamessage), [`CustomMessage`](/sdk/reference/messages#custommessage) | | Key Methods | `sendMessage()`, `sendMediaMessage()`, `sendCustomMessage()` | | Receiver Types | `CometChat.RECEIVER_TYPE.USER`, `CometChat.RECEIVER_TYPE.GROUP` | | Message Types | `TEXT`, `IMAGE`, `VIDEO`, `AUDIO`, `FILE`, `CUSTOM` | | Prerequisites | SDK initialized, user logged in | +| Primary output | `Promise` — resolves to the sent `TextMessage` / `MediaMessage` / `CustomMessage`; rejects with `CometChatException` | +| Constraints | There is no `sendCardMessage()` — card messages are **receive-only**. All three send methods are async: an un-`await`ed call returns a Promise, not a message. | +| Related | [Receive Messages](/sdk/react-native/receive-messages) · [Edit a Message](/sdk/react-native/edit-message) · [Delete a Message](/sdk/react-native/delete-message) · [Threaded Messages](/sdk/react-native/threaded-messages) | +| Full reference | [`TextMessage`](/sdk/reference/messages#textmessage) · [`MediaMessage`](/sdk/reference/messages#mediamessage) · [`CustomMessage`](/sdk/reference/messages#custommessage) · [`BaseMessage`](/sdk/reference/messages#basemessage) | diff --git a/sdk/react-native/setup-sdk.mdx b/sdk/react-native/setup-sdk.mdx index 7158f5167..c932c27bb 100644 --- a/sdk/react-native/setup-sdk.mdx +++ b/sdk/react-native/setup-sdk.mdx @@ -7,6 +7,18 @@ description: "Install, configure, initialize, and log in users with the CometCha {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `init()` | +| Key Classes | `AppSettings`, `AppSettingsBuilder`, `CometChatException` | +| Primary output | `init()` → `Promise` — resolves `true` once the SDK is ready | +| Constraints | Every other SDK call rejects until `init()` resolves. `init()` is idempotent but must not race — await it once at app startup, not per screen. | +| Related | [Authentication](/sdk/react-native/authentication-overview) · [Connection Status](/sdk/react-native/connection-status) · [Key Concepts](/sdk/react-native/key-concepts) | +| Full reference | [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```bash npm install @cometchat/chat-sdk-react-native @react-native-async-storage/async-storage ``` @@ -25,6 +37,7 @@ await CometChat.login("UID", "AUTH_KEY"); // dev only ``` **Prerequisites:** npm 8+, Node.js 16+, React Native 0.63+, credentials from [CometChat Dashboard](https://app.cometchat.com) + ## Prerequisites diff --git a/sdk/react-native/threaded-messages.mdx b/sdk/react-native/threaded-messages.mdx index 9e58b2928..c63b52abb 100644 --- a/sdk/react-native/threaded-messages.mdx +++ b/sdk/react-native/threaded-messages.mdx @@ -7,6 +7,19 @@ description: "Send, receive, and fetch CometChat threaded messages in React Nati {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addMessageListener()`, `removeMessageListener()`, `sendMessage()` | +| Key Classes | `BaseMessage`, `CometChatException`, `CustomMessage`, `MediaMessage`, `MessageListener`, `MessagesRequest` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — the reply, carrying its `parentMessageId` | +| Constraints | A reply is an ordinary message with `parentMessageId` set — there is no separate send-reply method. Replies do **not** appear in the parent conversation list. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Send a Message](/sdk/react-native/send-message) · [Receive Messages](/sdk/react-native/receive-messages) · [Message Filtering](/sdk/react-native/additional-message-filtering) | +| Full reference | [`BaseMessage`](/sdk/reference/messages#basemessage) · [`TextMessage`](/sdk/reference/messages#textmessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Send message in a thread const msg = new CometChat.TextMessage("UID", "Reply", CometChat.RECEIVER_TYPE.USER); @@ -22,6 +35,7 @@ const messages = await threadRequest.fetchPrevious(); const mainRequest = new CometChat.MessagesRequestBuilder() .setUID("UID").setLimit(30).hideReplies(true).build(); ``` + Threaded messages (or threads) are messages started from a particular parent message. Each thread is attached to a parent message. diff --git a/sdk/react-native/transfer-group-ownership.mdx b/sdk/react-native/transfer-group-ownership.mdx index fe1692737..2b8233a2b 100644 --- a/sdk/react-native/transfer-group-ownership.mdx +++ b/sdk/react-native/transfer-group-ownership.mdx @@ -6,12 +6,25 @@ description: "Transfer CometChat group ownership to another member in React Nati +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `transferGroupOwnership()` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — the new owner's UID; rejects with `CometChatException` | +| Constraints | Owner-only, and the target must already be a member. The former owner stays in the group as an admin. | +| Related | [Change Member Scope](/sdk/react-native/group-change-member-scope) · [Leave a Group](/sdk/react-native/leave-group) · [Delete a Group](/sdk/react-native/delete-group) | +| Full reference | [`GroupMember`](/sdk/reference/entities#groupmember) · [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Transfer group ownership await CometChat.transferGroupOwnership("GUID", "NEW_OWNER_UID"); ``` **Note:** Only the current group owner can transfer ownership. The owner must transfer ownership before leaving the group. + Transfer ownership of a group to another member. Only the current owner can do this, and since owners cannot leave their group, you must transfer ownership first if you want to leave. See [Leave Group](/sdk/react-native/leave-group). diff --git a/sdk/react-native/transient-messages.mdx b/sdk/react-native/transient-messages.mdx index 79147999d..83699ed6a 100644 --- a/sdk/react-native/transient-messages.mdx +++ b/sdk/react-native/transient-messages.mdx @@ -7,6 +7,19 @@ description: "Send and receive ephemeral real-time messages with the CometChat R {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addMessageListener()`, `sendTransientMessage()` | +| Key Classes | `MessageListener`, `TransientMessage` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `sendTransientMessage()` returns **`void`** — fire-and-forget, nothing to await and no delivery guarantee | +| Constraints | Transient messages are never persisted: no history, no receipts, no offline delivery. Only online recipients see them. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Typing Indicators](/sdk/react-native/typing-indicators) · [Send a Message](/sdk/react-native/send-message) · [Real-Time Listeners](/sdk/react-native/real-time-listeners) | +| Full reference | [`TransientMessage`](/sdk/reference/auxiliary#transientmessage) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Send transient message to user const msg = new CometChat.TransientMessage("UID", CometChat.RECEIVER_TYPE.USER, { LIVE_REACTION: "heart" }); @@ -17,6 +30,7 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ onTransientMessageReceived: (msg) => console.log("Transient:", msg) })); ``` + Transient messages are messages that are sent in real-time only and are not saved or tracked anywhere. The receiver of the message will only receive the message if he is online and these messages cannot be retrieved later. diff --git a/sdk/react-native/typing-indicators.mdx b/sdk/react-native/typing-indicators.mdx index 000231b86..6f97bc413 100644 --- a/sdk/react-native/typing-indicators.mdx +++ b/sdk/react-native/typing-indicators.mdx @@ -7,6 +7,19 @@ description: "Send and receive CometChat typing indicators in React Native apps {/* TL;DR for Agents and Quick Reference */} +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addMessageListener()`, `endTyping()`, `removeMessageListener()`, `startTyping()` | +| Key Classes | `MessageListener`, `TypingIndicator` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `startTyping()` / `endTyping()` return **`void`** — fire-and-forget, not Promises | +| Constraints | Do not `await` them. They are transient: no persistence, and only online recipients receive them. Always pair `startTyping()` with `endTyping()`. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Transient Messages](/sdk/react-native/transient-messages) · [Send a Message](/sdk/react-native/send-message) · [Real-Time Listeners](/sdk/react-native/real-time-listeners) | +| Full reference | [`TypingIndicator`](/sdk/reference/auxiliary#typingindicator) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Start typing indicator const typing = new CometChat.TypingIndicator("UID", CometChat.RECEIVER_TYPE.USER); @@ -21,6 +34,7 @@ CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ onTypingEnded: (indicator) => console.log("Typing ended:", indicator) })); ``` + ## Send a Typing Indicator diff --git a/sdk/react-native/update-group.mdx b/sdk/react-native/update-group.mdx index 30acd1df6..97767b991 100644 --- a/sdk/react-native/update-group.mdx +++ b/sdk/react-native/update-group.mdx @@ -6,11 +6,25 @@ description: "Update group details such as name, type, icon, and description usi +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `updateGroup()` | +| Key Classes | `CometChatException`, `GROUP_TYPE`, `Group` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `Promise` — the updated group; rejects with `CometChatException` | +| Constraints | Owner or admin only. The GUID cannot be changed — pass the existing GUID and only the fields you are altering. | +| Related | [Create a Group](/sdk/react-native/create-group) · [Retrieve Groups](/sdk/react-native/retrieve-groups) · [Change Member Scope](/sdk/react-native/group-change-member-scope) | +| Full reference | [`Group`](/sdk/reference/entities#group) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Update group details const group = new CometChat.Group("GUID", "New Name", CometChat.GROUP_TYPE.PUBLIC); const updated = await CometChat.updateGroup(group); ``` + Update a group's name, icon, description, or metadata. The GUID and group type cannot be changed after creation. See the [Group Class](/sdk/react-native/create-group#group-class) reference for all editable fields. diff --git a/sdk/react-native/user-management.mdx b/sdk/react-native/user-management.mdx index c89a8f6f6..4a0046ecd 100644 --- a/sdk/react-native/user-management.mdx +++ b/sdk/react-native/user-management.mdx @@ -6,6 +6,19 @@ description: "Create, update, and manage CometChat users programmatically using +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `createUser()`, `updateCurrentUserDetails()`, `updateUser()` | +| Key Classes | `CometChatException`, `User` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `createUser()` / `updateUser()` / `updateCurrentUserDetails()` → `Promise` | +| Constraints | `createUser()` and `updateUser()` need the **Auth Key** and are development-only — do not ship them in a client. `updateCurrentUserDetails()` is the safe client-side call. | +| Related | [Authentication](/sdk/react-native/authentication-overview) · [Retrieve Users](/sdk/react-native/retrieve-users) · [User Presence](/sdk/react-native/user-presence) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Create a user const user = new CometChat.User("user1"); @@ -21,6 +34,7 @@ await CometChat.updateCurrentUserDetails(user); ``` **Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). + Users must exist in CometChat before they can log in. This page covers creating, updating, and deleting users. All methods that return user data return a [`User`](/sdk/reference/entities#user) object. diff --git a/sdk/react-native/user-presence.mdx b/sdk/react-native/user-presence.mdx index cb79deb6e..2f7bc8dcd 100644 --- a/sdk/react-native/user-presence.mdx +++ b/sdk/react-native/user-presence.mdx @@ -6,6 +6,19 @@ description: "Track real-time user online/offline status and configure presence +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-sdk-react-native` | +| Import | `import { CometChat } from "@cometchat/chat-sdk-react-native";` | +| Key Methods | `addUserListener()`, `removeUserListener()` | +| Key Classes | `User`, `UserListener` | +| Prerequisites | SDK initialized via [`CometChat.init()`](/sdk/react-native/setup-sdk) and a logged-in user via [`CometChat.login()`](/sdk/react-native/authentication-overview) | +| Primary output | `addUserListener()` / `removeUserListener()` return **`void`** — presence arrives on `onUserOnline` / `onUserOffline` | +| Constraints | Presence needs a subscription set at `init()` (`ALL_USERS` / `FRIENDS` / `ROLES`); with none, the callbacks never fire. Every `add*Listener()` needs a matching `remove*Listener()` with the same listener ID — unremoved listeners leak and fire after unmount. | +| Related | [Retrieve Users](/sdk/react-native/retrieve-users) · [Real-Time Listeners](/sdk/react-native/real-time-listeners) · [Setup SDK](/sdk/react-native/setup-sdk) | +| Full reference | [`User`](/sdk/reference/entities#user) · [`CometChatException`](/sdk/reference/auxiliary#cometchatexception) | + + ```javascript // Subscribe to presence during init const appSettings = new CometChat.AppSettingsBuilder() @@ -21,6 +34,7 @@ CometChat.addUserListener("LISTENER_ID", new CometChat.UserListener({ // Remove listener CometChat.removeUserListener("LISTENER_ID"); ``` + Track whether users are online or offline in real-time. diff --git a/ui-kit/android/architecture-data-flow.mdx b/ui-kit/android/architecture-data-flow.mdx index ee3e24a10..d371dbe9c 100644 --- a/ui-kit/android/architecture-data-flow.mdx +++ b/ui-kit/android/architecture-data-flow.mdx @@ -1,16 +1,16 @@ --- title: "Architecture & Data Flow" -description: "How chatuikit-core, chatuikit-jetpack, and chatuikit-kotlin modules are structured using Clean Architecture." +description: "How chatuikit-core, chatuikit-compose, and chatuikit-kotlin modules are structured using Clean Architecture." --- -The UI Kit is split into three modules that follow Clean Architecture principles. `chatuikit-core` holds all business logic, data access, and state management. The UI modules (`chatuikit-jetpack` and `chatuikit-kotlin`) provide platform-specific rendering on top of the shared core. +The UI Kit is split into three modules that follow Clean Architecture principles. `chatuikit-core` holds all business logic, data access, and state management. The UI modules (`chatuikit-compose` and `chatuikit-kotlin`) provide platform-specific rendering on top of the shared core. ## Module Structure ```mermaid graph TD subgraph UI["UI Modules"] - A["chatuikit-jetpack
Jetpack Compose UI
Composables, Themes"] + A["chatuikit-compose
Jetpack Compose UI
Composables, Themes"] B["chatuikit-kotlin
XML Views / ViewBinding
Custom Views, Adapters"] end @@ -39,7 +39,7 @@ Every feature follows the same layered flow: **View → ViewModel → Repository ```mermaid block-beta columns 1 - A["View / Composable\nchatuikit-kotlin or chatuikit-jetpack"] + A["View / Composable\nchatuikit-kotlin or chatuikit-compose"] B["ViewModel\nchatuikit-core"] C["Repository\nchatuikit-core"] D["DataSource\nchatuikit-core → CometChat SDK"] @@ -447,7 +447,7 @@ class LoggingGetConversationsUseCase( ### 4. Passing a Custom ViewModel to the UI Component -Both `chatuikit-jetpack` (Compose) and `chatuikit-kotlin` (XML Views) accept a pre-built ViewModel. This is the entry point for all overrides. +Both `chatuikit-compose` (Compose) and `chatuikit-kotlin` (XML Views) accept a pre-built ViewModel. This is the entry point for all overrides. diff --git a/ui-kit/android/call-features.mdx b/ui-kit/android/call-features.mdx index 4ba919cd8..af17a5d73 100644 --- a/ui-kit/android/call-features.mdx +++ b/ui-kit/android/call-features.mdx @@ -33,7 +33,7 @@ Add the following dependency to your `build.gradle.kts` file: ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-kotlin-android:6.0.3") + implementation("com.cometchat:chatuikit-kotlin-android:6.0.6") implementation("com.cometchat:calls-sdk-android:5.0.1") } ``` @@ -42,7 +42,7 @@ dependencies { ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-compose-android:6.0.3") + implementation("com.cometchat:chatuikit-compose-android:6.0.6") implementation("com.cometchat:calls-sdk-android:5.0.1") } ``` diff --git a/ui-kit/android/call-logs.mdx b/ui-kit/android/call-logs.mdx index c6aa9ff42..34d6381d8 100644 --- a/ui-kit/android/call-logs.mdx +++ b/ui-kit/android/call-logs.mdx @@ -11,6 +11,33 @@ description: "Scrollable list of call logs for the logged-in user with caller na --- + + +**Requires the Calls SDK AND calling to be initialized — this component CRASHES otherwise.** +`CometChatCallLogs` builds a `CallLogRequest` in its ViewModel's `init {}`, with **no availability +check**, so simply placing it on a screen is fatal unless both conditions hold. Verified on device: + +| Calls artifact | `uiKit.enableCalling` | Result | +|---|---|---| +| absent | anything | `java.lang.NoClassDefFoundError: …CallLogRequest$CallLogRequestBuilder` | +| present | `false` | `java.lang.RuntimeException: Please call the CometChatCalls.init() method …` | +| present | `true` | renders (empty/error state when there are no logs) | + +Both are required: + +```kotlin +// app/build.gradle.kts +implementation("com.cometchat:calls-sdk-android:5.0.+") +``` +```json +// app/src/main/assets/cometchat-settings.json — this is what makes the UI Kit init CometChatCalls +{ "uiKit": { "enableCalling": true } } +``` + +The component **compiles fine** in every case — the failure is runtime-only, so a build cannot warn +you. The same applies to the other calling components. + + ## Where It Fits `CometChatCallLogs` is a list component. It renders the user's call history and emits the selected `CallLog` via `onItemClick`. Use it as a standalone call history screen or as a tab in a tabbed layout alongside conversations and contacts. diff --git a/ui-kit/android/calling-integration.mdx b/ui-kit/android/calling-integration.mdx index 5a8914a00..ede933702 100644 --- a/ui-kit/android/calling-integration.mdx +++ b/ui-kit/android/calling-integration.mdx @@ -1,6 +1,6 @@ --- title: "Calling Integration" -description: "Add voice and video calling to your Android UI Kit application using chatuikit-kotlin or chatuikit-jetpack." +description: "Add voice and video calling to your Android UI Kit application using chatuikit-kotlin or chatuikit-compose." --- ## Overview @@ -11,6 +11,23 @@ This guide walks you through adding voice and video calling capabilities to your Make sure you've completed the [Getting Started](/ui-kit/android/getting-started) guide before proceeding. + + +**`enableCalling: true` makes the Calls SDK dependency mandatory — otherwise the app crashes at +launch.** With the flag set, `CometChatUIKit.initFromSettings()` calls `initCometChatCalls()`, which +throws if `com.cometchat:calls-sdk-android` is absent: + +``` +java.lang.NoClassDefFoundError: Failed resolution of: + Lcom/cometchat/calls/core/CometChatCalls$SessionSettingsBuilder; + at com.cometchat.uikit.core.CometChatUIKit.initCometChatCalls(CometChatUIKit.kt:229) +``` + +The crash happens in `onCreate`, **before any UI renders** — the flag name gives no hint that a +dependency is implied. Change the flag and the dependency together, or leave `enableCalling` as +`false` in an app that does not use calling. + + ## Add the Calls SDK Add the CometChat Calls SDK dependency alongside your chosen UI Kit module: @@ -19,7 +36,7 @@ Add the CometChat Calls SDK dependency alongside your chosen UI Kit module: ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-kotlin-android:6.0.3") + implementation("com.cometchat:chatuikit-kotlin-android:6.0.6") implementation("com.cometchat:calls-sdk-android:5.0.1") } ``` @@ -28,14 +45,38 @@ dependencies { ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-compose-android:6.0.3") + implementation("com.cometchat:chatuikit-compose-android:6.0.6") implementation("com.cometchat:calls-sdk-android:5.0.1") } ``` -After adding this dependency, the Android UI Kit will automatically detect it and activate the calling features. You will see the `CometChatCallButtons` component rendered in the [MessageHeader](/ui-kit/android/message-header) component. +After adding this dependency, the Android UI Kit will automatically detect it and activate the calling features. + +Once calling is active, the voice and video call buttons render in the [MessageHeader](/ui-kit/android/message-header): + + + +The call buttons appear automatically — `CometChatMessageHeader` detects that calling is enabled, so no extra code is needed. + + + +The `CometChatMessageHeader` composable hides the call buttons by default (`hideVoiceCallButton` and `hideVideoCallButton` both default to `true`). Show them explicitly: + +```kotlin +CometChatMessageHeader( + user = user, + hideVoiceCallButton = false, + hideVideoCallButton = false +) +``` + + + + +**Enabling calling in an app that already has logged-in users requires a re-login.** `CometChatUIKit.login()` short-circuits when the same uid already has a persisted session — it returns `onSuccess` without logging the Calls SDK in, so the Calls SDK has no auth token and `CometChatCallLogs` shows a silent error state (logcat: `User auth token cannot be null`). After calling is first enabled, log out and log in again (`CometChatUIKit.logout(...)` then `CometChatUIKit.login(...)`), and wire `onError` on `CometChatCallLogs` during development so this failure is visible. + diff --git a/ui-kit/android/conversation-message-view.mdx b/ui-kit/android/conversation-message-view.mdx index 0218a4c47..5f7325e28 100644 --- a/ui-kit/android/conversation-message-view.mdx +++ b/ui-kit/android/conversation-message-view.mdx @@ -177,6 +177,22 @@ fun ConversationsScreen( --- + +**`enableEdgeToEdge()` alone is not enough.** It draws your layout edge-to-edge, so the UI Kit +toolbar renders **under the status bar** and the title collides with the clock. Give the layout root +an `android:id` and consume the insets (add `Type.ime()` on the message screen so the composer rides +above the keyboard): + +```kotlin +ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.root)) { v, insets -> + val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) + val ime = insets.getInsets(WindowInsetsCompat.Type.ime()) + v.setPadding(bars.left, bars.top, bars.right, maxOf(bars.bottom, ime.bottom)) + insets +} +``` + + ## Step 2: Set Up the Message Screen diff --git a/ui-kit/android/custom-text-formatter-guide.mdx b/ui-kit/android/custom-text-formatter-guide.mdx index 89c7b5070..9846d9ad3 100644 --- a/ui-kit/android/custom-text-formatter-guide.mdx +++ b/ui-kit/android/custom-text-formatter-guide.mdx @@ -8,7 +8,7 @@ description: "Extend CometChatTextFormatter to build custom inline text patterns | Field | Value | | --- | --- | -| Packages | `com.cometchat:chatuikit-kotlin` · `com.cometchat:chatuikit-jetpack` | +| Packages | `com.cometchat:chatuikit-kotlin-android` · `com.cometchat:chatuikit-compose-android` | | Key class | `CometChatTextFormatter` (abstract base class for custom formatters) | | Required setup | `CometChatUIKit.init()` then `CometChatUIKit.login("UID")` | | Purpose | Extend to create custom inline text patterns with tracking characters, suggestion lists, and span formatting | @@ -108,19 +108,20 @@ override fun prepareRightMessageBubbleSpan( ```kotlin lines -import com.cometchat.uikit.core.CometChatUIKit -val textFormatters = CometChatUIKit.getDataSource().getTextFormatters(this, messageComposer.additionParameter) -textFormatters.add(HashTagFormatter()) -messageComposer.setTextFormatters(textFormatters) +// V6: build the list yourself. The composer auto-adds a default CometChatMentionsFormatter, +// and setTextFormatters REPLACES the list — include the mentions formatter to keep @mentions. +messageComposer.setTextFormatters( + listOf(CometChatMentionsFormatter(this), HashTagFormatter()) +) ``` ```kotlin lines -import com.cometchat.uikit.core.CometChatUIKit // In your composable or ViewModel setup -val textFormatters = CometChatUIKit.getDataSource().getTextFormatters(context, additionParameter) +// V6: build the list yourself — setTextFormatters REPLACES the default list. +val textFormatters = listOf(CometChatMentionsFormatter(context), HashTagFormatter()) textFormatters.add(HashTagFormatter()) CometChatMessageComposer( diff --git a/ui-kit/android/getting-started-jetpack.mdx b/ui-kit/android/getting-started-jetpack.mdx index e84b77251..5a4377e55 100644 --- a/ui-kit/android/getting-started-jetpack.mdx +++ b/ui-kit/android/getting-started-jetpack.mdx @@ -36,6 +36,7 @@ You need three things from the [CometChat Dashboard](https://app.cometchat.com/) You also need: - Android Studio (Hedgehog or later recommended) - An Android emulator or physical device running Android 9.0 (API 28) or higher +- `compileSdk = 36` (or newer) in your app module — the UI Kit's transitive `androidx.core:core-ktx:1.18.0` requires it; a `compileSdk`-35 app fails `checkDebugAarMetadata` with an AAR-metadata error - Kotlin configured with Compose compiler plugin - Gradle plugin 8.0+ with Kotlin DSL @@ -45,6 +46,23 @@ Auth Key is for development only. In production, generate Auth Tokens server-sid --- + + +**`enableCalling: true` makes the Calls SDK dependency mandatory — otherwise the app crashes at +launch.** With the flag set, `CometChatUIKit.initFromSettings()` calls `initCometChatCalls()`, which +throws if `com.cometchat:calls-sdk-android` is absent: + +``` +java.lang.NoClassDefFoundError: Failed resolution of: + Lcom/cometchat/calls/core/CometChatCalls$SessionSettingsBuilder; + at com.cometchat.uikit.core.CometChatUIKit.initCometChatCalls(CometChatUIKit.kt:229) +``` + +The crash happens in `onCreate`, **before any UI renders** — the flag name gives no hint that a +dependency is implied. Change the flag and the dependency together, or leave `enableCalling` as +`false` in an app that does not use calling. + + ## Step 1 — Create an Android Project 1. Open Android Studio and start a new project. @@ -98,7 +116,7 @@ android { dependencies { // CometChat Jetpack Compose UI Kit - implementation("com.cometchat:chatuikit-compose-android:6.0.3") + implementation("com.cometchat:chatuikit-compose-android:6.0.6") // (Optional) Voice/video calling implementation("com.cometchat:calls-sdk-android:5.0.1") @@ -107,6 +125,19 @@ dependencies { --- + +**Required dependency exclude.** The UI Kit pulls `io.noties:prism4j`, which brings +`org.jetbrains:annotations-java5:17.0.0`. That duplicates `org.jetbrains:annotations:23.0.0` from +AndroidX/Kotlin and the build fails at dexing with ~40 `Duplicate class org.jetbrains.annotations.*` +errors. Add this to your app module: + +```kotlin +configurations.all { + exclude(group = "org.jetbrains", module = "annotations-java5") +} +``` + + ## Step 3 — Initialize and Login Create your `MainActivity.kt` with the CometChat initialization and login flow. Since Compose uses a declarative approach, we track the auth state and render UI conditionally: diff --git a/ui-kit/android/getting-started-kotlin.mdx b/ui-kit/android/getting-started-kotlin.mdx index 08fb97062..a60485102 100644 --- a/ui-kit/android/getting-started-kotlin.mdx +++ b/ui-kit/android/getting-started-kotlin.mdx @@ -36,6 +36,7 @@ You need three things from the [CometChat Dashboard](https://app.cometchat.com/) You also need: - Android Studio installed - An Android emulator or physical device running Android 9.0 (API 28) or higher +- `compileSdk = 36` (or newer) in your app module — the UI Kit's transitive `androidx.core:core-ktx:1.18.0` requires it; a `compileSdk`-35 app fails `checkDebugAarMetadata` with an AAR-metadata error - Kotlin configured in your project - Gradle plugin 8.0+ with Kotlin DSL @@ -45,6 +46,23 @@ Auth Key is for development only. In production, generate Auth Tokens server-sid --- + + +**`enableCalling: true` makes the Calls SDK dependency mandatory — otherwise the app crashes at +launch.** With the flag set, `CometChatUIKit.initFromSettings()` calls `initCometChatCalls()`, which +throws if `com.cometchat:calls-sdk-android` is absent: + +``` +java.lang.NoClassDefFoundError: Failed resolution of: + Lcom/cometchat/calls/core/CometChatCalls$SessionSettingsBuilder; + at com.cometchat.uikit.core.CometChatUIKit.initCometChatCalls(CometChatUIKit.kt:229) +``` + +The crash happens in `onCreate`, **before any UI renders** — the flag name gives no hint that a +dependency is implied. Change the flag and the dependency together, or leave `enableCalling` as +`false` in an app that does not use calling. + + ## Step 1 — Create an Android Project 1. Open Android Studio and start a new project. @@ -93,7 +111,7 @@ android { dependencies { // CometChat Kotlin UI Kit - implementation("com.cometchat:chatuikit-kotlin-android:6.0.3") + implementation("com.cometchat:chatuikit-kotlin-android:6.0.6") // (Optional) Voice/video calling implementation("com.cometchat:calls-sdk-android:5.0.1") @@ -110,6 +128,35 @@ android.enableJetifier=true --- + +**Required dependency exclude.** The UI Kit pulls `io.noties:prism4j`, which brings +`org.jetbrains:annotations-java5:17.0.0`. That duplicates `org.jetbrains:annotations:23.0.0` from +AndroidX/Kotlin and the build fails at dexing with ~40 `Duplicate class org.jetbrains.annotations.*` +errors. Add this to your app module: + +```kotlin +configurations.all { + exclude(group = "org.jetbrains", module = "annotations-java5") +} +``` + + + +**Required app theme.** The UI Kit's views are Material components, so on a non-Material theme the +first CometChat view you inflate throws `IllegalArgumentException: The style on this component +requires your app theme to be Theme.MaterialComponents (or a descendant)` — the app crashes on the +chat screen rather than rendering it unstyled. Inherit the kit's theme, which already descends from +Material: + +```xml res/values/themes.xml + + + +``` + +> **What this does:** Defines a custom style `CustomAIAssistantChatHistoryStyle` that sets the background color to `#FFFAF6` for the component, header, new chat area, date separator, and items. It applies a Times New Roman font to the header, new chat text, date separator, and item text. A helper style `textStyleTimesNewRoman` defines the font family. + + + + +```kotlin lines +binding.cometchatAiAssistantChatHistory.setStyle(R.style.CustomAIAssistantChatHistoryStyle); +``` + + + +```kotlin lines +import com.cometchat.uikit.compose.presentation.aiassistantchathistory.style.CometChatAIAssistantChatHistoryStyle + +CometChatAIAssistantChatHistory( + style = CometChatAIAssistantChatHistoryStyle.default().copy( + chatHistoryBackgroundColor = Color(0xFFEDEAFA) + ) +) +``` + + + +> **What this does:** Applies the `CustomAIAssistantChatHistoryStyle` theme to the `CometChatAIAssistantChatHistory` component, changing the background colors and fonts. + +To know more such attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_assistant_chat_history.xml). + +- **Verify**: The chat history component displays with the `#FFFAF6` background color and Times New Roman font for header text, new chat text, date separator text, and item text. + +## Functionality + +What you're changing: Small functional customizations such as setting the user and toggling visibility of UI states. + +- **Where**: Activity or Fragment where you hold a reference to `CometChatAIAssistantChatHistory`. +- **Applies to**: `CometChatAIAssistantChatHistory`. +- **Default behavior**: All UI states are visible with default settings. +- **Override**: Call the corresponding method on the component instance. + +| Methods | Description | Code | +| --- | --- | --- | +| `setUser` | Sets the user whose chat histories with the AI assistant need to be fetched. This is a required property for the component to function. The user's role must be `@agentic`. | `.setUser(user);` | +| `setErrorStateVisibility` | Toggles the visibility of the error state of the component | `.setErrorStateVisibility(View.GONE);` | +| `setEmptyStateVisibility` | Toggles the visibility of the empty state of the component | `.setEmptyStateVisibility(View.GONE);` | + +- **Verify**: After calling `setUser(user)`, confirm the component fetches and displays the AI assistant chat histories for that user. After calling a visibility method, confirm the corresponding UI state is shown or hidden. + +## Customization Matrix + +| What you want to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Component background color | `themes.xml` | `cometChatAIAssistantChatHistoryBackgroundColor` | `#FFFAF6` | +| Header background color | `themes.xml` | `cometChatAIAssistantChatHistoryHeaderBackgroundColor` | `#FFFAF6` | +| Header text color | `themes.xml` | `cometChatAIAssistantChatHistoryHeaderTextColor` | `?attr/cometchatTextColorPrimary` | +| Header text appearance | `themes.xml` | `cometChatAIAssistantChatHistoryHeaderTextAppearance` | `@style/textStyleTimesNewRoman` | +| New chat background color | `themes.xml` | `cometChatAIAssistantChatHistoryNewChatBackgroundColor` | `#FFFAF6` | +| New chat text color | `themes.xml` | `cometChatAIAssistantChatHistoryNewChatTextColor` | `?attr/cometchatTextColorPrimary` | +| New chat text appearance | `themes.xml` | `cometChatAIAssistantChatHistoryNewChatTextAppearance` | `@style/textStyleTimesNewRoman` | +| Date separator text appearance | `themes.xml` | `cometChatAIAssistantChatHistoryDateSeparatorTextAppearance` | `@style/textStyleTimesNewRoman` | +| Date separator text color | `themes.xml` | `cometChatAIAssistantChatHistoryDateSeparatorTextColor` | `?attr/cometchatTextColorTertiary` | +| Date separator background color | `themes.xml` | `cometChatAIAssistantChatHistoryDateSeparatorBackgroundColor` | `#FFFAF6` | +| Item background color | `themes.xml` | `cometChatAIAssistantChatHistoryItemBackgroundColor` | `#FFFAF6` | +| Item text appearance | `themes.xml` | `cometChatAIAssistantChatHistoryItemTextAppearance` | `@style/textStyleTimesNewRoman` | +| Item text color | `themes.xml` | `cometChatAIAssistantChatHistoryItemTextColor` | `?attr/cometchatTextColorPrimary` | +| Apply a custom style | Activity/Fragment | `setStyle(int styleRes)` | `binding.cometchatAiAssistantChatHistory.setStyle(R.style.CustomAIAssistantChatHistoryStyle);` | +| Set the user for fetching history | Activity/Fragment | `setUser(User)` | `.setUser(user);` | +| Error state visibility | Activity/Fragment | `setErrorStateVisibility(int)` | `.setErrorStateVisibility(View.GONE);` | +| Empty state visibility | Activity/Fragment | `setEmptyStateVisibility(int)` | `.setEmptyStateVisibility(View.GONE);` | + +## Next Steps + + + + Display messages in a conversation + + + Browse recent conversations + + + Browse and search available users + + + Search across conversations and messages + + \ No newline at end of file diff --git a/ui-kit/android/v6/ai-features.mdx b/ui-kit/android/v6/ai-features.mdx new file mode 100644 index 000000000..d9e7c149a --- /dev/null +++ b/ui-kit/android/v6/ai-features.mdx @@ -0,0 +1,59 @@ +--- +title: "Smart Chat Features" +description: "Integrate AI-powered conversation starters, smart replies, and conversation summaries into your Android chat app." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin-android` (Java), `com.cometchat:chatuikit-kotlin-android` (Kotlin XML), `com.cometchat:chatuikit-compose-android` (Jetpack Compose) | +| Required setup | `CometChatUIKit.init()` then `CometChatUIKit.login()` + AI features enabled in [CometChat Dashboard](/fundamentals/ai-user-copilot/overview) | +| AI features | Conversation Starter, Smart Replies, Conversation Summary | +| Key components | [Message List](/ui-kit/android/v6/message-list) (Conversation Starter), [Message Composer](/ui-kit/android/v6/message-composer) (Smart Replies, Summary) | +| Activation | Enable each AI feature from the CometChat Dashboard — UI Kit auto-integrates them, no additional code required | +| Related | [Core Features](/ui-kit/android/v6/core-features), [Extensions](/ui-kit/android/v6/extensions), [AI Agent Guide](/ui-kit/android/v6/guide-ai-agent) | + + + +CometChat's AI capabilities greatly enhance user interaction and engagement in your application. Here's how the Android UI Kit integrates these features. + + + + + +## Conversation Starter + +When a user initiates a new chat, the UI kit displays a list of suggested opening lines that users can select, making it easier for them to start a conversation. These suggestions are powered by CometChat's AI, which predicts contextually relevant conversation starter options. + +For a comprehensive understanding and guide on implementing and using the Conversation Starter, refer to our specific guide on the [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter). + +Once you have successfully activated the [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter) from your CometChat Dashboard, the feature will automatically be incorporated into the [MessageList](/ui-kit/android/v6/message-list) Component of UI Kits. + + + + + +## Smart Replies + +Smart Replies are AI-generated responses to messages. They can predict what a user might want to say next by analyzing the context of the conversation. This allows for quicker and more convenient responses, especially on mobile devices. + +For a comprehensive understanding and guide on implementing and using the Smart Replies, refer to our specific guide on the [Smart Replies](/fundamentals/ai-user-copilot/smart-replies). + +Once you have successfully activated the [Smart Replies](/fundamentals/ai-user-copilot/smart-replies) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/android/v6/message-composer) Component of UI Kits. + + + + + +## Conversation Summary + +The Conversation Summary feature provides concise summaries of long conversations, allowing users to catch up quickly on missed chats. This feature uses natural language processing to determine the main points in a conversation. + +For a comprehensive understanding and guide on implementing and using the Conversation Summary, refer to our specific guide on the [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary). + +Once you have successfully activated the [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/android/v6/message-composer) Component of UI Kits. + + + + diff --git a/ui-kit/android/v6/architecture-data-flow.mdx b/ui-kit/android/v6/architecture-data-flow.mdx new file mode 100644 index 000000000..dc8a3a4ad --- /dev/null +++ b/ui-kit/android/v6/architecture-data-flow.mdx @@ -0,0 +1,521 @@ +--- +title: "Architecture & Data Flow" +description: "How chatuikit-core, chatuikit-jetpack, and chatuikit-kotlin modules are structured using Clean Architecture." +--- + +The UI Kit is split into three modules that follow Clean Architecture principles. `chatuikit-core` holds all business logic, data access, and state management. The UI modules (`chatuikit-jetpack` and `chatuikit-kotlin`) provide platform-specific rendering on top of the shared core. + +## Module Structure + +```mermaid +graph TD + subgraph UI["UI Modules"] + A["chatuikit-jetpack
Jetpack Compose UI
Composables, Themes"] + B["chatuikit-kotlin
XML Views / ViewBinding
Custom Views, Adapters"] + end + + subgraph Core["chatuikit-core"] + D["domain/ — usecase, repository interfaces, models"] + E["data/ — datasource, repository implementations"] + F["viewmodel/ — shared ViewModels"] + G["state/ — sealed UIState classes"] + H["events/ — CometChatEvents SharedFlow bus"] + I["factory/ — ViewModel factories"] + J["formatter, mentions, resources, utils"] + end + + K["CometChat SDK
Chat SDK 4.x · Calls SDK 4.x"] + + A -->|depends on| Core + B -->|depends on| Core + Core -->|calls| K + +``` + +## 4-Layer Architecture + +Every feature follows the same layered flow: **View → ViewModel → Repository → DataSource**. + +```mermaid +block-beta + columns 1 + A["View / Composable\nchatuikit-kotlin or chatuikit-jetpack"] + B["ViewModel\nchatuikit-core"] + C["Repository\nchatuikit-core"] + D["DataSource\nchatuikit-core → CometChat SDK"] + + A --> B + B --> C + C --> D +``` + +The ViewModel lives in `chatuikit-core` and is shared by both UI modules. This means the same `CometChatConversationsViewModel` drives both the XML View and the Composable — only the rendering layer differs. + +## Clean Architecture Layers (chatuikit-core) + +### Data Layer + +The data layer wraps the CometChat SDK behind interfaces, making it swappable and testable. + +**DataSource** — defines the contract for raw SDK operations: + +```kotlin +// Interface (contract) +interface ConversationsDataSource { + suspend fun fetchConversations(request: ConversationsRequest): List + suspend fun deleteConversation(conversationWith: String, conversationType: String): String + suspend fun markAsDelivered(message: BaseMessage) +} + +// Implementation (calls CometChat SDK) +class ConversationsDataSourceImpl : ConversationsDataSource { + override suspend fun fetchConversations(request: ConversationsRequest): List { + // Wraps CometChat.fetchConversations() in a coroutine + } +} +``` + +Every feature has a DataSource pair: `ConversationsDataSource` / `ConversationsDataSourceImpl`, `UsersDataSource` / `UsersDataSourceImpl`, etc. + +**Repository Implementation** — coordinates data sources and handles error wrapping: + +```kotlin +class ConversationsRepositoryImpl( + private val dataSource: ConversationsDataSource +) : ConversationsRepository { + + private var hasMore = true + + override suspend fun getConversations( + request: ConversationsRequest + ): Result> { + return try { + val conversations = dataSource.fetchConversations(request) + hasMore = conversations.isNotEmpty() + Result.success(conversations) + } catch (e: CometChatException) { + Result.failure(e) + } + } +} +``` + +Repositories wrap raw SDK exceptions into Kotlin `Result` types, track pagination state, and coordinate between data sources. + +### Domain Layer + +The domain layer defines contracts and single-purpose use cases. It has no dependency on the SDK or Android framework. + +**Repository Interfaces** — contracts that the data layer implements: + +```kotlin +interface ConversationsRepository { + suspend fun getConversations(request: ConversationsRequest): Result> + suspend fun deleteConversation(conversationWith: String, conversationType: String): Result + suspend fun markAsDelivered(conversation: Conversation): Result + fun hasMoreConversations(): Boolean +} +``` + +**Use Cases** — encapsulate a single business action: + +```kotlin +open class GetConversationsUseCase( + private val repository: ConversationsRepository +) { + open suspend operator fun invoke( + request: ConversationsRequest + ): Result> { + return repository.getConversations(request) + } + + open fun hasMore(): Boolean = repository.hasMoreConversations() +} +``` + +Use cases are `open` so they can be overridden for testing or custom behavior. Each use case does one thing: + +| Use Case | Action | +|---|---| +| `GetConversationsUseCase` | Fetch paginated conversations | +| `DeleteConversationUseCase` | Delete a conversation | +| `RefreshConversationsUseCase` | Clear and re-fetch | +| `FetchUsersUseCase` / `SearchUsersUseCase` | Fetch or search users | +| `FetchGroupsUseCase` | Fetch groups | +| `FetchGroupMembersUseCase` / `SearchGroupMembersUseCase` | Fetch or search group members | +| `BanGroupMemberUseCase` / `KickGroupMemberUseCase` | Member moderation | +| `ChangeMemberScopeUseCase` | Change member role | +| `SendTextMessageUseCase` / `SendMediaMessageUseCase` / `SendCustomMessageUseCase` | Send messages | +| `EditMessageUseCase` | Edit a sent message | +| `FetchCallLogsUseCase` | Fetch call history | +| `InitiateCallUseCase` / `InitiateUserCallUseCase` / `StartGroupCallUseCase` | Start calls | +| `FetchReactionsUseCase` / `RemoveReactionUseCase` | Reaction management | +| `CreatePollUseCase` | Create a poll | +| `GetStickersUseCase` | Fetch sticker sets | +| `JoinGroupUseCase` / `GetGroupUseCase` / `GetUserUseCase` | Entity lookups | + +### ViewModel Layer + +ViewModels receive use cases via constructor injection and expose `StateFlow` / sealed `UIState` classes to the UI: + +```kotlin +class CometChatConversationsViewModel( + private val getConversationsUseCase: GetConversationsUseCase, + private val deleteConversationUseCase: DeleteConversationUseCase, + private val refreshConversationsUseCase: RefreshConversationsUseCase, + private val enableListeners: Boolean = true +) : ViewModel() { + + // UI observes this sealed state + private val _uiState = MutableStateFlow(UIState.Loading) + val uiState: StateFlow = _uiState + + fun fetchConversations() { + viewModelScope.launch { + getConversationsUseCase(request) + .onSuccess { conversations -> + _uiState.value = if (conversations.isEmpty()) UIState.Empty + else UIState.Content(conversations) + } + .onFailure { _uiState.value = UIState.Error(it) } + } + } +} +``` + +### State Management (StateFlow + Sealed Classes) + +Each feature has a dedicated sealed UIState class. All state is exposed via `StateFlow` — not LiveData: + +```kotlin +sealed class UIState { + object Loading : UIState() + object Empty : UIState() + data class Error(val exception: CometChatException) : UIState() + data class Content(val conversations: List) : UIState() +} +``` + +Feature-specific states include additional fields: + +| State Class | Feature | Extra Fields | +|---|---|---| +| `ConversationStarterUIState` | Conversation list | — | +| `MessageListUIState` | Message list | scroll position, reply state | +| `MessageComposerUIState` | Composer | attachment state, edit mode | +| `MessageHeaderUIState` | Header | typing indicator, user status | +| `GroupsUIState` | Groups | — | +| `UsersUIState` | Users | — | +| `GroupMembersUIState` | Group members | scope change state | +| `CallLogsUIState` | Call logs | — | +| `CallButtonsUIState` | Call buttons | call initiation state | +| `IncomingCallUIState` / `OutgoingCallUIState` / `OngoingCallUIState` | Calls | call session state | +| `ReactionListUIState` | Reactions | — | +| `CreatePollUIState` | Polls | form validation state | +| `StickerKeyboardUIState` | Stickers | sticker sets | + +### ListOperations Interface + +List-based ViewModels implement the `ListOperations` interface, which provides a standard contract for manipulating list data: + +```kotlin +interface ListOperations { + fun addAtIndex(index: Int, item: T) + fun updateAtIndex(index: Int, item: T) + fun removeAtIndex(index: Int) + fun moveToTop(item: T) +} +``` + +This ensures consistent list manipulation across Conversations, Users, Groups, Group Members, and Call Logs. + +## Dependency Injection via Factories + +ViewModels are created through `ViewModelProvider.Factory` classes that wire up the dependency chain: + +```kotlin +class CometChatConversationsViewModelFactory( + private val repository: ConversationsRepository = ConversationsRepositoryImpl( + ConversationsDataSourceImpl() + ), + private val enableListeners: Boolean = true +) : ViewModelProvider.Factory { + + override fun create(modelClass: Class): T { + val getUseCase = GetConversationsUseCase(repository) + val deleteUseCase = DeleteConversationUseCase(repository) + val refreshUseCase = RefreshConversationsUseCase(repository) + + return CometChatConversationsViewModel( + getConversationsUseCase = getUseCase, + deleteConversationUseCase = deleteUseCase, + refreshConversationsUseCase = refreshUseCase, + enableListeners = enableListeners + ) as T + } +} +``` + +Default implementations are provided, but you can inject custom repositories: + +```kotlin +// Custom repository for testing or caching +val factory = CometChatConversationsViewModelFactory( + repository = MyCustomConversationRepository(), + enableListeners = false // disable for previews +) +``` + +## Data Flow: End to End + +### Fetching Conversations + +```mermaid +graph TD + A["UI — Composable / View
collects uiState"] --> B["CometChatConversationsViewModel
calls getConversationsUseCase"] + B --> C["GetConversationsUseCase
calls repository.getConversations"] + C --> D["ConversationsRepositoryImpl
calls dataSource, wraps Result, tracks pagination"] + D --> E["ConversationsDataSourceImpl
calls CometChat SDK"] + E --> F["CometChat SDK → REST API → Response"] + +``` + +### Real-Time Updates + +```mermaid +graph TD + A["CometChat SDK — WebSocket
onTextMessageReceived / onTypingStarted"] --> B["ViewModel — SDK listener
processes event, updates internal list"] + B --> C["Emits new UIState.Content — updatedList"] + C --> D["UI recomposes / rebinds automatically"] + +``` + +### User Action (Delete Conversation) + +```mermaid +graph TD + A["UI — user swipes to delete"] --> B["ViewModel.deleteConversation"] + B --> C["DeleteConversationUseCase"] + C --> D["ConversationsRepositoryImpl"] + D --> E["DataSource → CometChat SDK → REST API → 200 OK"] + E --> F["ViewModel removes item → emits updated UIState"] + +``` + +## Component ↔ Core Mapping + +| UI Component | Core ViewModel | Use Cases | Repository | DataSource | +|---|---|---|---|---| +| Conversation List | `CometChatConversationsViewModel` | Get, Delete, Refresh | `ConversationsRepository` | `ConversationsDataSource` | +| Message List | `CometChatMessageListViewModel` | (message fetching) | `MessageListRepository` | `MessageListDataSource` | +| Message Composer | `CometChatMessageComposerViewModel` | SendText, SendMedia, SendCustom, Edit | `MessageComposerRepository` | `MessageComposerDataSource` | +| Message Header | `CometChatMessageHeaderViewModel` | — | `MessageHeaderRepository` | `MessageHeaderDataSource` | +| Users | `CometChatUsersViewModel` | FetchUsers, SearchUsers | `UsersRepository` | `UsersDataSource` | +| Groups | `CometChatGroupsViewModel` | FetchGroups, JoinGroup | `GroupsRepository` | `GroupsDataSource` | +| Group Members | `CometChatGroupMembersViewModel` | FetchMembers, Search, Ban, Kick, ChangeScope | `GroupMembersRepository` | `GroupMembersDataSource` | +| Call Logs | `CometChatCallLogsViewModel` | FetchCallLogs | `CallLogsRepository` | `CallLogsDataSource` | +| Call Buttons | `CometChatCallButtonsViewModel` | InitiateCall, StartGroupCall | `CallButtonsRepository` | `CallButtonsDataSource` | +| Reactions | `CometChatReactionListViewModel` | FetchReactions, RemoveReaction | `ReactionListRepository` | `ReactionListDataSource` | +| Message Info | `CometChatMessageInformationViewModel` | — | `MessageInformationRepository` | `MessageInformationDataSource` | + +## Events (Cross-Component Communication) + +The `CometChatEvents` singleton in `chatuikit-core` provides a typed event bus using Kotlin `SharedFlow` for communication between components that don't share a ViewModel: + +| Event Flow | Emitted When | +|---|---| +| `CometChatEvents.messageEvents` | Message sent, edited, deleted, reacted | +| `CometChatEvents.conversationEvents` | Conversation deleted | +| `CometChatEvents.groupEvents` | Group created, member added/removed/banned | +| `CometChatEvents.userEvents` | User blocked/unblocked | +| `CometChatEvents.callEvents` | Call initiated, accepted, rejected | +| `CometChatEvents.uiEvents` | UI-level events (show dialog, navigate) | + +See the [Events reference](/ui-kit/android/v6/events) for sealed class types and subscription examples. + +## Component-Level Overrides + +Every layer in the architecture is designed to be replaceable. You can override at the level that makes sense for your use case — from swapping the entire data source to just tweaking a single use case. + +### Override Points + +```mermaid +graph TD + A["UI Component"] --> B["ViewModel ← inject via custom Factory"] + B --> C["UseCase ← subclass (open classes)"] + C --> D["Repository ← implement interface"] + D --> E["DataSource ← implement interface"] +``` + +### 1. Custom Repository + +The most common override. Implement the repository interface and pass it to the factory. + +```kotlin +class OfflineUsersRepository : UsersRepository { + + private val cachedUsers = listOf(/* local data */) + + override suspend fun getUsers(request: UsersRequest): Result> { + return Result.success(cachedUsers) + } + + override fun hasMoreUsers(): Boolean = false +} +``` + +Wire it in: + + + +```kotlin +val factory = CometChatUsersViewModelFactory( + repository = OfflineUsersRepository(), + enableListeners = false +) +val viewModel = ViewModelProvider(this, factory)[CometChatUsersViewModel::class.java] + +val usersView = findViewById(R.id.users) +usersView.setViewModel(viewModel) +``` + + + +```kotlin +val factory = CometChatUsersViewModelFactory( + repository = OfflineUsersRepository(), + enableListeners = false +) +val viewModel: CometChatUsersViewModel = viewModel(factory = factory) + +CometChatUsers( + usersViewModel = viewModel +) +``` + + + +### 2. Custom DataSource + +Override at the lowest level to change how SDK calls are made — useful for caching, offline support, or wrapping a different backend. + +```kotlin +class CachedUsersDataSource( + private val sdkDataSource: UsersDataSourceImpl = UsersDataSourceImpl(), + private val cache: UserCache +) : UsersDataSource { + + override suspend fun fetchUsers(request: UsersRequest): List { + val cached = cache.get(request) + if (cached != null) return cached + + val users = sdkDataSource.fetchUsers(request) + cache.put(request, users) + return users + } +} +``` + +Then wrap it in the default repository implementation: + +```kotlin +val dataSource = CachedUsersDataSource(cache = myCache) +val repository = UsersRepositoryImpl(dataSource) +val factory = CometChatUsersViewModelFactory(repository = repository) +``` + +### 3. Custom Use Cases + +Use cases are `open` classes, so you can subclass them to add validation, logging, or transformation: + +```kotlin +class LoggingGetConversationsUseCase( + repository: ConversationsRepository +) : GetConversationsUseCase(repository) { + + override suspend operator fun invoke( + request: ConversationsRequest + ): Result> { + Log.d("Conversations", "Fetching conversations...") + val result = super.invoke(request) + result.onSuccess { Log.d("Conversations", "Fetched ${it.size} items") } + result.onFailure { Log.e("Conversations", "Fetch failed", it) } + return result + } +} +``` + +### 4. Passing a Custom ViewModel to the UI Component + +Both `chatuikit-jetpack` (Compose) and `chatuikit-kotlin` (XML Views) accept a pre-built ViewModel. This is the entry point for all overrides. + + + +```kotlin +class MyUsersActivity : AppCompatActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_users) + + val factory = CometChatUsersViewModelFactory( + repository = MyCustomUsersRepository() + ) + val viewModel = ViewModelProvider(this, factory)[CometChatUsersViewModel::class.java] + + val usersView = findViewById(R.id.users) + usersView.setViewModel(viewModel) + } +} +``` + + + +```kotlin +@Composable +fun MyUsersScreen() { + val factory = CometChatUsersViewModelFactory( + repository = MyCustomUsersRepository(), + enableListeners = true + ) + val viewModel: CometChatUsersViewModel = viewModel(factory = factory) + + CometChatUsers( + usersViewModel = viewModel, + style = CometChatUsersStyle.default(), + hideToolbar = false, + hideSearchBox = false + ) +} +``` + + + +### 5. Disabling Listeners for Previews and Testing + +Every factory accepts `enableListeners = false`. When disabled, the ViewModel won't register SDK listeners or UIKit event subscriptions — useful for Compose previews, unit tests, or showcase screens: + +```kotlin +val factory = CometChatConversationsViewModelFactory( + repository = FakeConversationRepository(), + enableListeners = false // No WebSocket listeners, no event subscriptions +) +``` + +### Override Summary by Component + +| Component | Factory Class | Repository Interface | Key Use Cases | +|---|---|---|---| +| Conversation List | `CometChatConversationsViewModelFactory` | `ConversationsRepository` | Get, Delete, Refresh | +| Users | `CometChatUsersViewModelFactory` | `UsersRepository` | FetchUsers, SearchUsers | +| Groups | `CometChatGroupsViewModelFactory` | `GroupsRepository` | FetchGroups, JoinGroup | +| Group Members | `CometChatGroupMembersViewModelFactory` | `GroupMembersRepository` | FetchMembers, Search, Ban, Kick, ChangeScope | +| Message List | `CometChatMessageListViewModelFactory` | `MessageListRepository` | (message fetching) | +| Message Composer | `CometChatMessageComposerViewModelFactory` | `MessageComposerRepository` | SendText, SendMedia, SendCustom, Edit | +| Call Logs | `CometChatCallLogsViewModelFactory` | `CallLogsRepository` | FetchCallLogs | +| Call Buttons | `CometChatCallButtonsViewModelFactory` | `CallButtonsRepository` | InitiateCall, StartGroupCall | +| Reactions | `CometChatReactionListViewModelFactory` | `ReactionListRepository` | FetchReactions, RemoveReaction | + +## Related + +- [Events](/ui-kit/android/v6/events) — Cross-component communication via `CometChatEvents` SharedFlow +- [Methods](/ui-kit/android/v6/methods) — UI Kit wrapper methods for init, auth, and messaging diff --git a/ui-kit/android/v6/call-buttons.mdx b/ui-kit/android/v6/call-buttons.mdx new file mode 100644 index 000000000..93d396843 --- /dev/null +++ b/ui-kit/android/v6/call-buttons.mdx @@ -0,0 +1,304 @@ +--- +title: "Call Buttons" +description: "Voice and video call buttons that initiate calls for a given user or group." +--- + +`CometChatCallButtons` renders voice and video call buttons and initiates calls for the bound `User` or `Group`. Place it in a `CometChatMessageHeader` or anywhere a call action is needed. + +--- + +## Where It Fits + +`CometChatCallButtons` is a utility component. Wire it into a `CometChatMessageHeader` or place it standalone wherever a call action is needed. + + + + +```xml activity_chat.xml lines + +``` + +```kotlin lines +val callButtons = findViewById(R.id.call_buttons) +callButtons.setUser(user) +``` + + + + +```kotlin lines +CometChatCallButtons( + user = user +) +``` + + + + +--- + +## Quick Start + + + + +Add to your layout XML: + +```xml lines + +``` + +Set a `User` or `Group` — required before calls can be initiated: + +```kotlin lines +override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.your_layout) + + val callButtons = findViewById(R.id.call_buttons) + callButtons.setUser(user) + // or callButtons.setGroup(group) +} +``` + +Or programmatically: + +```kotlin lines +override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val callButtons = CometChatCallButtons(this) + callButtons.setUser(user) + setContentView(callButtons) +} +``` + + + + +```kotlin lines +@Composable +fun CallButtonsScreen() { + CometChatCallButtons( + user = user + // or group = group + ) +} +``` + + + + +Prerequisites: CometChat SDK initialized with `CometChatUIKit.init()`, a user logged in, and the UI Kit dependency added. + +> You must call `setUser(User)` or `setGroup(Group)` before the buttons can initiate a call. Without a target, button clicks have no effect. + +--- + +## Actions and Events + +### Callback Methods + +#### `onVoiceCallClick` + +Fires when the voice call button is tapped. Replaces the default behavior of initiating an audio call. + + + + +```kotlin lines +callButtons.setOnVoiceCallClick { user, group -> + // Custom voice call logic +} +``` + + + + +```kotlin lines +CometChatCallButtons( + user = user, + onVoiceCallClick = { u, g -> + // Custom voice call logic + } +) +``` + + + + +#### `onVideoCallClick` + +Fires when the video call button is tapped. Replaces the default behavior of initiating a video call. + + + + +```kotlin lines +callButtons.setOnVideoCallClick { user, group -> + // Custom video call logic +} +``` + + + + +```kotlin lines +CometChatCallButtons( + user = user, + onVideoCallClick = { u, g -> + // Custom video call logic + } +) +``` + + + + +#### `onError` + +Fires on internal errors (network failure, auth issue, SDK exception). + + + + +```kotlin lines +callButtons.setOnError { exception -> + Log.e("CallButtons", "Error: ${exception.message}") +} +``` + + + + +```kotlin lines +CometChatCallButtons( + user = user, + onError = { exception -> + Log.e("CallButtons", "Error: ${exception.message}") + } +) +``` + + + + +### Global UI Events (CometChatCallEvents) + +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccOutgoingCall` | An outgoing call is initiated | `Call` | +| `ccCallAccepted` | A call is accepted by the recipient | `Call` | +| `ccCallRejected` | A call is rejected by the recipient | `Call` | +| `ccCallEnded` | A call is ended | `Call` | + +--- + +## Functionality + +| Method (Kotlin XML) | Compose Parameter | Description | +| --- | --- | --- | +| `setUser(user)` | `user = user` | Set the user to call (required for 1-on-1) | +| `setGroup(group)` | `group = group` | Set the group to call (required for group calls) | +| `setOnVoiceCallClick { }` | `onVoiceCallClick = { }` | Override voice call button behavior | +| `setOnVideoCallClick { }` | `onVideoCallClick = { }` | Override video call button behavior | +| `setOnError { }` | `onError = { }` | Error callback | +| `setVoiceCallButtonVisibility(View.GONE)` | `hideVoiceCallButton = true` | Toggle voice call button | +| `setVideoCallButtonVisibility(View.GONE)` | `hideVideoCallButton = true` | Toggle video call button | + +--- + +## Style + + + + +Define a custom style in `themes.xml`: + +```xml themes.xml lines + +``` + +```kotlin lines +callButtons.setStyle(R.style.CustomCallButtonsStyle) +``` + + + + +```kotlin lines +CometChatCallButtons( + user = user, + style = CometChatCallButtonsStyle.default().copy( + voiceCallIconTint = Color(0xFF4CAF50), + videoCallIconTint = Color(0xFF2196F3), + voiceCallBackgroundColor = Color(0xFFE8F5E9), + videoCallBackgroundColor = Color(0xFFE3F2FD) + ) +) +``` + + + + +See [Component Styling](/ui-kit/android/v6/component-styling) for the full reference. + +--- + +## ViewModel + +```kotlin lines +val viewModel = ViewModelProvider(this) + .get(CometChatCallButtonsViewModel::class.java) +``` + + + + +```kotlin lines +callButtons.setViewModel(viewModel) +``` + + + + +```kotlin lines +CometChatCallButtons( + user = user, + callButtonsViewModel = viewModel +) +``` + + + + +See [ViewModel & Data](/ui-kit/android/v6/customization-viewmodel-data) for state observation and custom repositories. + +--- + +## Next Steps + + + + View call history + + + Incoming call notification with accept/reject + + + Outgoing call screen with end-call button + + + Display user/group info in the toolbar + + diff --git a/ui-kit/android/v6/call-features.mdx b/ui-kit/android/v6/call-features.mdx new file mode 100644 index 000000000..ad738b447 --- /dev/null +++ b/ui-kit/android/v6/call-features.mdx @@ -0,0 +1,200 @@ +--- +title: "Call" +description: "Add one-on-one and group audio/video calling to your Android app using the CometChat Calls SDK and UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Kotlin (XML Views) | `com.cometchat:chatuikit-kotlin-android` + `com.cometchat:calls-sdk-android` | +| Jetpack Compose | `com.cometchat:chatuikit-compose-android` + `com.cometchat:calls-sdk-android` | +| Required setup | `CometChatUIKit.init()` then `CometChatUIKit.login()` — Calls SDK must also be installed | +| Call features | Incoming Call, Outgoing Call, Call Logs, Call Buttons, Ongoing Call | +| Key components | `CometChatCallButtons`, `CometChatIncomingCall`, `CometChatOutgoingCall`, `CometChatCallLogs`, `CometChatOngoingCall` | +| Auto-detection | UI Kit automatically detects the Calls SDK and enables call UI components | +| Related | [Getting Started](/ui-kit/android/v6/getting-started), [Core Features](/ui-kit/android/v6/core-features), [Call Log Details Guide](/ui-kit/android/v6/guide-call-log-details) | + + + +CometChat's Calls feature allows you to seamlessly integrate one-on-one as well as group audio and video calling capabilities into your application. This document provides a technical overview of these features, as implemented in the Android UI Kit. + +## Integration + +First, make sure that you've correctly integrated the UI Kit library into your project. If you haven't done this yet or are facing difficulties, refer to our [Getting Started](/ui-kit/android/v6/getting-started) guide. + +Once you've successfully integrated the UI Kit, the next step is to add the CometChat Calls SDK to your project. This is necessary to enable the calling features in the UI Kit. + +### Step 1: Add Calls SDK Dependency + +Add the following dependency to your `build.gradle.kts` file: + + + +```kotlin build.gradle.kts +dependencies { + implementation("com.cometchat:chatuikit-kotlin-android:6.0.0") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") +} +``` + + + +```kotlin build.gradle.kts +dependencies { + implementation("com.cometchat:chatuikit-compose-android:6.0.0") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") +} +``` + + + +After adding this dependency, sync your project. The Android UI Kit will automatically detect the Calls SDK and activate the calling features. + +### Step 2: Verify Call Buttons Appear + +Once the Calls SDK is integrated, you will see the `CometChatCallButtons` component automatically rendered in the [MessageHeader](/ui-kit/android/v6/message-header) component. This provides users with quick access to initiate audio and video calls. + + + + + +### Step 3: Add Call Listener for Incoming Calls + +To receive incoming calls globally in your app, you will need to add a `CallListener`. This should be added before you initialize the CometChat UI Kit. We recommend creating a custom Application class and adding the call listener there. + +When an incoming call is received, you can display the `CometChatIncomingCall` component using the current activity context. + + + +```kotlin +class BaseApplication : Application() { + + companion object { + private val LISTENER_ID = "${BaseApplication::class.java.simpleName}${System.currentTimeMillis()}" + } + + override fun onCreate() { + super.onCreate() + + CometChat.addCallListener(LISTENER_ID, object : CometChat.CallListener { + override fun onIncomingCallReceived(call: Call) { + // Get the current activity context + val currentActivity = getCurrentActivity() // Implement this method + + currentActivity?.let { + // Create and display the incoming call component + val incomingCallView = CometChatIncomingCall(it) + incomingCallView.call = call + incomingCallView.fitsSystemWindows = true + incomingCallView.onError = OnError { exception -> + // Handle errors + } + + // Display the component (e.g., as dialog or snackbar) + } + } + + override fun onOutgoingCallAccepted(call: Call) { + // Handle outgoing call acceptance + } + + override fun onOutgoingCallRejected(call: Call) { + // Handle outgoing call rejection + } + + override fun onIncomingCallCancelled(call: Call) { + // Handle incoming call cancellation + } + }) + } +} +``` + + + +```kotlin +class BaseApplication : Application() { + + companion object { + private val LISTENER_ID = "${BaseApplication::class.java.simpleName}${System.currentTimeMillis()}" + } + + override fun onCreate() { + super.onCreate() + + CometChat.addCallListener(LISTENER_ID, object : CometChat.CallListener { + override fun onIncomingCallReceived(call: Call) { + CometChatCallActivity.launchIncomingCallScreen(this@BaseApplication, call, null) + // Pass null or IncomingCallConfiguration if need to configure CometChatIncomingCall component + } + + override fun onOutgoingCallAccepted(call: Call) { + // Handle outgoing call acceptance + } + + override fun onOutgoingCallRejected(call: Call) { + // Handle outgoing call rejection + } + + override fun onIncomingCallCancelled(call: Call) { + // Handle incoming call cancellation + } + }) + } +} +``` + + + +## Call Components + +The CometChat Android UI Kit provides five main components for implementing calling features in your app. Each component handles a specific part of the calling experience. + +### Call Buttons + +The `CometChatCallButtons` component provides users with quick access to initiate audio and video calls. This component is automatically rendered in the [MessageHeader](/ui-kit/android/v6/message-header) when the Calls SDK is integrated. + + + + + +[Learn more about Call Buttons →](/ui-kit/android/v6/call-buttons) + +### Incoming Call + +The `CometChatIncomingCall` component displays when a user receives an incoming call. It provides a full-screen interface showing caller information and call controls. + + + + + +[Learn more about Incoming Call →](/ui-kit/android/v6/incoming-call) + +### Outgoing Call + +The `CometChatOutgoingCall` component manages the outgoing call experience. It displays while waiting for the recipient to answer and automatically transitions to the active call screen once accepted. + + + + + +[Learn more about Outgoing Call →](/ui-kit/android/v6/outgoing-call) + +### Call Logs + +The `CometChatCallLogs` component displays a history of all call activities, including missed, received, and dialed calls. Users can view call details and initiate new calls from the log. + + + + + +[Learn more about Call Logs →](/ui-kit/android/v6/call-logs) + +### Ongoing Call + +The `CometChatOngoingCall` component renders the active call screen with video feeds, mute/unmute controls, camera toggle, and end-call actions. + +### Call Log Details + +For detailed information about individual calls, including participants, join/leave history, and recordings, see the [Call Log Details](/ui-kit/android/v6/guide-call-log-details) guide. diff --git a/ui-kit/android/v6/call-logs.mdx b/ui-kit/android/v6/call-logs.mdx new file mode 100644 index 000000000..c15a0a8b2 --- /dev/null +++ b/ui-kit/android/v6/call-logs.mdx @@ -0,0 +1,862 @@ +--- +title: "Call Logs" +description: "Scrollable list of call logs for the logged-in user with caller names, avatars, call status, and timestamps." +--- + +`CometChatCallLogs` renders a scrollable list of call logs for the logged-in user with caller names, avatars, call status indicators, and timestamps. + + + + + +--- + +## Where It Fits + +`CometChatCallLogs` is a list component. It renders the user's call history and emits the selected `CallLog` via `onItemClick`. Use it as a standalone call history screen or as a tab in a tabbed layout alongside conversations and contacts. + + + + +```xml activity_call_logs.xml lines + +``` + +```kotlin lines +val callLogs = findViewById(R.id.call_logs) + +callLogs.setOnItemClick { callLog -> + // Navigate to call detail or initiate call +} +``` + + + + +```kotlin lines +CometChatCallLogs( + modifier = Modifier.fillMaxSize(), + onItemClick = { callLog -> + // Navigate to call detail or initiate call + } +) +``` + + + + +--- + +## Quick Start + + + + +Add to your layout XML: + +```xml lines + +``` + +Or programmatically: + +```kotlin lines +override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(CometChatCallLogs(this)) +} +``` + + + + +```kotlin lines +@Composable +fun CallLogsScreen() { + CometChatCallLogs( + modifier = Modifier.fillMaxSize() + ) +} +``` + + + + +Prerequisites: CometChat SDK initialized with `CometChatUIKit.init()`, a user logged in, the UI Kit dependency added, and the CometChat Calls SDK configured. + +Or in a Fragment: + + + + +```kotlin lines +override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + return CometChatCallLogs(requireContext()) +} +``` + + + + +```kotlin lines +override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + return ComposeView(requireContext()).apply { + setContent { CometChatCallLogs() } + } +} +``` + + + + +--- + +## Filtering Call Logs + + + + +Pass a `CallLogRequest.CallLogRequestBuilder` to control what loads: + +```kotlin lines +callLogs.setCallLogRequestBuilder( + CallLogRequest.CallLogRequestBuilder() + .setLimit(20) + .setCallCategory(CometChatConstants.CALL_CATEGORY_CALL) +) +``` + + + + +```kotlin lines +CometChatCallLogs( + callLogRequestBuilder = CallLogRequest.CallLogRequestBuilder() + .setLimit(20) + .setCallCategory(CometChatConstants.CALL_CATEGORY_CALL) +) +``` + + + + +### Filter Recipes + +| Recipe | Builder method | +| --- | --- | +| Limit per page | `.setLimit(10)` | +| Audio calls only | `.setCallType(CometChatConstants.CALL_TYPE_AUDIO)` | +| Video calls only | `.setCallType(CometChatConstants.CALL_TYPE_VIDEO)` | +| Call category | `.setCallCategory(CometChatConstants.CALL_CATEGORY_CALL)` | + + +Pass the builder object, not the result of `.build()`. The component calls `.build()` internally. Default page size is 30 with infinite scroll. + + +--- + +## Actions and Events + +### Callback Methods + +#### `onItemClick` + +Fires when a call log row is tapped. Primary navigation hook. + + + + +```kotlin lines +callLogs.setOnItemClick { callLog -> + // Navigate to call detail +} +``` + + + + +```kotlin lines +CometChatCallLogs( + onItemClick = { callLog -> + // Navigate to call detail + } +) +``` + + + + +> Replaces the default item-click behavior. Your custom lambda executes instead of the built-in navigation. + +#### `onItemLongClick` + +Fires when a call log row is long-pressed. + + + + +```kotlin lines +callLogs.setOnItemLongClick { callLog -> + // Show context menu +} +``` + + + + +```kotlin lines +CometChatCallLogs( + onItemLongClick = { callLog -> + // Show context menu + } +) +``` + + + + +#### `onBackPress` + +Fires when the user presses the back button in the toolbar. + + + + +```kotlin lines +callLogs.setOnBackPress { + finish() +} +``` + + + + +```kotlin lines +CometChatCallLogs( + onBackPress = { /* navigate back */ } +) +``` + + + + +#### `onError` + +Fires on internal errors (network failure, auth issue, SDK exception). + + + + +```kotlin lines +callLogs.setOnError { exception -> + Log.e("CallLogs", "Error: ${exception.message}") +} +``` + + + + +```kotlin lines +CometChatCallLogs( + onError = { exception -> + Log.e("CallLogs", "Error: ${exception.message}") + } +) +``` + + + + +#### `onLoad` + +Fires when the list is successfully fetched and loaded. + + + + +```kotlin lines +callLogs.setOnLoad { callLogList -> + Log.d("CallLogs", "Loaded ${callLogList.size}") +} +``` + + + + +```kotlin lines +CometChatCallLogs( + onLoad = { callLogList -> + Log.d("CallLogs", "Loaded ${callLogList.size}") + } +) +``` + + + + +#### `onEmpty` + +Fires when the list is empty after loading. + + + + +```kotlin lines +callLogs.setOnEmpty { + Log.d("CallLogs", "No call logs") +} +``` + + + + +```kotlin lines +CometChatCallLogs( + onEmpty = { /* no call logs */ } +) +``` + + + + +--- + +## Functionality + +| Method (Kotlin XML) | Compose Parameter | Description | +| --- | --- | --- | +| `setBackIconVisibility(View.VISIBLE)` | `hideBackIcon = false` | Toggle back button | +| `setToolbarVisibility(View.GONE)` | `hideToolbar = true` | Toggle toolbar | +| `setSeparatorVisibility(View.GONE)` | `hideSeparator = true` | Toggle list separators | +| `setTitle("Call History")` | `title = "Call History"` | Custom toolbar title | + +--- + +## Custom View Slots + +### Leading View + +Replace the avatar / left section. + + + + + + + + +```kotlin lines +callLogs.setLeadingView(object : CallLogsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return ImageView(context).apply { + layoutParams = ViewGroup.LayoutParams(48.dp, 48.dp) + } + } + + override fun bindView( + context: Context, createdView: View, callLog: CallLog, + holder: RecyclerView.ViewHolder, callLogList: List, position: Int + ) { + val imageView = createdView as ImageView + // Load caller avatar + } +}) +``` + + + + +```kotlin lines +CometChatCallLogs( + leadingView = { callLog -> + CometChatAvatar( + imageUrl = callLog.initiator?.avatar, + name = callLog.initiator?.name + ) + } +) +``` + + + + +### Title View + +Replace the name / title text. + + + + + + + + +```kotlin lines +callLogs.setTitleView(object : CallLogsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context) + } + + override fun bindView( + context: Context, createdView: View, callLog: CallLog, + holder: RecyclerView.ViewHolder, callLogList: List, position: Int + ) { + (createdView as TextView).text = callLog.initiator?.name ?: "" + } +}) +``` + + + + +```kotlin lines +CometChatCallLogs( + titleView = { callLog -> + Text( + text = callLog.initiator?.name ?: "", + style = CometChatTheme.typography.heading4Medium + ) + } +) +``` + + + + +### Subtitle View + +Replace the subtitle text below the caller's name. + + + + + + + + +```kotlin lines +callLogs.setSubtitleView(object : CallLogsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context).apply { maxLines = 1; ellipsize = TextUtils.TruncateAt.END } + } + + override fun bindView( + context: Context, createdView: View, callLog: CallLog, + holder: RecyclerView.ViewHolder, callLogList: List, position: Int + ) { + (createdView as TextView).text = callLog.status ?: "Unknown" + } +}) +``` + + + + +```kotlin lines +CometChatCallLogs( + subtitleView = { callLog -> + Text( + text = callLog.status ?: "Unknown", + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } +) +``` + + + + +### Trailing View + +Replace the right section of each call log item. + + + + + + + + +```kotlin lines +callLogs.setTrailingView(object : CallLogsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context) + } + + override fun bindView( + context: Context, createdView: View, callLog: CallLog, + holder: RecyclerView.ViewHolder, callLogList: List, position: Int + ) { + (createdView as TextView).text = SimpleDateFormat("h:mm a", Locale.getDefault()) + .format(Date(callLog.initiatedAt * 1000)) + } +}) +``` + + + + +```kotlin lines +CometChatCallLogs( + trailingView = { callLog -> + Text( + text = SimpleDateFormat("h:mm a", Locale.getDefault()) + .format(Date(callLog.initiatedAt * 1000)) + ) + } +) +``` + + + + +### Item View + +Replace the entire list item row. + + + + + + + + +```kotlin lines +callLogs.setItemView(object : CallLogsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return LayoutInflater.from(context).inflate(R.layout.custom_call_log_item, null) + } + + override fun bindView( + context: Context, createdView: View, callLog: CallLog, + holder: RecyclerView.ViewHolder, callLogList: List, position: Int + ) { + val avatar = createdView.findViewById(R.id.custom_avatar) + val title = createdView.findViewById(R.id.tvName) + title.text = callLog.initiator?.name + avatar.setAvatar(callLog.initiator?.name, callLog.initiator?.avatar) + } +}) +``` + + + + +```kotlin lines +CometChatCallLogs( + itemView = { callLog -> + Row( + modifier = Modifier.fillMaxWidth().padding(12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + CometChatAvatar(imageUrl = callLog.initiator?.avatar, name = callLog.initiator?.name) + Spacer(Modifier.width(12.dp)) + Column(modifier = Modifier.weight(1f)) { + Text(callLog.initiator?.name ?: "", style = CometChatTheme.typography.heading4Medium) + Text(callLog.status ?: "", style = CometChatTheme.typography.body3Regular) + } + } + } +) +``` + + + + +### State Views + + + + +```kotlin lines +callLogs.setEmptyView(R.layout.custom_empty_view) +callLogs.setErrorView(R.layout.custom_error_view) +callLogs.setLoadingView(R.layout.custom_loading_view) +``` + + + + +```kotlin lines +CometChatCallLogs( + emptyView = { Text("No call logs") }, + errorView = { onRetry -> Button(onClick = onRetry) { Text("Retry") } }, + loadingView = { CircularProgressIndicator() } +) +``` + + + + +### Overflow Menu + + + + +```kotlin lines +callLogs.setOverflowMenu(ImageButton(context).apply { + setImageResource(R.drawable.ic_filter) + setOnClickListener { /* show filter */ } +}) +``` + + + + +```kotlin lines +CometChatCallLogs( + overflowMenu = { + IconButton(onClick = { /* show filter */ }) { + Icon(painterResource(R.drawable.ic_filter), "Filter") + } + } +) +``` + + + + +--- + +## Menu Options + + + + +```kotlin lines +// Replace all options +callLogs.setOptions { context, callLog -> + listOf( + CometChatPopupMenu.MenuItem(id = "delete", name = "Delete", onClick = { /* ... */ }), + CometChatPopupMenu.MenuItem(id = "callback", name = "Call Back", onClick = { /* ... */ }) + ) +} + +// Append to defaults +callLogs.setAddOptions { context, callLog -> + listOf( + CometChatPopupMenu.MenuItem(id = "info", name = "Info", onClick = { /* ... */ }) + ) +} +``` + + + + +```kotlin lines +CometChatCallLogs( + options = { context, callLog -> + listOf( + MenuItem(id = "delete", name = "Delete", onClick = { /* ... */ }), + MenuItem(id = "callback", name = "Call Back", onClick = { /* ... */ }) + ) + }, + addOptions = { context, callLog -> + listOf(MenuItem(id = "info", name = "Info", onClick = { /* ... */ })) + } +) +``` + + + + +--- + +## Common Patterns + +### Minimal list — hide all chrome + + + + +```kotlin lines +callLogs.setToolbarVisibility(View.GONE) +callLogs.setSeparatorVisibility(View.GONE) +``` + + + + +```kotlin lines +CometChatCallLogs( + hideToolbar = true, + hideSeparator = true +) +``` + + + + +### Audio calls only + + + + +```kotlin lines +callLogs.setCallLogRequestBuilder( + CallLogRequest.CallLogRequestBuilder() + .setCallType(CometChatConstants.CALL_TYPE_AUDIO) +) +``` + + + + +```kotlin lines +CometChatCallLogs( + callLogRequestBuilder = CallLogRequest.CallLogRequestBuilder() + .setCallType(CometChatConstants.CALL_TYPE_AUDIO) +) +``` + + + + +### Video calls only + + + + +```kotlin lines +callLogs.setCallLogRequestBuilder( + CallLogRequest.CallLogRequestBuilder() + .setCallType(CometChatConstants.CALL_TYPE_VIDEO) +) +``` + + + + +```kotlin lines +CometChatCallLogs( + callLogRequestBuilder = CallLogRequest.CallLogRequestBuilder() + .setCallType(CometChatConstants.CALL_TYPE_VIDEO) +) +``` + + + + +--- + +## Advanced Methods + +### ViewModel Access + +```kotlin lines +val factory = CometChatCallLogsViewModelFactory() +val viewModel = ViewModelProvider(this, factory) + .get(CometChatCallLogsViewModel::class.java) +``` + + + + +```kotlin lines +callLogs.setViewModel(viewModel) +``` + + + + +```kotlin lines +CometChatCallLogs( + callLogsViewModel = viewModel +) +``` + + + + +See [ViewModel & Data](/ui-kit/android/v6/customization-viewmodel-data) for ListOperations, state observation, and custom repositories. + +--- + +## Style + + + + + + + + +Define a custom style in `themes.xml`: + +```xml themes.xml lines + + + + + +``` + + + + +```kotlin lines +CometChatCallLogs( + style = CometChatCallLogsStyle.default().copy( + backgroundColor = Color(0xFFF5F5F5), + titleTextColor = Color(0xFF141414), + itemStyle = CometChatCallLogsItemStyle.default().copy( + backgroundColor = Color.White, + titleTextColor = Color(0xFF141414), + subtitleTextColor = Color(0xFF727272), + avatarStyle = CometChatAvatarStyle.default().copy(cornerRadius = 12.dp) + ) + ) +) +``` + + + + +### Style Properties + +| Property | Description | +| --- | --- | +| `backgroundColor` | List background color | +| `titleTextColor` | Toolbar title color | +| `itemStyle.backgroundColor` | Row background | +| `itemStyle.titleTextColor` | Caller name color | +| `itemStyle.subtitleTextColor` | Call status text color | +| `itemStyle.separatorColor` | Row separator color | +| `itemStyle.avatarStyle` | Avatar appearance | + +See [Component Styling](/ui-kit/android/v6/component-styling) for the full reference. + +--- + +## Next Steps + + + + Voice and video calling overview + + + Browse recent conversations + + + Detailed styling reference with screenshots + + + Custom ViewModels, repositories, and ListOperations + + diff --git a/ui-kit/android/v6/calling-integration.mdx b/ui-kit/android/v6/calling-integration.mdx new file mode 100644 index 000000000..825f1692a --- /dev/null +++ b/ui-kit/android/v6/calling-integration.mdx @@ -0,0 +1,123 @@ +--- +title: "Calling Integration" +description: "Add voice and video calling to your Android UI Kit application using chatuikit-kotlin or chatuikit-jetpack." +--- + +## Overview + +This guide walks you through adding voice and video calling capabilities to your Android application using the CometChat UI Kit. + + +Make sure you've completed the [Getting Started](/ui-kit/android/v6/getting-started) guide before proceeding. + + +## Add the Calls SDK + +Add the CometChat Calls SDK dependency alongside your chosen UI Kit module: + + + +```kotlin build.gradle.kts +dependencies { + implementation("com.cometchat:chatuikit-kotlin-android:6.0.0") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") +} +``` + + + +```kotlin build.gradle.kts +dependencies { + implementation("com.cometchat:chatuikit-compose-android:6.0.0") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") +} +``` + + + +After adding this dependency, the Android UI Kit will automatically detect it and activate the calling features. You will see the `CometChatCallButtons` component rendered in the [MessageHeader](/ui-kit/android/v6/message-header) component. + + + + + +## Set Up Call Listener + +To receive incoming calls globally in your app, add a `CallListener` before initializing the CometChat UI Kit. We recommend creating a custom Application class: + + + +```kotlin +class BaseApplication : Application() { + companion object { + private val LISTENER_ID = "${BaseApplication::class.java.simpleName}${System.currentTimeMillis()}" + } + + override fun onCreate() { + super.onCreate() + CometChat.addCallListener(LISTENER_ID, object : CometChat.CallListener { + override fun onIncomingCallReceived(call: Call) { + // Get the current activity context + val currentActivity = getCurrentActivity() // Implement this method + + currentActivity?.let { + val incomingCallView = CometChatIncomingCall(it) + incomingCallView.call = call + incomingCallView.fitsSystemWindows = true + incomingCallView.onError = OnError { exception -> + // Handle errors + } + + // Display the component (e.g., as dialog or full-screen overlay) + } + } + + override fun onOutgoingCallAccepted(call: Call) { + // Handle accepted outgoing call + } + + override fun onOutgoingCallRejected(call: Call) { + // Handle rejected outgoing call + } + + override fun onIncomingCallCancelled(call: Call) { + // Handle cancelled incoming call + } + }) + } +} +``` + + + +```kotlin +class BaseApplication : Application() { + companion object { + private val LISTENER_ID = "${BaseApplication::class.java.simpleName}${System.currentTimeMillis()}" + } + + override fun onCreate() { + super.onCreate() + CometChat.addCallListener(LISTENER_ID, object : CometChat.CallListener { + override fun onIncomingCallReceived(call: Call) { + CometChatCallActivity.launchIncomingCallScreen(this@BaseApplication, call, null) + // Pass null or IncomingCallConfiguration if need to configure CometChatIncomingCall component + } + + override fun onOutgoingCallAccepted(call: Call) { + // Handle accepted outgoing call + } + + override fun onOutgoingCallRejected(call: Call) { + // Handle rejected outgoing call + } + + override fun onIncomingCallCancelled(call: Call) { + // Handle cancelled incoming call + } + }) + } +} +``` + + diff --git a/ui-kit/android/v6/color-resources.mdx b/ui-kit/android/v6/color-resources.mdx new file mode 100644 index 000000000..89d9e8684 --- /dev/null +++ b/ui-kit/android/v6/color-resources.mdx @@ -0,0 +1,219 @@ +--- +title: "Color Resources" +description: "Review and override the default UI Kit color palette for consistent light and dark mode styling." +--- + + + +| Field | Value | +| --- | --- | +| Kotlin XML Views | Colors defined in `res/values/color.xml` (light) and `res/values-night/color.xml` (dark), overridable via theme attributes or `CometChatTheme.set*()` | +| Jetpack Compose | Colors provided via `lightColorScheme()` and `darkColorScheme()` factory functions, customizable via `.copy()` | +| Key tokens | `primary`, `backgroundColor1–4`, `textColorPrimary/Secondary/Tertiary`, `strokeColorDefault/Light/Dark`, `successColor`, `errorColor`, `warningColor`, `infoColor` | +| Related | [Theme Introduction](/ui-kit/android/v6/theme-introduction) · [Component Styling](/ui-kit/android/v6/component-styling) | + + + +The UI Kit ships with a complete color palette for light and dark modes. This page documents the default values and how to override them. + +--- + +## Color Categories + +The palette is organized into these groups: + +| Category | Tokens | Purpose | +| --- | --- | --- | +| Primary | `primary` | Brand color for buttons, highlights, interactive elements | +| Neutral | `neutral50` – `neutral900` | Grayscale ramp for backgrounds, text, borders | +| Alert | `success`, `error`, `warning`, `info`, `messageRead` | Status indicators | +| Background | `backgroundColor1` – `backgroundColor4` | Surface/panel backgrounds (derived from neutrals) | +| Stroke | `strokeColorDefault`, `strokeColorLight`, `strokeColorDark`, `strokeColorHighlight` | Borders and dividers | +| Text | `textColorPrimary`, `textColorSecondary`, `textColorTertiary`, `textColorDisabled`, `textColorWhite`, `textColorHighlight` | Typography colors | +| Icon | `iconTintPrimary`, `iconTintSecondary`, `iconTintTertiary`, `iconTintWhite`, `iconTintHighlight` | Icon tints | +| Button | `primaryButtonBackground`, `primaryButtonText`, `secondaryButtonBackground`, `secondaryButtonText` | Button colors | + +--- + +## Default Light Mode Palette + + + + +Defined in `chatuikit-kotlin/src/main/res/values/color.xml`: + +```xml color.xml lines + +#6852D6 + + +#FFFFFF +#FAFAFA +#F5F5F5 +#E8E8E8 +#DCDCDC +#A1A1A1 +#727272 +#5B5B5B +#434343 +#141414 + + +#0B7BEA +#09C26F +#FFAB00 +#F44649 +#56E8A7 +``` + + + + +Provided by `lightColorScheme()` in `CometChatColorScheme.kt`: + +```kotlin lines +import com.cometchat.uikit.compose.theme.lightColorScheme + +// Default light color scheme +val colors = lightColorScheme() + +// Key defaults: +// primary = Color(0xFF6852D6) +// neutralColor50 = Color(0xFFFFFFFF) +// neutralColor900 = Color(0xFF141414) +// successColor = Color(0xFF09C26F) +// errorColor = Color(0xFFF44649) +// warningColor = Color(0xFFFFAB00) +// infoColor = Color(0xFF0B7BEA) +``` + + + + +--- + +## Default Dark Mode Palette + + + + +Defined in `chatuikit-kotlin/src/main/res/values-night/color.xml`. Note how neutral values are inverted: + +```xml values-night/color.xml lines + +#6852D6 + + +#141414 +#1A1A1A +#272727 +#383838 +#4C4C4C +#858585 +#989898 +#A8A8A8 +#C8C8C8 +#FFFFFF + + +#0D66BF +#0B9F5D +#D08D04 +#C73C3E +#56E8A7 +``` + +Android automatically uses `values-night` resources when the system is in dark mode. + + + + +Provided by `darkColorScheme()`: + +```kotlin lines +import com.cometchat.uikit.compose.theme.darkColorScheme + +// Default dark color scheme +val colors = darkColorScheme() + +// Key defaults (neutrals inverted): +// primary = Color(0xFF6852D6) +// neutralColor50 = Color(0xFF141414) +// neutralColor900 = Color(0xFFFFFFFF) +// successColor = Color(0xFF0B9F5D) +// errorColor = Color(0xFFC73C3E) +``` + + + + +--- + +## Override Colors + + + + +Override via XML theme attributes in `themes.xml`: + +```xml themes.xml lines + +``` + +Or programmatically via `CometChatTheme`: + +```kotlin lines +CometChatTheme.setPrimaryColor(Color.parseColor("#F76808")) +CometChatTheme.setBackgroundColor1(Color.parseColor("#FFFFFF")) +CometChatTheme.setTextColorPrimary(Color.parseColor("#000000")) +CometChatTheme.setStrokeColorDefault(Color.parseColor("#E0E0E0")) +``` + + + + +Customize via `.copy()` on the factory functions: + +```kotlin lines +val customColors = lightColorScheme().copy( + primary = Color(0xFFF76808), + backgroundColor1 = Color(0xFFFFFFFF), + textColorPrimary = Color(0xFF000000), + strokeColorDefault = Color(0xFFE0E0E0) +) + +CometChatTheme(colorScheme = customColors) { + // Your content +} +``` + + + + + + + + +--- + +## Derived Colors + +Background, stroke, text, and icon colors are derived from the neutral scale by default: + +| Token | Light Mode Default | Dark Mode Default | +| --- | --- | --- | +| `backgroundColor1` | `neutral50` (#FFFFFF) | `neutral50` (#141414) | +| `backgroundColor2` | `neutral100` (#FAFAFA) | `neutral100` (#1A1A1A) | +| `textColorPrimary` | `neutral900` (#141414) | `neutral900` (#FFFFFF) | +| `textColorSecondary` | `neutral600` (#727272) | `neutral600` (#989898) | +| `strokeColorDefault` | `neutral200` (#F5F5F5) | `neutral200` (#272727) | +| `strokeColorLight` | `neutral300` (#E8E8E8) | `neutral300` (#383838) | +| `iconTintPrimary` | `neutral900` (#141414) | `neutral900` (#FFFFFF) | +| `iconTintHighlight` | `primary` (#6852D6) | `primary` (#6852D6) | + +This means overriding a neutral color automatically updates all tokens that reference it. diff --git a/ui-kit/android/v6/component-styling.mdx b/ui-kit/android/v6/component-styling.mdx new file mode 100644 index 000000000..d1313cc3b --- /dev/null +++ b/ui-kit/android/v6/component-styling.mdx @@ -0,0 +1,1731 @@ +--- +title: "Component Styling" +description: "Style CometChat UI Kit components using XML theme attributes or Compose style data classes." +--- + + + +| Field | Value | +| --- | --- | +| Kotlin XML Views | Override XML styles in `themes.xml` extending component parent styles (e.g., `CometChatConversationsStyle`), assign via theme attributes | +| Jetpack Compose | Pass style data classes as parameters (e.g., `CometChatConversationsStyle`, `CometChatMessageListStyle`) with `.default()` and `.copy()` | +| Pattern (XML) | Create custom style → extend parent → assign to `AppTheme` via theme attribute | +| Pattern (Compose) | Call `ComponentStyle.default().copy(property = value)` → pass as `style` parameter | +| Related | [Theme Introduction](/ui-kit/android/v6/theme-introduction) · [Color Resources](/ui-kit/android/v6/color-resources) · [Message Bubble Styling](/ui-kit/android/v6/message-bubble-styling) | + + + +This page shows how to style CometChat UI Kit components in Android. It is written for Android developers customizing UI Kit v6. + +## When to use this + +- You want UI Kit screens (lists, headers, and message UI) to match your brand colors and typography. +- You need to customize calling and AI UI components without rebuilding UI from scratch. +- You prefer centralized styling through `res/values/themes.xml` (XML Views) or style data classes (Compose). +- You want consistent iconography by supplying your own vector drawables. +- You need a repeatable pattern that can be applied across components. + +## Prerequisites + +- CometChat Android UI Kit v6 installed in your app. +- Your app theme extends `CometChatTheme.DayNight` (for XML Views). +- You can edit `res/values/themes.xml` in your Android module. +- You can add drawable resources to `res/drawable/` when needed. +- You rebuild or sync Gradle after updating styles. + +## Styling Pattern + + + + +Components read styles from XML theme attributes. The pattern is: + +1. Open `res/values/themes.xml`. +2. Create a custom style that extends the component's parent style (for example, `CometChatConversationsStyle`). +3. Assign your custom style to `AppTheme` using the component's theme attribute (for example, `cometchatConversationsStyle`). +4. Sync Gradle and rebuild the app. +5. Navigate to the screen that uses the component and confirm the visual change. + +```xml themes.xml lines + + + + + +``` + +You can also set fonts globally: + +```xml themes.xml lines + +``` + + + + +Components accept a `style` parameter — a data class with `.default()` factory and `.copy()` for overrides: + +```kotlin lines +CometChatConversations( + style = CometChatConversationsStyle.default().copy( + backgroundColor = Color(0xFFFFF9F5), + titleTextColor = Color(0xFFF76808) + ) +) +``` + +Nested styles (e.g., avatar inside conversations) are overridden the same way: + +```kotlin lines +CometChatConversations( + style = CometChatConversationsStyle.default().copy( + avatarStyle = CometChatAvatarStyle.default().copy( + backgroundColor = Color(0xFFFBAA75), + cornerRadius = 8.dp + ) + ) +) +``` + + + + +## Core concepts + +- `AppTheme` is the single place where UI Kit style hooks are wired (XML Views). +- Each UI Kit component has a parent style (for example, `CometChatMessageListStyle`) and a theme attribute (for example, `cometchatMessageListStyle`). +- Custom styles must extend the correct parent style to inherit default behavior. +- Drawable overrides (for example, custom icons) live in `res/drawable/` and are referenced from styles. +- Fonts can be set once at the theme level and reused across components. + +--- + +## Implementation + +Use the following sections to style each component. Each section lists what changes, where to change it, the exact code to paste, and how to verify the result. + +### Chat Lists & Messaging + +#### Conversations + +The `CometChatConversations` component renders the recent chats list. + + + + + +What you're changing: avatar and badge styling in the conversation list. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatConversations` +- **Default behavior**: UI Kit default avatar and badge styles. +- **Override**: set `cometchatConversationsStyle` in `AppTheme` or pass a style object. + + + + + +```xml themes.xml lines + + + + + + + + + +``` + + + + +```kotlin lines +CometChatConversations( + style = CometChatConversationsStyle.default().copy( + avatarStyle = CometChatAvatarStyle.default().copy( + backgroundColor = Color(0xFFFBAA75), + cornerRadius = 8.dp + ), + badgeStyle = CometChatBadgeStyle.default().copy( + backgroundColor = Color(0xFFF76808), + textColor = Color.White + ) + ) +) +``` + + + + +- **What this does**: applies custom avatar and badge styles to conversation list items. +- **Verify**: the Conversations list shows updated avatar backgrounds and badge colors. + +Attribute references: +- [Conversations attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_conversations.xml) +- [Avatar attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_avatar.xml) +- [Badge attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_badge.xml) + +#### Users + +The `CometChatUsers` component renders a list of users for selection or navigation. + + + + + +What you're changing: user list avatar and separator styling. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatUsers` +- **Default behavior**: UI Kit default avatar and list styling. +- **Override**: set `cometchatUsersStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + + + +``` + + + + +```kotlin lines +CometChatUsers( + style = CometChatUsersStyle.default().copy( + separatorColor = Color(0xFFF76808), + titleTextColor = Color(0xFFF76808) + ) +) +``` + + + + +- **What this does**: applies avatar and separator color overrides to the user list. +- **Verify**: the Users list shows updated avatar backgrounds and separator color. + +Attribute references: +- [Users attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_users.xml) +- [Avatar attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_avatar.xml) + +#### Groups + +The `CometChatGroups` component renders group items and their summary data. + + + + + +What you're changing: group list avatar and typography colors. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatGroups` +- **Default behavior**: UI Kit default group item styling. +- **Override**: set `cometchatGroupsStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + + + +``` + + + + +```kotlin lines +CometChatGroups( + style = CometChatGroupsStyle.default().copy( + separatorColor = Color(0xFFF76808), + titleTextColor = Color(0xFFF76808) + ) +) +``` + + + + +- **What this does**: styles group avatars and separators in the Groups list. +- **Verify**: the Groups list shows the updated avatar background and title color. + +Attribute references: +- [Groups attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_groups.xml) +- [Avatar attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_avatar.xml) + +#### Message Header + +The `CometChatMessageHeader` component renders the title, avatar, and action icons for a chat. + + + + + +What you're changing: title text color, avatar styling, and call button icons. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatMessageHeader` +- **Default behavior**: UI Kit default header typography and icons. +- **Override**: set `cometchatMessageHeaderStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + + + + + +``` + + + + +```kotlin lines +CometChatMessageHeader( + style = CometChatMessageHeaderStyle.default().copy( + titleTextColor = Color(0xFFF76808) + ) +) +``` + + + + +- **What this does**: applies custom title color, avatar styling, and call button tints in the message header. +- **Verify**: open a conversation and check the header text and call button icons. + +Attribute references: +- [Message Header attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_message_header.xml) +- [Call Buttons attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_call_buttons.xml) + +#### Message List + +The `CometChatMessageList` component renders conversation messages and their bubble styles. + + + + + +What you're changing: message list background and outgoing bubble styling. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatMessageList` +- **Default behavior**: UI Kit default message list background and bubble colors. +- **Override**: set `cometchatMessageListStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + + + +``` + + + + +```kotlin lines +CometChatMessageList( + style = CometChatMessageListStyle.default().copy( + backgroundColor = Color(0xFFFEEDE1), + outgoingMessageBubbleStyle = CometChatOutgoingMessageBubbleStyle.default().copy( + backgroundColor = Color(0xFFF76808) + ) + ) +) +``` + + + + +- **What this does**: changes the message list background and outgoing bubble color. +- **Verify**: open a conversation and check outgoing message bubble colors. + +Attribute references: +- [Message List attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_message_list.xml) +- [Message Bubble attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_message_bubble.xml) + +#### Message Composer + +The `CometChatMessageComposer` component renders the input box and action buttons. + + + + + +What you're changing: send button icon and composer icon tints. + +- **Where to change it**: `res/drawable/active_send_button.xml` and `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatMessageComposer` +- **Default behavior**: UI Kit default composer icons and send button drawable. +- **Override**: set `cometchatMessageComposerStyle` in `AppTheme` or pass a style object. + + + + +```xml res/drawable/active_send_button.xml lines + + + + + + + +``` + +```xml res/values/themes.xml lines + + + + + +``` + + + + +```kotlin lines +CometChatMessageComposer( + style = CometChatMessageComposerStyle.default().copy( + attachmentIconTint = Color(0xFFF76808), + voiceRecordingIconTint = Color(0xFFF76808), + aiIconTint = Color(0xFFF76808) + ) +) +``` + + + + +- **What this does**: applies custom icon tints and the active send button drawable to the composer. +- **Verify**: the composer shows the custom send button and tinted icons. + +Attribute references: +- [Message Composer attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_message_composer.xml) + +#### Group Members + +The `CometChatGroupMembers` component lists users inside a group. + + + + + +What you're changing: group member list avatars, separators, and back icon tint. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatGroupMembers` +- **Default behavior**: UI Kit default list styling. +- **Override**: set `cometchatGroupMembersStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + + + +``` + + + + +```kotlin lines +CometChatGroupMembers( + style = CometChatGroupMembersStyle.default().copy( + separatorColor = Color(0xFFF76808), + titleTextColor = Color(0xFFF76808) + ) +) +``` + + + + +- **What this does**: applies custom avatar and separator styling to the group members list. +- **Verify**: the group members screen shows updated avatar and separator colors. + +Attribute references: +- [Group Members attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_group_members.xml) +- [Avatar attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_avatar.xml) + +#### Thread Header + +The `CometChatThreadHeader` component renders the parent message preview in threaded views. + + + + + +What you're changing: thread header bubble colors and reply count styling. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatThreadHeader` +- **Default behavior**: UI Kit default thread header styling. +- **Override**: set `cometchatThreadHeaderStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + + + + + +``` + + + + +```kotlin lines +CometChatThreadHeader( + style = CometChatThreadHeaderStyle.default().copy( + backgroundColor = Color(0xFFFEEDE1), + replyCountTextColor = Color(0xFFF76808) + ) +) +``` + + + + +- **What this does**: customizes thread header bubble colors and reply count styling. +- **Verify**: open a thread and confirm the header background and reply count colors. + +Attribute references: +- [Thread Header attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_thread_header.xml) +- [Message Bubble attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_message_bubble.xml) + +#### Mentions + +The `CometChatMentions` styling controls how user mentions appear inside messages. + + + + + +What you're changing: mention text and background styles for incoming and outgoing bubbles. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatMentions` +- **Default behavior**: UI Kit default mention styling. +- **Override**: set `cometchatMessageBubbleMentionsStyle` in both incoming and outgoing bubble styles. + + + + +```xml themes.xml lines + + + + + + + + + + + +``` + + + + +```kotlin lines +CometChatMessageList( + style = CometChatMessageListStyle.default().copy( + incomingMessageBubbleStyle = CometChatIncomingMessageBubbleStyle.default().copy( + mentionTextColor = Color(0xFFD6409F) + ), + outgoingMessageBubbleStyle = CometChatOutgoingMessageBubbleStyle.default().copy( + mentionTextColor = Color.White + ) + ) +) +``` + + + + +- **What this does**: customizes mention colors for incoming and outgoing message bubbles. +- **Verify**: send a mention in a chat and check the mention highlight colors. + +Attribute references: +- [Mentions attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_mentions.xml) +- [Message Bubble attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_message_bubble.xml) + +#### Search + +The `CometChatSearch` component provides cross-conversation and message search UI. + + + + + +What you're changing: search background and typography styles. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatSearch` + +- **Default behavior**: UI Kit default search colors and text appearance. + +- **Override**: set `cometchatSearchStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + + + +``` + +- **What this does**: applies custom search colors and text styles across search UI sections. + +- **Verify**: open Search and check section headers, chips, and list items. + +Attribute references: +- [Search attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_search.xml) + + +#### Message Information + +The `CometChatMessageInformation` component displays message metadata such as delivery and read status. + + + + + +What you're changing: message information styling for metadata views. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatMessageInformation` + +- **Default behavior**: UI Kit default metadata styling. + +- **Override**: set `cometchatMessageInformationStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: wires a custom Message Information style so you can override specific metadata attributes. + +- **Verify**: open Message Information and confirm your overrides apply. + +Attribute references: +- [Message Information attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_message_information.xml) + + +#### Message Option Sheet + +The `CometChatMessageOptionSheet` component is the action menu for message-level actions. + + + + + +What you're changing: option sheet background and icon tint. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatMessageOptionSheet` + +- **Default behavior**: UI Kit default option sheet styling. + +- **Override**: set `cometchatPopupMenuStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: updates message option sheet icon tint and background color. + +- **Verify**: long-press a message and confirm the option sheet styling. + +Attribute references: +- [Message Option Sheet attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_message_option_sheet.xml) + + +#### Attachment Option Sheet + +The `CometChatAttachmentOptionSheet` component renders the attachment picker. + + + + + +What you're changing: attachment option sheet background and icon tint. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatAttachmentOptionSheet` + +- **Default behavior**: UI Kit default attachment sheet styling. + +- **Override**: set `cometchatAttachmentOptionSheetStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies custom colors to the attachment picker sheet. + +- **Verify**: open the attachment menu and confirm background and icons. + +Attribute references: +- [Attachment Option Sheet attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_attachment_option_sheet.xml) + + +--- + +### Calling UI + +#### Call Logs + +The `CometChatCallLogs` component renders recent call history. + + + + + +What you're changing: call log list separators and title colors. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatCallLogs` +- **Default behavior**: UI Kit default call log styling. +- **Override**: set `cometchatCallLogsStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + + + +``` + + + + +```kotlin lines +CometChatCallLogs( + style = CometChatCallLogsStyle.default().copy( + separatorColor = Color(0xFFF76808), + titleTextColor = Color(0xFFF76808) + ) +) +``` + + + + +- **What this does**: applies custom avatar and text colors to the call logs list. +- **Verify**: open Call Logs and confirm the separator and title colors. + +Attribute references: +- [Call Logs attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_call_logs.xml) + +#### Incoming Call + +The `CometChatIncomingCall` component renders the incoming call UI. + + + + + +What you're changing: incoming call background, buttons, and avatar styling. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatIncomingCall` +- **Default behavior**: UI Kit default incoming call layout and colors. +- **Override**: set `cometchatIncomingCallStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + +``` + + + + +```kotlin lines +CometChatIncomingCall( + call = call, + style = CometChatIncomingCallStyle.default().copy( + backgroundColor = Color(0xFFAA9EE8) + ) +) +``` + + + + +- **What this does**: customizes the incoming call screen background and action buttons. +- **Verify**: trigger an incoming call and confirm the background and button colors. + +Attribute references: +- [Incoming Call attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_incoming_call.xml) +- [Avatar attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_avatar.xml) + +#### Outgoing Call + +The `CometChatOutgoingCall` component renders the outgoing call UI. + + + + + +What you're changing: outgoing call avatar styling. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatOutgoingCall` +- **Default behavior**: UI Kit default outgoing call styling. +- **Override**: set `cometchatOutgoingCallStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + + + +``` + + + + +```kotlin lines +CometChatOutgoingCall( + call = call, + style = CometChatOutgoingCallStyle.default().copy( + avatarStyle = CometChatAvatarStyle.default().copy( + backgroundColor = Color(0xFFFBAA75) + ) + ) +) +``` + + + + +- **What this does**: applies a custom avatar style to the outgoing call screen. +- **Verify**: place a call and confirm the avatar styling. + +Attribute references: +- [Outgoing Call attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_outgoing_call.xml) +- [Avatar attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_avatar.xml) + +#### Call Buttons + +The `CometChatCallButton` component renders voice and video call buttons. + + + + + +What you're changing: button background, stroke, and icon tint. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatCallButtons` + +- **Default behavior**: UI Kit default call button styling. + +- **Override**: set `cometchatCallButtonsStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: customizes call button padding, background, and icon colors. + +- **Verify**: open a chat header and confirm button styling. + +Attribute references: +- [Call Buttons attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_call_buttons.xml) + + +--- + +### AI UI +#### AI Assistant Chat History + +The `CometChatAIAssistantChatHistory` component renders the AI conversation history view. + + + + + +What you're changing: background, header, and list typography. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatAIAssistantChatHistory` + +- **Default behavior**: UI Kit default AI history styling. + +- **Override**: set `cometChatAIAssistantChatHistoryStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + + + +``` + +- **What this does**: applies custom colors and font styling to the AI Assistant history screen. + +- **Verify**: open AI Assistant history and confirm background and header styling. + +Attribute references: +- [AI Assistant Chat History attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_assistant_chat_history.xml) + +#### AI Option Sheet + +The `CometChatAIOptionSheet` component renders AI action options. + + + + + +What you're changing: AI option sheet background and icon tint. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatAIOptionSheet` + +- **Default behavior**: UI Kit default AI option sheet styling. + +- **Override**: set `cometchatAIOptionSheetStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: customizes AI option sheet colors. + +- **Verify**: open AI actions and confirm the option sheet styling. + +Attribute references: +- [AI Option Sheet attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_option_sheet.xml) + +#### Conversation Starter + +The `CometChatConversationStarter` component renders AI-powered conversation starters. + + + + + +What you're changing: conversation starter item backgrounds. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatConversationStarter` + +- **Default behavior**: UI Kit default conversation starter styling. + +- **Override**: set `cometchatAIConversationStarterStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies a custom background color to AI conversation starter items. + +- **Verify**: open a new chat and confirm the conversation starter chip color. + +Attribute references: +- [AI Conversation Starter attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_conversation_starter.xml) + +#### Conversation Summary + +The `CometChatConversationSummary` component renders AI-generated summaries of chats. + + + + + +What you're changing: conversation summary background color. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatConversationSummary` + +- **Default behavior**: UI Kit default conversation summary styling. + +- **Override**: set `cometchatAIConversationSummaryStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies a custom background color to conversation summary cards. + +- **Verify**: open a chat summary and confirm the background color. + +Attribute references: +- [AI Conversation Summary attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_conversation_summary.xml) + +#### Smart Replies + +The `CometChatSmartReplies` component renders AI-generated reply suggestions. + + + + + +What you're changing: smart reply background, item color, and stroke. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatSmartReplies` + +- **Default behavior**: UI Kit default smart replies styling. + +- **Override**: set `cometchatAISmartRepliesStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: customizes smart reply container and chip styling. + +- **Verify**: open a conversation with smart replies enabled and confirm chip styling. + +Attribute references: +- [AI Smart Replies attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_smart_replies.xml) + + +--- + +### Base Components + +#### Avatar + +The `CometChatAvatar` component is used across lists and headers. + + + + + +What you're changing: avatar shape and background color. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatAvatar` +- **Default behavior**: UI Kit default avatar styling. +- **Override**: set `cometchatAvatarStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + +``` + + + + +```kotlin lines +// Globally via CometChatConversations, CometChatUsers, etc. +style = ComponentStyle.default().copy( + avatarStyle = CometChatAvatarStyle.default().copy( + backgroundColor = Color(0xFFFBAA75), + cornerRadius = 8.dp + ) +) +``` + + + + +- **What this does**: applies a consistent avatar style across UI Kit components. +- **Verify**: open any list with avatars and confirm the style. + +Attribute references: +- [Avatar attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_avatar.xml) + +#### Badge + +The `CometChatBadge` component shows unread or notification counts. + + + + + +What you're changing: badge background, text color, and corner radius. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatBadge` +- **Default behavior**: UI Kit default badge styling. +- **Override**: set `cometchatBadgeStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + +``` + + + + +```kotlin lines +// Via parent component style +style = CometChatConversationsStyle.default().copy( + badgeStyle = CometChatBadgeStyle.default().copy( + backgroundColor = Color(0xFFF44649), + textColor = Color.White, + cornerRadius = 4.dp + ) +) +``` + + + + +- **What this does**: applies a custom badge appearance across UI Kit lists. +- **Verify**: check any unread badge to confirm colors and radius. + +Attribute references: +- [Badge attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_badge.xml) + +#### Status Indicator + +The `CometChatStatusIndicator` component shows user presence status. + + + + + +What you're changing: status indicator icon shape and drawable. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatStatusIndicator` +- **Default behavior**: UI Kit default presence icon. +- **Override**: set `cometchatStatusIndicatorStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + +``` + + + + +```kotlin lines +// Via parent component style +style = ComponentStyle.default().copy( + statusIndicatorStyle = CometChatStatusIndicatorStyle.default().copy( + cornerRadius = 8.dp + ) +) +``` + + + + +- **What this does**: applies the custom status indicator in UI Kit components. +- **Verify**: check any user list to confirm the presence icon. + +Attribute references: +- [Status Indicator attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_status_indicator.xml) + +#### Reaction List + +The `CometChatReactionList` component renders reactions on messages. + + + + + +What you're changing: active tab color in the reaction list. + +- **Where to change it**: `res/values/themes.xml` (XML Views) or `style` parameter (Compose) +- **Applies to**: `CometChatReactionList` +- **Default behavior**: UI Kit default reaction list styling. +- **Override**: set `cometchatReactionListStyle` in `AppTheme` or pass a style object. + + + + +```xml themes.xml lines + + + + + +``` + + + + +```kotlin lines +CometChatReactionList( + style = CometChatReactionListStyle.default().copy( + tabTextActiveColor = Color(0xFFF76808) + ) +) +``` + + + + +- **What this does**: applies a custom active tab color in the reaction list. +- **Verify**: open reactions and confirm the active tab color. + +Attribute references: +- [Reaction List attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_reaction_list.xml) + +#### Date + +The `CometChatDate` component formats timestamps in lists and message threads. + + + + + +What you're changing: date text color. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatDate` + +- **Default behavior**: UI Kit default date styling. + +- **Override**: set `cometchatDateStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: customizes date text color in UI Kit lists and headers. + +- **Verify**: check any timestamp and confirm the color. + +Attribute references: +- [Date attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_date.xml) + + +#### Receipts + +The `CometChatReceipts` component renders read and delivered status icons. + + + + + +What you're changing: read receipt icon drawable. + +- **Where to change it**: `res/drawable/read_receipts.xml` and `res/values/themes.xml` + +- **Applies to**: `CometChatReceipts` + +- **Default behavior**: UI Kit default receipt icons. + +- **Override**: set `cometchatMessageReceiptStyle` in `AppTheme` and reference a custom drawable. + +- **Code**: +```xml res/drawable/read_receipts.xml lines + + + + +``` + +- **What this does**: defines a custom read receipt icon. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies the custom receipt icon to message status indicators. + +- **Verify**: send a message and check the receipt icon for read status. + +Attribute references: +- [Message Receipt attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_message_receipt.xml) + + +#### Media Recorder + +The `CometChatMediaRecorder` component controls audio and video message recording. + + + + + +What you're changing: recorder icon sizes and recording button background color. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatMediaRecorder` + +- **Default behavior**: UI Kit default media recorder styling. + +- **Override**: set `cometchatMediaRecorderStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies custom sizing and color to the media recorder UI. + +- **Verify**: open the recorder and check icon sizes and record button color. + +Attribute references: +- [Media Recorder attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_media_recorder.xml) + + +#### Sticker Keyboard + +The `CometChatStickerKeyboard` component renders the sticker picker UI. + + + + + +What you're changing: sticker keyboard background color. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatStickerKeyboard` + +- **Default behavior**: UI Kit default sticker keyboard styling. + +- **Override**: set `cometchatStickerKeyboardStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies a custom background color to the sticker keyboard. + +- **Verify**: open the sticker keyboard and confirm the background color. + +Attribute references: +- [Sticker Keyboard attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_sticker_keyboard.xml) + + +--- + +## Customization matrix + +| What you want to change | Where | Property or API | Example | +| --- | --- | --- | --- | +| Conversations avatar and badge | `themes.xml` / style param | `cometchatConversationsStyle` | `cometchatConversationsBadgeStyle` | +| Users list separators | `themes.xml` / style param | `cometchatUsersStyle` | `cometchatUsersSeparatorColor` | +| Group list titles | `themes.xml` / style param | `cometchatGroupsStyle` | `cometchatGroupsTitleTextColor` | +| Header call icons | `themes.xml` / style param | `cometchatMessageHeaderStyle` | `cometchatMessageHeaderCallButtonsStyle` | +| Message list background | `themes.xml` / style param | `cometchatMessageListStyle` | `cometchatMessageListBackgroundColor` | +| Search styling | `themes.xml` / style param | `cometchatSearchStyle` | `cometchatSearchBackgroundColor` | +| Message Information | `themes.xml` / style param | `cometchatMessageInformationStyle` | `cometchatMessageInformationBackgroundColor` | +| AI Chat History | `themes.xml` / style param | `cometchatAIAssistantChatHistoryStyle` | `cometchatAIAssistantChatHistoryBackgroundColor` | +| Date formatting | `themes.xml` / style param | `cometchatDateStyle` | `cometchatDateTextColor` | +| Receipts icons | `themes.xml` / style param | `cometchatReceiptsStyle` | `cometchatReceiptsReadColor` | +| Composer send button | `res/drawable/` + `themes.xml` | `cometchatMessageComposerActiveSendButtonDrawable` | `@drawable/active_send_button` | +| Call buttons styling | `themes.xml` / style param | `cometchatCallButtonsStyle` | `cometchatCallButtonsVideoCallBackgroundColor` | diff --git a/ui-kit/android/v6/components-overview.mdx b/ui-kit/android/v6/components-overview.mdx new file mode 100644 index 000000000..1461fb7f8 --- /dev/null +++ b/ui-kit/android/v6/components-overview.mdx @@ -0,0 +1,248 @@ +--- +title: "Overview" +description: "Browse all prebuilt UI components in the CometChat Android UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin-android` (Kotlin XML Views), `com.cometchat:chatuikit-compose-android` (Jetpack Compose) | +| Required setup | `CometChatUIKit.init()` + `CometChatUIKit.login()` before rendering any component | +| Shared core | `chatuikit-core` — ViewModels, repositories, use cases, events (shared by both modules) | +| Calling | Requires separate `com.cometchat:calls-sdk-android` package | + + + +## Architecture + +The UI Kit is a set of independent components that compose into chat layouts. A typical chat layout uses four core components: + +- `CometChatConversations` — list of recent conversations +- `CometChatMessageHeader` — toolbar with avatar, name, status, typing indicator +- `CometChatMessageList` — scrollable message feed with reactions, receipts, threads +- `CometChatMessageComposer` — rich input with attachments, mentions, voice notes + +Selecting a conversation yields a `User` or `Group` object. Pass it to the message components to load the chat. + +Components communicate via `CometChatEvents` — a SharedFlow-based event bus. See [Events](/ui-kit/android/v6/events). + +--- + +## Component Catalog + +### Conversations and Lists + +| Component | Purpose | Page | +| --- | --- | --- | +| `CometChatConversations` | Scrollable list of recent conversations | [Conversations](/ui-kit/android/v6/conversations) | +| `CometChatUsers` | Scrollable list of users | [Users](/ui-kit/android/v6/users) | +| `CometChatGroups` | Scrollable list of groups | [Groups](/ui-kit/android/v6/groups) | +| `CometChatGroupMembers` | Scrollable list of group members | [Group Members](/ui-kit/android/v6/group-members) | + +### Messages + +| Component | Purpose | Page | +| --- | --- | --- | +| `CometChatMessageHeader` | Toolbar with avatar, name, status, typing | [Message Header](/ui-kit/android/v6/message-header) | +| `CometChatMessageList` | Message feed with reactions, receipts, threads | [Message List](/ui-kit/android/v6/message-list) | +| `CometChatMessageComposer` | Rich input with attachments, mentions, voice | [Message Composer](/ui-kit/android/v6/message-composer) | +| `CometChatThreadHeader` | Parent message bubble and reply count | [Thread Header](/ui-kit/android/v6/threaded-messages-header) | + +### Calling + +| Component | Purpose | Page | +| --- | --- | --- | +| `CometChatCallButtons` | Voice and video call buttons | [Call Buttons](/ui-kit/android/v6/call-buttons) | +| `CometChatIncomingCall` | Incoming call notification | [Incoming Call](/ui-kit/android/v6/incoming-call) | +| `CometChatOutgoingCall` | Outgoing call screen | [Outgoing Call](/ui-kit/android/v6/outgoing-call) | +| `CometChatCallLogs` | Call history list | [Call Logs](/ui-kit/android/v6/call-logs) | + +--- + +## Component API Pattern + +All components share a consistent API surface across both modules. + +### Setting User or Group + + + + + +```kotlin lines +messageHeader.setUser(user) +messageList.setUser(user) +messageComposer.setUser(user) + +// Or for group chat +messageHeader.setGroup(group) +messageList.setGroup(group) +messageComposer.setGroup(group) +``` + + + + +```kotlin lines +CometChatMessageHeader(user = user) +CometChatMessageList(user = user) +CometChatMessageComposer(user = user) + +// Or for group chat +CometChatMessageHeader(group = group) +CometChatMessageList(group = group) +CometChatMessageComposer(group = group) +``` + + + + +### Callbacks + + + + +```kotlin lines +conversations.setOnItemClick { conversation -> /* navigate */ } +conversations.setOnError { exception -> /* handle error */ } +conversations.setOnLoad { list -> /* data loaded */ } +``` + + + + +```kotlin lines +CometChatConversations( + onItemClick = { conversation -> /* navigate */ }, + onError = { exception -> /* handle error */ }, + onLoad = { list -> /* data loaded */ } +) +``` + + + + +### Data Filtering + + + + +```kotlin lines +conversations.setConversationsRequestBuilder( + ConversationsRequest.ConversationsRequestBuilder().setLimit(20) +) +``` + + + + +```kotlin lines +CometChatConversations( + conversationsRequestBuilder = ConversationsRequest.ConversationsRequestBuilder().setLimit(20) +) +``` + + + + +### View Slots + +Replace specific regions of a component's UI. See [View Slots](/ui-kit/android/v6/customization-view-slots). + + + + +```kotlin lines +conversations.setSubtitleView(object : ConversationsViewHolderListener() { + override fun createView(context: Context, binding: CometchatConversationsListItemsBinding): View { + return CustomSubtitleView(context) + } + override fun bindView(context: Context, createdView: View, conversation: Conversation, ...) { + (createdView as CustomSubtitleView).bind(conversation) + } +}) +``` + + + + +```kotlin lines +CometChatConversations( + subtitleView = { conversation, typingIndicator -> + Text(conversation.lastMessage?.text ?: "") + } +) +``` + + + + +### Styles + +See [Component Styling](/ui-kit/android/v6/component-styling). + + + + +XML theme attributes in `themes.xml`: + +```xml lines + +``` + + + + +Style data classes via parameters: + +```kotlin lines +CometChatConversations( + style = CometChatConversationsStyle.default().copy( + backgroundColor = Color(0xFFF5F5F5) + ) +) +``` + + + + +### Events + +Global inter-component communication via `CometChatEvents`: + +```kotlin lines +// Subscribe to message events +viewModelScope.launch { + CometChatEvents.messageEvents.collect { event -> + when (event) { + is CometChatMessageEvent.MessageSent -> { /* handle */ } + is CometChatMessageEvent.MessageDeleted -> { /* handle */ } + else -> {} + } + } +} +``` + +See [Events](/ui-kit/android/v6/events) for the full reference. + +--- + +## Next Steps + + + + Chat features included out of the box + + + Customize colors, fonts, and styles + + + Deep customization via ViewModels, styles, and view slots + + + Task-oriented tutorials for common patterns + + diff --git a/ui-kit/android/v6/conversation-message-view.mdx b/ui-kit/android/v6/conversation-message-view.mdx new file mode 100644 index 000000000..61f3ed5f9 --- /dev/null +++ b/ui-kit/android/v6/conversation-message-view.mdx @@ -0,0 +1,446 @@ +--- +title: "Building A Conversation List + Message View" +sidebarTitle: "Conversation List + Message View" +description: "Build a conversation list with a full-screen message view using the Kotlin XML Views or Jetpack Compose UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Components | `CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Sequential navigation — conversation list → full-screen message view | +| Prerequisite | Complete [Kotlin Integration](/ui-kit/android/v6/getting-started-kotlin) or [Jetpack Compose Integration](/ui-kit/android/v6/getting-started-jetpack) Steps 1–3 first | +| Pattern | WhatsApp, Slack, Telegram | + + + +This guide builds a sequential navigation chat layout — conversation list as the entry point, tap a conversation to open a full-screen message view. + +This assumes you've already completed the integration guide for your chosen UI toolkit (project created, dependencies installed, init + login working). + +--- + +## What You're Building + +Three sections working together: + +1. **Conversation list** — shows all active conversations (users and groups) +2. **Message header** — displays user/group name, avatar, and status +3. **Message list + composer** — chat history with real-time updates and text input + + + +This implementation uses Android's standard Activity navigation: `ConversationActivity` displays the list, user taps a conversation, `MessageActivity` launches with the selected user/group data via Intent extras. + + +This implementation uses Compose state to manage navigation between the conversation list and message screen — no Activities or Fragments needed beyond your `MainActivity`. + + + +--- + +## Step 1: Set Up the Conversation List + + + + +Create a new Activity called `ConversationActivity` to display the list of conversations. + +**Layout** — `activity_conversation.xml`: + +```xml activity_conversation.xml lines + + + + + +``` + +**Activity** — `ConversationActivity.kt`: + +```kotlin ConversationActivity.kt lines +import android.content.Intent +import android.os.Bundle +import android.util.Log +import androidx.activity.enableEdgeToEdge +import androidx.appcompat.app.AppCompatActivity +import com.cometchat.chat.models.Group +import com.cometchat.chat.models.User +import com.cometchat.uikit.kotlin.presentation.conversations.ui.CometChatConversations + +class ConversationActivity : AppCompatActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + setContentView(R.layout.activity_conversation) + + val conversations = findViewById(R.id.conversations) + + conversations.setTitle("Chats") + conversations.setOnItemClick { conversation -> + val intent = Intent(this, MessageActivity::class.java) + when (val entity = conversation.conversationWith) { + is User -> intent.putExtra("user", entity) + is Group -> intent.putExtra("group", entity) + else -> Log.e("ConversationActivity", "Unknown conversation type") + } + startActivity(intent) + } + } +} +``` + + +You must use an activity that supports the **lifecycle** API (`AppCompatActivity`, `ComponentActivity`, or `FragmentActivity`) to properly manage the UI Kit's lifecycle events. + + + + + +Create a `ChatApp.kt` file with the root composable that manages navigation between the conversation list and message screen: + +```kotlin ChatApp.kt lines +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import com.cometchat.chat.models.Group +import com.cometchat.chat.models.User + +@Composable +fun ChatApp() { + var selectedUser by remember { mutableStateOf(null) } + var selectedGroup by remember { mutableStateOf(null) } + + val inChat = selectedUser != null || selectedGroup != null + + if (!inChat) { + ConversationsScreen( + onConversationClick = { user, group -> + selectedUser = user + selectedGroup = group + } + ) + } else { + MessageScreen( + user = selectedUser, + group = selectedGroup, + onBack = { + selectedUser = null + selectedGroup = null + } + ) + } +} +``` + +Add the `ConversationsScreen` composable: + +```kotlin ChatApp.kt lines +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.Modifier +import com.cometchat.uikit.compose.presentation.conversations.ui.CometChatConversations + +@Composable +fun ConversationsScreen( + onConversationClick: (User?, Group?) -> Unit +) { + CometChatConversations( + modifier = Modifier.fillMaxSize(), + title = "Chats", + onItemClick = { conversation -> + when (val entity = conversation.conversationWith) { + is User -> onConversationClick(entity, null) + is Group -> onConversationClick(null, entity) + } + } + ) +} +``` + + + + +--- + +## Step 2: Set Up the Message Screen + + + + +Create a new Activity — `MessageActivity` to display the chat interface. + +**Layout** — `activity_message.xml`: + +```xml activity_message.xml lines + + + + + + + + + +``` + +**Activity** — `MessageActivity.kt`: + +```kotlin MessageActivity.kt lines +import android.os.Bundle +import android.widget.Toast +import androidx.activity.enableEdgeToEdge +import androidx.appcompat.app.AppCompatActivity +import com.cometchat.chat.models.Group +import com.cometchat.chat.models.User +import com.cometchat.uikit.kotlin.presentation.messagecomposer.ui.CometChatMessageComposer +import com.cometchat.uikit.kotlin.presentation.messageheader.ui.CometChatMessageHeader +import com.cometchat.uikit.kotlin.presentation.messagelist.ui.CometChatMessageList + +class MessageActivity : AppCompatActivity() { + + private lateinit var messageHeader: CometChatMessageHeader + private lateinit var messageList: CometChatMessageList + private lateinit var messageComposer: CometChatMessageComposer + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + setContentView(R.layout.activity_message) + + messageHeader = findViewById(R.id.message_header) + messageList = findViewById(R.id.message_list) + messageComposer = findViewById(R.id.message_composer) + + val user = intent.getSerializableExtra("user") as? User + val group = intent.getSerializableExtra("group") as? Group + + when { + user != null -> { + messageHeader.setUser(user) + messageList.setUser(user) + messageComposer.setUser(user) + } + group != null -> { + messageHeader.setGroup(group) + messageList.setGroup(group) + messageComposer.setGroup(group) + } + else -> { + Toast.makeText(this, "Missing user or group data", Toast.LENGTH_SHORT).show() + finish() + } + } + + messageHeader.setOnBackPress { finish() } + } +} +``` + + + + +Add the `MessageScreen` composable with header, list, and composer stacked vertically: + +```kotlin ChatApp.kt lines +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.consumeWindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBars +import androidx.compose.material3.Scaffold +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import com.cometchat.chat.models.Group +import com.cometchat.chat.models.User +import com.cometchat.uikit.compose.presentation.messagecomposer.ui.CometChatMessageComposer +import com.cometchat.uikit.compose.presentation.messageheader.ui.CometChatMessageHeader +import com.cometchat.uikit.compose.presentation.messagelist.ui.CometChatMessageList + +@Composable +fun MessageScreen( + user: User? = null, + group: Group? = null, + onBack: () -> Unit +) { + Scaffold( + contentWindowInsets = WindowInsets.statusBars + ) { paddingValues -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(paddingValues) + .consumeWindowInsets(paddingValues) + .navigationBarsPadding() + .imePadding() + ) { + CometChatMessageHeader( + modifier = Modifier.fillMaxWidth(), + user = user, + group = group, + hideBackButton = false, + onBackPress = onBack + ) + + CometChatMessageList( + modifier = Modifier + .fillMaxWidth() + .weight(1f), + user = user, + group = group + ) + + CometChatMessageComposer( + modifier = Modifier.fillMaxWidth(), + user = user, + group = group + ) + } + } +} +``` + + + + +--- + +## Step 3: Update MainActivity + + + + +Update your `MainActivity` to launch `ConversationActivity` after successful login: + +```kotlin MainActivity.kt lines +private fun loginUser() { + CometChatUIKit.login("cometchat-uid-1", object : CometChat.CallbackListener() { + override fun onSuccess(user: User) { + Log.d(TAG, "Login successful: ${user.uid}") + + // Launch Conversation List + Message View + startActivity(Intent(this@MainActivity, ConversationActivity::class.java)) + } + + override fun onError(e: CometChatException) { + Log.e(TAG, "Login failed: ${e.message}") + } + }) +} +``` + + + + +Update your `MainActivity` to render `ChatApp()` after successful login: + +```kotlin MainActivity.kt lines +setContent { + when { + error != null -> { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text(error ?: "Unknown error") + } + } + !isReady -> { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + } + else -> { + ChatApp() + } + } +} +``` + + + + +--- + +## Step 4: Register Activities & Permissions + + + + +Add the new activities to your `AndroidManifest.xml`: + +```xml AndroidManifest.xml lines + + + + + + + + + + +``` + + + + +No additional activities needed — everything runs inside your existing `MainActivity`. + + + + +Ensure you've added the required permissions in your `AndroidManifest.xml`: + +```xml AndroidManifest.xml lines + + +``` + +--- + +## Next Steps + + + + Explore all available UI Kit components and their customization options + + + Customize colors, fonts, and styles to match your brand + + + Back to the main integration guide + + + Add capabilities like threaded messages, blocking, and group management + + diff --git a/ui-kit/android/v6/conversations.mdx b/ui-kit/android/v6/conversations.mdx new file mode 100644 index 000000000..ffbc2278f --- /dev/null +++ b/ui-kit/android/v6/conversations.mdx @@ -0,0 +1,952 @@ +--- +title: "Conversations" +description: "Scrollable list of recent one-on-one and group conversations for the logged-in user." +--- + +`CometChatConversations` renders a scrollable list of recent conversations with real-time updates for new messages, typing indicators, read receipts, and user presence. + + + + + +--- + +## Where It Fits + +`CometChatConversations` is a list component. It renders recent conversations and emits the selected `Conversation` via `onItemClick`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a standard chat layout. + + + + +```xml activity_chat.xml lines + +``` + +```kotlin lines +val conversations = findViewById(R.id.conversations) + +conversations.setOnItemClick { conversation -> + when (val entity = conversation.conversationWith) { + is User -> navigateToUserChat(entity) + is Group -> navigateToGroupChat(entity) + } +} +``` + + + + +```kotlin lines +CometChatConversations( + modifier = Modifier.fillMaxSize(), + onItemClick = { conversation -> + when (val entity = conversation.conversationWith) { + is User -> navigateToUserChat(entity) + is Group -> navigateToGroupChat(entity) + } + } +) +``` + + + + +> See the [Conversation List + Message View](/ui-kit/android/v6/conversation-message-view) guide for a complete layout. + +--- + +## Quick Start + + + + +Add to your layout XML: + +```xml lines + +``` + +Or programmatically: + +```kotlin lines +override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(CometChatConversations(this)) +} +``` + + + + +```kotlin lines +@Composable +fun ConversationsScreen() { + CometChatConversations( + modifier = Modifier.fillMaxSize() + ) +} +``` + + + + + +Prerequisites: CometChat SDK initialized with `CometChatUIKit.init()`, a user logged in, and the UI Kit dependency added. + +Or in a Fragment: + + + + +```kotlin lines +override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + return CometChatConversations(requireContext()) +} +``` + + + + +```kotlin lines +override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + return ComposeView(requireContext()).apply { + setContent { CometChatConversations() } + } +} +``` + + + + +--- + +## Filtering Conversations + + + + +Pass a `ConversationsRequest.ConversationsRequestBuilder` to control what loads: + +```kotlin lines +conversations.setConversationsRequestBuilder( + ConversationsRequest.ConversationsRequestBuilder() + .setConversationType(CometChatConstants.CONVERSATION_TYPE_USER) + .setLimit(20) +) +``` + + + + +```kotlin lines +CometChatConversations( + conversationsRequestBuilder = ConversationsRequest.ConversationsRequestBuilder() + .setConversationType(CometChatConstants.CONVERSATION_TYPE_USER) + .setLimit(20) +) +``` + + + + +### Filter Recipes + +| Recipe | Builder method | +| --- | --- | +| Only user conversations | `.setConversationType(CONVERSATION_TYPE_USER)` | +| Only group conversations | `.setConversationType(CONVERSATION_TYPE_GROUP)` | +| Limit per page | `.setLimit(10)` | +| With tags | `.setTags(listOf("vip")).withTags(true)` | +| Filter by user tags | `.withUserAndGroupTags(true).setUserTags(listOf("premium"))` | +| Filter by group tags | `.withUserAndGroupTags(true).setGroupTags(listOf("support"))` | + + +Pass the builder object, not the result of `.build()`. The component calls `.build()` internally. Default page size is 30 with infinite scroll. + + +--- + +## Actions and Events + +### Callback Methods + +#### `onItemClick` + +Fires when a conversation row is tapped. Primary navigation hook. + + + + +```kotlin lines +conversations.setOnItemClick { conversation -> + // Navigate to chat screen +} +``` + + + + +```kotlin lines +CometChatConversations( + onItemClick = { conversation -> + // Navigate to chat screen + } +) +``` + + + + +> Replaces the default item-click behavior. Your custom lambda executes instead of the built-in navigation. + +#### `onItemLongClick` + +Fires when a conversation row is long-pressed. Use for additional actions like delete or select. + + + + +```kotlin lines +conversations.setOnItemLongClick { conversation -> + // Show context menu +} +``` + + + + +```kotlin lines +CometChatConversations( + onItemLongClick = { conversation -> + // Show context menu + } +) +``` + + + + +#### `onBackPress` + +Fires when the user presses the back button in the toolbar. + + + + +```kotlin lines +conversations.setOnBackPress { + finish() +} +``` + + + + +```kotlin lines +CometChatConversations( + onBackPress = { /* navigate back */ } +) +``` + + + + +#### `onSearchClick` + +Fires when the user taps the search icon in the toolbar. + + + + +```kotlin lines +conversations.setOnSearchClick { + // Open search screen +} +``` + + + + +```kotlin lines +CometChatConversations( + onSearchClick = { /* open search */ } +) +``` + + + + +#### `onSelection` + +Fires when conversations are selected/deselected in multi-select mode. + + + + +```kotlin lines +conversations.setSelectionMode(UIKitConstants.SelectionMode.MULTIPLE) +conversations.setOnSelection { selectedConversations -> + updateToolbar(selectedConversations.size) +} +``` + + + + +```kotlin lines +CometChatConversations( + selectionMode = UIKitConstants.SelectionMode.MULTIPLE, + onSelection = { selectedConversations -> + updateToolbar(selectedConversations.size) + } +) +``` + + + + +#### `onError` + +Fires on internal errors (network failure, auth issue, SDK exception). + + + + +```kotlin lines +conversations.setOnError { exception -> + Log.e("Conversations", "Error: ${exception.message}") +} +``` + + + + +```kotlin lines +CometChatConversations( + onError = { exception -> + Log.e("Conversations", "Error: ${exception.message}") + } +) +``` + + + + +#### `onLoad` + +Fires when the list is successfully fetched and loaded. + + + + +```kotlin lines +conversations.setOnLoad { conversations -> + Log.d("Conversations", "Loaded ${conversations.size}") +} +``` + + + + +```kotlin lines +CometChatConversations( + onLoad = { conversations -> + Log.d("Conversations", "Loaded ${conversations.size}") + } +) +``` + + + + +#### `onEmpty` + +Fires when the list is empty after loading. + + + + +```kotlin lines +conversations.setOnEmpty { + Log.d("Conversations", "No conversations") +} +``` + + + + +```kotlin lines +CometChatConversations( + onEmpty = { /* no conversations */ } +) +``` + + + + +### Global Events + +The component emits events via `CometChatEvents` that can be subscribed to from anywhere: + +```kotlin lines +viewModelScope.launch { + CometChatEvents.conversationEvents.collect { event -> + when (event) { + is CometChatConversationEvent.ConversationDeleted -> { /* handle */ } + is CometChatConversationEvent.ConversationUpdated -> { /* handle */ } + } + } +} +``` + +### SDK Events (Real-Time, Automatic) + +The component listens to these SDK events internally. No manual setup needed. + +| SDK Listener | Internal behavior | +| --- | --- | +| `onTextMessageReceived` / `onMediaMessageReceived` / `onCustomMessageReceived` | Moves conversation to top, updates last message and unread count | +| `onTypingStarted` / `onTypingEnded` | Shows/hides typing indicator in subtitle | +| `onMessagesDelivered` / `onMessagesRead` | Updates receipt indicators | +| `onUserOnline` / `onUserOffline` | Updates presence status dot | +| `onGroupMemberJoined` / `onGroupMemberLeft` / `onGroupMemberKicked` / `onGroupMemberBanned` | Updates group conversation metadata | + +--- + +## Functionality + +| Method (Kotlin XML) | Compose Parameter | Description | +| --- | --- | --- | +| `setBackIconVisibility(View.VISIBLE)` | `hideBackIcon = false` | Toggle back button | +| `setToolbarVisibility(View.GONE)` | `hideToolbar = true` | Toggle toolbar | +| `setSearchBoxVisibility(View.GONE)` | `hideSearchBox = true` | Toggle search box | +| `setDisableSoundForMessages(true)` | `disableSoundForMessages = true` | Disable message sounds | +| `setCustomSoundForMessages(R.raw.sound)` | `customSoundForMessages = R.raw.sound` | Custom message sound | +| `setSelectionMode(MULTIPLE)` | `selectionMode = MULTIPLE` | Enable selection mode | +| `setTitle("Chats")` | `title = "Chats"` | Custom toolbar title | +| `setSearchPlaceholderText("Search...")` | `searchPlaceholderText = "Search..."` | Search placeholder | + +--- + +## Custom View Slots + +### Leading View + +Replace the avatar / left section. + + + + +```kotlin lines +conversations.setLeadingView(object : ConversationsViewHolderListener() { + override fun createView(context: Context, binding: CometchatConversationsListItemsBinding): View { + return ImageView(context).apply { + layoutParams = ViewGroup.LayoutParams(48.dp, 48.dp) + } + } + + override fun bindView( + context: Context, createdView: View, conversation: Conversation, + typingIndicator: TypingIndicator?, holder: RecyclerView.ViewHolder, + conversations: List, position: Int + ) { + val imageView = createdView as ImageView + // Load avatar image + } +}) +``` + + + + +```kotlin lines +CometChatConversations( + leadingView = { conversation, typingIndicator -> + CometChatAvatar( + imageUrl = conversation.conversationWith?.avatar, + name = conversation.conversationWith?.name + ) + } +) +``` + + + + +### Title View + +Replace the name / title text. + + + + +```kotlin lines +conversations.setTitleView(object : ConversationsViewHolderListener() { + override fun createView(context: Context, binding: CometchatConversationsListItemsBinding): View { + return TextView(context) + } + + override fun bindView( + context: Context, createdView: View, conversation: Conversation, + typingIndicator: TypingIndicator?, holder: RecyclerView.ViewHolder, + conversations: List, position: Int + ) { + (createdView as TextView).text = conversation.conversationWith?.name ?: "" + } +}) +``` + + + + +```kotlin lines +CometChatConversations( + titleView = { conversation, _ -> + Text( + text = conversation.conversationWith?.name ?: "", + style = CometChatTheme.typography.heading4Medium + ) + } +) +``` + + + + +### Subtitle View + +Replace the last message preview. + + + + +```kotlin lines +conversations.setSubtitleView(object : ConversationsViewHolderListener() { + override fun createView(context: Context, binding: CometchatConversationsListItemsBinding): View { + return TextView(context).apply { maxLines = 1; ellipsize = TextUtils.TruncateAt.END } + } + + override fun bindView( + context: Context, createdView: View, conversation: Conversation, + typingIndicator: TypingIndicator?, holder: RecyclerView.ViewHolder, + conversations: List, position: Int + ) { + val textView = createdView as TextView + if (typingIndicator != null) { + textView.text = "typing..." + } else { + textView.text = when (val msg = conversation.lastMessage) { + is TextMessage -> msg.text + is MediaMessage -> "📎 ${msg.attachment?.fileExtension ?: "Media"}" + else -> "New conversation" + } + } + } +}) +``` + + + + +```kotlin lines +CometChatConversations( + subtitleView = { conversation, typingIndicator -> + val text = if (typingIndicator != null) "typing..." else { + when (val msg = conversation.lastMessage) { + is TextMessage -> msg.text ?: "" + is MediaMessage -> "📎 ${msg.attachment?.fileExtension ?: "Media"}" + else -> "New conversation" + } + } + Text(text, maxLines = 1, overflow = TextOverflow.Ellipsis) + } +) +``` + + + + +### Trailing View + +Replace the timestamp / badge / right section. + + + + +```kotlin lines +conversations.setTrailingView(object : ConversationsViewHolderListener() { + override fun createView(context: Context, binding: CometchatConversationsListItemsBinding): View { + return TextView(context) + } + + override fun bindView( + context: Context, createdView: View, conversation: Conversation, + typingIndicator: TypingIndicator?, holder: RecyclerView.ViewHolder, + conversations: List, position: Int + ) { + (createdView as TextView).text = "${conversation.unreadMessageCount} unread" + } +}) +``` + + + + +```kotlin lines +CometChatConversations( + trailingView = { conversation, _ -> + if (conversation.unreadMessageCount > 0) { + Badge { Text("${conversation.unreadMessageCount}") } + } + } +) +``` + + + + +### State Views + + + + +```kotlin lines +conversations.setEmptyView(customEmptyView) +conversations.setErrorView(customErrorView) +conversations.setLoadingView(customLoadingView) +``` + + + + +```kotlin lines +CometChatConversations( + emptyView = { Text("No conversations yet") }, + errorView = { onRetry -> Button(onClick = onRetry) { Text("Retry") } }, + loadingView = { CircularProgressIndicator() } +) +``` + + + + +### Overflow Menu + + + + +```kotlin lines +conversations.setOverflowMenu(ImageButton(context).apply { + setImageResource(R.drawable.ic_filter) + setOnClickListener { /* show filter */ } +}) +``` + + + + +```kotlin lines +CometChatConversations( + overflowMenu = { + IconButton(onClick = { /* show filter */ }) { + Icon(painterResource(R.drawable.ic_filter), "Filter") + } + } +) +``` + + + + +--- + +## Menu Options + + + + +```kotlin lines +// Replace all options +conversations.setOptions { context, conversation -> + listOf( + CometChatPopupMenu.MenuItem(id = "archive", name = "Archive", onClick = { /* ... */ }), + CometChatPopupMenu.MenuItem(id = "mute", name = "Mute", onClick = { /* ... */ }) + ) +} + +// Append to defaults +conversations.setAddOptions { context, conversation -> + listOf( + CometChatPopupMenu.MenuItem(id = "pin", name = "Pin", onClick = { /* ... */ }) + ) +} +``` + + + + +```kotlin lines +CometChatConversations( + options = { context, conversation -> + listOf( + MenuItem(id = "archive", name = "Archive", onClick = { /* ... */ }), + MenuItem(id = "mute", name = "Mute", onClick = { /* ... */ }) + ) + }, + addOptions = { context, conversation -> + listOf(MenuItem(id = "pin", name = "Pin", onClick = { /* ... */ })) + } +) +``` + + + + +--- + +## Common Patterns + +### Minimal list — hide all chrome + + + + +```kotlin lines +conversations.setToolbarVisibility(View.GONE) +conversations.setSearchBoxVisibility(View.GONE) +``` + + + + +```kotlin lines +CometChatConversations( + hideToolbar = true, + hideSearchBox = true +) +``` + + + + +### Users-only conversations + + + + +```kotlin lines +conversations.setConversationsRequestBuilder( + ConversationsRequest.ConversationsRequestBuilder() + .setConversationType(CometChatConstants.CONVERSATION_TYPE_USER) +) +``` + + + + +```kotlin lines +CometChatConversations( + conversationsRequestBuilder = ConversationsRequest.ConversationsRequestBuilder() + .setConversationType(CometChatConstants.CONVERSATION_TYPE_USER) +) +``` + + + + +### Custom date formatting + + + + +```kotlin lines +conversations.setDateTimeFormatter(object : DateTimeFormatterCallback { + override fun today(timestamp: Long) = "Today" + override fun yesterday(timestamp: Long) = "Yesterday" + override fun otherDays(timestamp: Long) = SimpleDateFormat("MMM d", Locale.getDefault()).format(Date(timestamp)) + override fun time(timestamp: Long) = SimpleDateFormat("h:mm a", Locale.getDefault()).format(Date(timestamp)) + override fun minutes(diff: Long, timestamp: Long) = "${diff}m ago" + override fun hours(diff: Long, timestamp: Long) = "${diff}h ago" + override fun lastWeek(timestamp: Long) = "Last week" +}) +``` + + + + +```kotlin lines +CometChatConversations( + dateTimeFormatter = object : DateTimeFormatterCallback { + override fun today(timestamp: Long) = "Today" + override fun yesterday(timestamp: Long) = "Yesterday" + override fun otherDays(timestamp: Long) = SimpleDateFormat("MMM d", Locale.getDefault()).format(Date(timestamp)) + override fun time(timestamp: Long) = SimpleDateFormat("h:mm a", Locale.getDefault()).format(Date(timestamp)) + override fun minutes(diff: Long, timestamp: Long) = "${diff}m ago" + override fun hours(diff: Long, timestamp: Long) = "${diff}h ago" + override fun lastWeek(timestamp: Long) = "Last week" + } +) +``` + + + + +--- + +## Advanced Methods + +### Programmatic Selection + + + + +```kotlin lines +// Enable selection +conversations.setSelectionMode(UIKitConstants.SelectionMode.MULTIPLE) + +// Select a conversation +conversations.selectConversation(conversation, UIKitConstants.SelectionMode.MULTIPLE) + +// Get selected +val selected = conversations.getSelectedConversations() + +// Clear +conversations.clearSelection() +``` + + + + +Selection is managed via the `selectionMode` and `onSelection` parameters. The component handles selection state internally. + + + + +### ViewModel Access + +```kotlin lines +val factory = CometChatConversationsViewModelFactory( + repository = MyCustomRepository() // optional +) +val viewModel = ViewModelProvider(this, factory) + .get(CometChatConversationsViewModel::class.java) +``` + + + + +```kotlin lines +conversations.setViewModel(viewModel) +``` + + + + +```kotlin lines +CometChatConversations( + conversationsViewModel = viewModel +) +``` + + + + +See [ViewModel & Data](/ui-kit/android/v6/customization-viewmodel-data) for ListOperations, state observation, and custom repositories. + +--- + +## Style + + + + +Define a custom style in `themes.xml`: + +```xml themes.xml lines + + + +``` + + + + +```kotlin lines +CometChatConversations( + style = CometChatConversationsStyle.default().copy( + backgroundColor = Color(0xFFF5F5F5), + titleTextColor = Color(0xFF141414), + searchBoxStyle = CometChatSearchBoxStyle.default().copy( + backgroundColor = Color(0xFFFFFFFF) + ), + itemStyle = CometChatConversationsItemStyle.default().copy( + backgroundColor = Color.White, + titleTextColor = Color(0xFF141414), + subtitleTextColor = Color(0xFF727272), + avatarStyle = CometChatAvatarStyle.default().copy(cornerRadius = 12.dp), + badgeStyle = CometChatBadgeStyle.default().copy(backgroundColor = Color(0xFFF76808)), + dateStyle = CometChatDateStyle.default().copy(textColor = Color(0xFFA1A1A1)), + receiptStyle = CometChatReceiptStyle.default().copy(), + statusIndicatorStyle = CometChatStatusIndicatorStyle.default().copy(), + typingIndicatorStyle = CometChatTypingIndicatorStyle.default().copy() + ) + ) +) +``` + + + + +### Style Properties + +| Property | Description | +| --- | --- | +| `backgroundColor` | List background color | +| `titleTextColor` | Toolbar title color | +| `searchBoxStyle` | Search box appearance | +| `itemStyle.backgroundColor` | Row background | +| `itemStyle.selectedBackgroundColor` | Selected row background | +| `itemStyle.titleTextColor` | Conversation name color | +| `itemStyle.subtitleTextColor` | Last message preview color | +| `itemStyle.separatorColor` | Row separator color | +| `itemStyle.avatarStyle` | Avatar appearance | +| `itemStyle.badgeStyle` | Unread badge appearance | +| `itemStyle.dateStyle` | Timestamp appearance | +| `itemStyle.receiptStyle` | Read receipt icons | +| `itemStyle.statusIndicatorStyle` | Online/offline indicator | +| `itemStyle.typingIndicatorStyle` | Typing indicator text | +| `itemStyle.mentionStyle` | Mention highlight style | + +See [Component Styling](/ui-kit/android/v6/component-styling) for the full reference. + +--- + +## Next Steps + + + + Build a full chat layout with this component + + + Detailed styling reference with screenshots + + + Custom ViewModels, repositories, and ListOperations + + + Replace specific UI regions across all components + + diff --git a/ui-kit/android/v6/core-features.mdx b/ui-kit/android/v6/core-features.mdx new file mode 100644 index 000000000..ad33a43b5 --- /dev/null +++ b/ui-kit/android/v6/core-features.mdx @@ -0,0 +1,244 @@ +--- +title: "Core" +description: "Overview of CometChat's core chat features including instant messaging, media sharing, read receipts, typing indicators, user presence, reactions, mentions, threaded conversations, and moderation." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin-android` (Kotlin XML Views), `com.cometchat:chatuikit-compose-android` (Jetpack Compose) | +| Required setup | `CometChatUIKit.init()` then `CometChatUIKit.login()` — must complete before rendering any component | +| Core features | Instant Messaging, Media Sharing, Read Receipts, Mark as Unread, Typing Indicator, User Presence, Reactions, Mentions, Rich Text Formatting, Quoted Reply, Search, Threaded Conversations, Moderation, Report Message, Group Chat | +| Key components | `CometChatConversations`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader`, `CometChatUsers`, `CometChatGroups`, `CometChatGroupMembers`, `CometChatMessageInformation`, `CometChatThreadHeader` | +| Theming | See [Theming](/ui-kit/android/v6/theme-introduction) | + + + +The UI Kit components work together to deliver a complete chat experience. The sections below map each core feature to the components that power it. + +## Instant Messaging + +Real-time text messaging — users can send and receive instant messages. + + + + + +| Component | Role | +| --- | --- | +| [CometChatMessageComposer](/ui-kit/android/v6/message-composer) | Enables users to write and send text messages. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Renders sent and received messages using text bubbles. | + +## Media Sharing + +Share images, videos, audio files, and documents within conversations. + + + + + +| Component | Role | +| --- | --- | +| [CometChatMessageComposer](/ui-kit/android/v6/message-composer) | Provides an action sheet with options for sharing media files. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Renders media message bubbles — [Image](/ui-kit/android/v6/message-bubble-styling#image-bubble), [File](/ui-kit/android/v6/message-bubble-styling#file-bubble), [Audio](/ui-kit/android/v6/message-bubble-styling#audio-bubble), [Video](/ui-kit/android/v6/message-bubble-styling#video-bubble). | + +## Read Receipts + +Visibility into message status — delivered and read indicators. + + + + + +| Component | Role | +| --- | --- | +| [CometChatConversations](/ui-kit/android/v6/conversations) | Displays delivery status of the last message in each conversation item. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Shows read receipt status on every message bubble. | +| [CometChatMessageInformation](/ui-kit/android/v6/component-styling#message-information) | Shows detailed delivery and read status for a specific sent message. | + +## Mark as Unread + +Users can manually mark messages as unread to revisit important conversations later. The message list can start from the first unread message automatically. + + + + + +| Component | Role | +| --- | --- | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Provides the "Mark as unread" option in message actions and supports starting from the first unread message. | +| [CometChatConversations](/ui-kit/android/v6/conversations) | Reflects updated unread count in real-time. | + +## Typing Indicators + +Shows when a user is typing a response in real-time. + + + + + +| Component | Role | +| --- | --- | +| [CometChatConversations](/ui-kit/android/v6/conversations) | Shows real-time typing status in conversation items. | +| [CometChatMessageHeader](/ui-kit/android/v6/message-header) | Displays a "typing..." indicator when the other user or a group member is typing. | + +## User Presence + +See whether contacts are online or offline. + + + + + +| Component | Role | +| --- | --- | +| [CometChatConversations](/ui-kit/android/v6/conversations) | Shows user presence in conversation items. | +| [CometChatMessageHeader](/ui-kit/android/v6/message-header) | Displays user presence in the chat header. | +| [CometChatUsers](/ui-kit/android/v6/users) | Shows presence indicators in the user list. | +| [CometChatGroupMembers](/ui-kit/android/v6/group-members) | Shows presence indicators for group members. | + +## Reactions + +React to messages with emojis without typing a full response. + + + + + +| Component | Role | +| --- | --- | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Displays reactions on message bubbles and provides the reaction picker. | + +## Mentions + +Address specific users in a conversation by typing `@` to trigger mention suggestions. + + + + + +| Component | Role | +| --- | --- | +| [CometChatConversations](/ui-kit/android/v6/conversations) | Shows where users have been mentioned from the conversation list. | +| [CometChatMessageComposer](/ui-kit/android/v6/message-composer) | Triggers mention suggestions on `@` and inserts formatted mentions. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Renders mentions with distinct styling in the message flow. | + + +## Rich Text Formatting + +Rich Text Formatting allows users to style their messages with bold, italic, strikethrough, code, code blocks, blockquotes, ordered/unordered lists, and links. This brings richer expression to conversations and helps users emphasize key points. + + + + + +| Component | Role | +| --- | --- | +| [CometChatMessageComposer](/ui-kit/android/v6/message-composer) | Provides a built-in rich text editor with formatting toolbar and text selection menu items for bold, italic, strikethrough, code, links, lists, blockquotes, and code blocks. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Renders formatted messages with the appropriate styling automatically applied, ensuring that rich text formatting is displayed exactly as intended by the sender. | +## Threaded Conversations + +Respond directly to a specific message, keeping conversations organized. + + + + + +| Component | Role | +| --- | --- | +| [CometChatThreadHeader](/ui-kit/android/v6/threaded-messages-header) | Displays all replies made to a particular message. | +| [CometChatMessageComposer](/ui-kit/android/v6/message-composer) | Allows composing messages within a thread. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Displays threaded messages in context. | + +## Quoted Replies + +Reply to specific messages by selecting "Reply" from the message action menu, maintaining context in the conversation. + + + + + +| Component | Role | +| --- | --- | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Provides the "Reply" option in message actions. | +| [CometChatMessageComposer](/ui-kit/android/v6/message-composer) | Shows the quoted reply above the input field for context. | + +## Group Chats + +Conversations with multiple participants — team collaborations, group discussions, and communities. + + + + + +| Component | Role | +| --- | --- | +| [CometChatGroups](/ui-kit/android/v6/groups) | Lists and manages groups. | +| [CometChatGroupMembers](/ui-kit/android/v6/group-members) | Displays and manages group members with roles and actions. | + +## Moderation + +Automatically filter and manage inappropriate content based on predefined rules. + + + + + + +Learn more about setting up moderation rules in the [Moderation](/moderation/overview) documentation. + + +| Component | Role | +| --- | --- | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Handles moderated messages, displaying blocked content based on your moderation settings. | + +## Report Message + +Users can report inappropriate messages by choosing from predefined reasons with optional remarks. + + +Learn more about flagged messages in the [Flagged Messages](/moderation/flagged-messages) documentation. + + + + + + +| Component | Role | +| --- | --- | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Provides the "Report Message" option in message actions. | + +## Conversation and Advanced Search + +Conversation and Advanced Search enables users to quickly find conversations, messages, and media across chats in real time. It supports filters, scopes, and custom actions, allowing users to locate content efficiently while keeping the chat experience smooth and intuitive. + + + + + +| Component | Role | +| --- | --- | +| [CometChatSearch](/ui-kit/android/v6/search) | Allows users to search across conversations and messages in real time. Users can click on a result to open the conversation or jump directly to a specific message. | +| [CometChatMessageHeader](/ui-kit/android/v6/message-header) | Shows the search button in the chat header, allowing users to search within a conversation. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Shows the selected message when clicked from search results and highlights it in the message list. | +| [CometChatConversations](/ui-kit/android/v6/conversations) | Displays the search input. | + +--- + +## Next Steps + + + + Browse all available UI Kit components + + + Customize the look and feel of your chat UI + + + Add audio and video calling + + + Explore AI-powered chat capabilities + + diff --git a/ui-kit/android/v6/custom-text-formatter-guide.mdx b/ui-kit/android/v6/custom-text-formatter-guide.mdx new file mode 100644 index 000000000..592fb0b1d --- /dev/null +++ b/ui-kit/android/v6/custom-text-formatter-guide.mdx @@ -0,0 +1,174 @@ +--- +title: "Custom Text Formatter" +sidebarTitle: "Custom Text Formatter" +description: "Extend CometChatTextFormatter to build custom inline text patterns with tracking characters and suggestion lists." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin` · `com.cometchat:chatuikit-jetpack` | +| Key class | `CometChatTextFormatter` (abstract base class for custom formatters) | +| Required setup | `CometChatUIKit.init()` then `CometChatUIKit.login("UID")` | +| Purpose | Extend to create custom inline text patterns with tracking characters, suggestion lists, and span formatting | +| Features | Tracking character activation, suggestion list, span formatting per context (composer, bubbles, conversations), pre-send hooks | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-android/tree/v6/sample-app-kotlin) | +| Related | [Mentions Formatter](/ui-kit/android/v6/mentions-formatter-guide) \| [ShortCut Formatter](/ui-kit/android/v6/shortcut-formatter-guide) \| [All Guides](/ui-kit/android/v6/guide-overview) | + + + +`CometChatTextFormatter` is an abstract class for formatting text in the message composer and message bubbles. Extend it to build custom formatters — hashtags, shortcuts, or any pattern triggered by a tracking character. + +| Capability | Description | +| --- | --- | +| Tracking character | Activates the formatter when the user types a specific character (e.g., `#`, `!`) | +| Suggestion list | Populates a dropdown of `SuggestionItem` objects as the user types | +| Span formatting | Applies `SpannableStringBuilder` spans per context: composer, left/right bubbles, conversations | +| Pre-send hook | `handlePreMessageSend` lets you modify the message before it's sent | +| Component integration | Plugs into any component via `setTextFormatters()` | + +--- + +## Steps + +### 1. Create a class extending CometChatTextFormatter + +Pass your tracking character to the superclass constructor. + + + +```kotlin lines +class HashTagFormatter : CometChatTextFormatter('#') { + private val suggestions: MutableList = ArrayList() +} +``` + + +```kotlin lines +// Same class — formatters are shared between both modules +class HashTagFormatter : CometChatTextFormatter('#') { + private val suggestions: MutableList = ArrayList() +} +``` + + + +### 2. Override the search method + +Called when the user types after the tracking character. Match input against your data and update the suggestion list. + +```kotlin lines +override fun search(context: Context, queryString: String?) { + suggestions.clear() + val query = "#${queryString ?: ""}" + // Match against your hashtag data source + val matchingTags = getMatchingTags(query) + for (tag in matchingTags) { + val item = SuggestionItem("", tag, null, null, tag, null, null) + item.isHideLeadingIcon = true + suggestions.add(item) + } + setSuggestionItemList(suggestions) +} +``` + +### 3. Override onScrollToBottom + +Required by the base class. Implement pagination logic or leave empty. + +```kotlin +override fun onScrollToBottom() { + // Load more suggestions if needed +} +``` + +### 4. Override span formatting methods (optional) + +Customize how matched text renders in different contexts using `SpannableStringBuilder`. + +```kotlin lines +override fun prepareLeftMessageBubbleSpan( + context: Context, baseMessage: BaseMessage, spannable: SpannableStringBuilder +): SpannableStringBuilder? { + // Apply custom spans for incoming message bubbles + return applyHashTagSpans(spannable, Color.parseColor("#5dff05")) +} + +override fun prepareRightMessageBubbleSpan( + context: Context, baseMessage: BaseMessage, spannable: SpannableStringBuilder +): SpannableStringBuilder? { + // Apply custom spans for outgoing message bubbles + return applyHashTagSpans(spannable, Color.parseColor("#30b3ff")) +} +``` + +### 5. Integrate with a component + + + +```kotlin lines +import com.cometchat.uikit.core.CometChatUIKit + +val textFormatters = CometChatUIKit.getDataSource().getTextFormatters(this, messageComposer.additionParameter) +textFormatters.add(HashTagFormatter()) +messageComposer.setTextFormatters(textFormatters) +``` + + +```kotlin lines +import com.cometchat.uikit.core.CometChatUIKit + +// In your composable or ViewModel setup +val textFormatters = CometChatUIKit.getDataSource().getTextFormatters(context, additionParameter) +textFormatters.add(HashTagFormatter()) + +CometChatMessageComposer( + user = user, + textFormatters = textFormatters +) +``` + + + +Pass the same list to `CometChatMessageList` and `CometChatConversations` via their `setTextFormatters()` methods to apply formatting across all contexts. + +--- + +## Methods Reference + +| Method | Description | +| --- | --- | +| `search(Context, String)` | Abstract — called when user types after the tracking character. Update the suggestion list here. | +| `onScrollToBottom()` | Abstract — called when the suggestion list scrolls to the bottom. Implement pagination or leave empty. | +| `onItemClick(Context, SuggestionItem, User, Group)` | Called when a suggestion item is selected. Override to customize insertion behavior. | +| `handlePreMessageSend(Context, BaseMessage)` | Called before a message is sent. Override to modify the message (e.g., add metadata). | +| `prepareLeftMessageBubbleSpan(Context, BaseMessage, SpannableStringBuilder)` | Override to format text in incoming message bubbles. | +| `prepareRightMessageBubbleSpan(Context, BaseMessage, SpannableStringBuilder)` | Override to format text in outgoing message bubbles. | +| `prepareComposerSpan(Context, BaseMessage, SpannableStringBuilder)` | Override to format text in the message composer. | +| `prepareConversationSpan(Context, BaseMessage, SpannableStringBuilder)` | Override to format text in the conversations list preview. | +| `setSuggestionItemList(List)` | Updates the suggestion dropdown with new items. | +| `setDisableSuggestions(boolean)` | Disables the suggestion dropdown entirely. (`protected` — accessible from subclasses only.) | +| `setInfoText(String)` | Sets informational text displayed above the suggestion list. | +| `setInfoVisibility(boolean)` | Toggles visibility of the info text. | +| `setShowLoadingIndicator(boolean)` | Shows/hides a loading spinner in the suggestion dropdown. | +| `getTrackingCharacter()` | Returns the tracking character passed to the constructor. | + +--- + +## Next Steps + + + + Built-in @mention formatting with styled tokens + + + Shortcut text expansion via the message-shortcuts extension + + + Browse all feature and formatter guides + + + Full working sample application on GitHub + + \ No newline at end of file diff --git a/ui-kit/android/v6/customization-events.mdx b/ui-kit/android/v6/customization-events.mdx new file mode 100644 index 000000000..61991429a --- /dev/null +++ b/ui-kit/android/v6/customization-events.mdx @@ -0,0 +1,227 @@ +--- +title: "Events & Callbacks" +description: "Handle user interaction events, selection mode, and global UI Kit events." +--- + +The UI Kit provides two levels of event handling: component-level callbacks set directly on a component, and global events via the `CometChatEvents` singleton using Kotlin `SharedFlow`. + +--- + +## Component-Level Callbacks + +### Click Callbacks + + + + +```kotlin lines +conversations.setOnItemClick { conversation -> + // Navigate to chat screen +} + +conversations.setOnItemLongClick { conversation -> + // Show context menu +} + +conversations.setOnBackPress { + // Handle back navigation +} + +conversations.setOnSearchClick { + // Open search +} + +conversations.setOnError { exception -> + Log.e("Conversations", "Error: ${exception.message}") +} + +conversations.setOnLoad { list -> + Log.d("Conversations", "Loaded ${list.size} conversations") +} + +conversations.setOnEmpty { + Log.d("Conversations", "No conversations") +} +``` + + + + +```kotlin lines +CometChatConversations( + onItemClick = { conversation -> + // Navigate to chat screen + }, + onItemLongClick = { conversation -> + // Show context menu + }, + onBackPress = { + // Handle back navigation + }, + onSearchClick = { + // Open search + }, + onError = { exception -> + Log.e("Conversations", "Error: ${exception.message}") + }, + onLoad = { list -> + Log.d("Conversations", "Loaded ${list.size} conversations") + }, + onEmpty = { + Log.d("Conversations", "No conversations") + } +) +``` + + + + +--- + +## Selection Mode + +Enable single or multi-select on list components: + + + + +```kotlin lines +// Enable multi-select mode +conversations.setSelectionMode(UIKitConstants.SelectionMode.MULTIPLE) + +// Listen for selection changes +conversations.setOnSelection { selectedList -> + updateToolbar(selectedList.size) +} + +// Get selected items +val selected = conversations.getSelectedConversations() + +// Clear selection +conversations.clearSelection() +``` + + + + +```kotlin lines +CometChatConversations( + selectionMode = UIKitConstants.SelectionMode.MULTIPLE, + onSelection = { selectedList -> + updateToolbar(selectedList.size) + } +) +``` + + + + +--- + +## Global Events (CometChatEvents) + +Global events are emitted by UI Kit components when actions happen anywhere in the app. They use Kotlin `SharedFlow` for reactive, type-safe event distribution. Subscribe from any coroutine scope. + +### Event Flows + +| Flow | Sealed Class | Fires When | +| --- | --- | --- | +| `CometChatEvents.messageEvents` | `CometChatMessageEvent` | Messages sent, edited, deleted, reactions, typing | +| `CometChatEvents.callEvents` | `CometChatCallEvent` | Calls initiated, accepted, rejected, ended | +| `CometChatEvents.conversationEvents` | `CometChatConversationEvent` | Conversations deleted or updated | +| `CometChatEvents.groupEvents` | `CometChatGroupEvent` | Groups created, updated, members changed | +| `CometChatEvents.userEvents` | `CometChatUserEvent` | Users blocked/unblocked | +| `CometChatEvents.uiEvents` | `CometChatUIEvent` | UI-level events (panels, dialogs) | + +### Subscribing to Events + +```kotlin lines +import com.cometchat.uikit.core.events.CometChatEvents +import com.cometchat.uikit.core.events.CometChatMessageEvent + +// Subscribe in a ViewModel or lifecycle-aware scope +viewModelScope.launch { + CometChatEvents.messageEvents.collect { event -> + when (event) { + is CometChatMessageEvent.MessageSent -> { + // Handle sent message: event.message, event.status + } + is CometChatMessageEvent.MessageDeleted -> { + // Handle deleted message: event.message + } + is CometChatMessageEvent.MessageEdited -> { + // Handle edited message: event.message + } + is CometChatMessageEvent.ReactionAdded -> { + // Handle reaction: event.event + } + else -> { /* other message events */ } + } + } +} +``` + +### Emitting Events + +```kotlin lines +// Emit from anywhere — thread-safe +CometChatEvents.emitMessageEvent( + CometChatMessageEvent.MessageSent(message, MessageStatus.SUCCESS) +) + +CometChatEvents.emitCallEvent( + CometChatCallEvent.OutgoingCall(call) +) + +CometChatEvents.emitConversationEvent( + CometChatConversationEvent.ConversationDeleted(conversation) +) +``` + +### Key Event Types + +**Message Events:** + +| Event | Data | +| --- | --- | +| `MessageSent` | `message`, `status` | +| `MessageEdited` | `message`, `status` | +| `MessageDeleted` | `message` | +| `MessageRead` | `message` | +| `ReactionAdded` / `ReactionRemoved` | `event` (ReactionEvent) | +| `TypingStarted` / `TypingEnded` | `indicator` (TypingIndicator) | +| `MessagesDelivered` / `MessagesRead` | `receipt` (MessageReceipt) | + +**Call Events:** + +| Event | Data | +| --- | --- | +| `OutgoingCall` | `call` | +| `CallAccepted` | `call` | +| `CallRejected` | `call` | +| `CallEnded` | `call` | + +**Conversation Events:** + +| Event | Data | +| --- | --- | +| `ConversationDeleted` | `conversation` | +| `ConversationUpdated` | `conversation` | + +--- + +## Component vs Global Events + +| Aspect | Component Callbacks | Global Events | +| --- | --- | --- | +| Scope | Single component instance | App-wide | +| Registration | `setOnItemClick {}` or composable parameter | `CometChatEvents.*.collect {}` | +| Use case | Handle user interaction on a specific screen | Cross-component coordination | +| Example | Tap a conversation → navigate | Message sent → update conversation list | + +--- + +## Related + +- [Events Reference](/ui-kit/android/v6/events) — Full list of all event types. +- [Customization Overview](/ui-kit/android/v6/customization-overview) — SDK Listeners vs UIKit Events distinction. diff --git a/ui-kit/android/v6/customization-menu-options.mdx b/ui-kit/android/v6/customization-menu-options.mdx new file mode 100644 index 000000000..ff8ea7b08 --- /dev/null +++ b/ui-kit/android/v6/customization-menu-options.mdx @@ -0,0 +1,182 @@ +--- +title: "Menu & Options" +description: "Add, replace, or extend context menu actions on components." +--- + +Components provide context menus (e.g., long-press on a conversation or message). You can replace all options or append custom ones. + +--- + +## setOptions vs addOptions + +| Method | Behavior | +| --- | --- | +| `setOptions` | Replaces all default options with your custom list | +| `addOptions` | Appends your custom options to the existing defaults | + +Use `addOptions` to keep defaults (like "Delete") and add your own. Use `setOptions` for full control. + +--- + +## Adding Custom Options + + + + +```kotlin lines +import com.cometchat.uikit.kotlin.presentation.shared.popupmenu.CometChatPopupMenu + +conversations.addOptions { context, conversation -> + listOf( + CometChatPopupMenu.MenuItem( + id = "pin", + name = "Pin Conversation", + startIcon = ContextCompat.getDrawable(context, R.drawable.ic_pin), + onClick = { pinConversation(conversation) } + ) + ) +} +``` + + + + +```kotlin lines +import com.cometchat.uikit.compose.shared.views.popupmenu.MenuItem + +CometChatConversations( + addOptions = { context, conversation -> + listOf( + MenuItem( + id = "pin", + name = "Pin Conversation", + startIcon = painterResource(R.drawable.ic_pin), + onClick = { pinConversation(conversation) } + ) + ) + } +) +``` + + + + +--- + +## Replacing All Options + + + + +```kotlin lines +conversations.setOptions { context, conversation -> + listOf( + CometChatPopupMenu.MenuItem( + id = "archive", + name = "Archive", + startIcon = ContextCompat.getDrawable(context, R.drawable.ic_archive), + onClick = { archiveConversation(conversation) } + ), + CometChatPopupMenu.MenuItem( + id = "mute", + name = "Mute", + startIcon = ContextCompat.getDrawable(context, R.drawable.ic_mute), + onClick = { muteConversation(conversation) } + ) + ) +} +``` + + + + +```kotlin lines +CometChatConversations( + options = { context, conversation -> + listOf( + MenuItem( + id = "archive", + name = "Archive", + startIcon = painterResource(R.drawable.ic_archive), + onClick = { archiveConversation(conversation) } + ), + MenuItem( + id = "mute", + name = "Mute", + startIcon = painterResource(R.drawable.ic_mute), + onClick = { muteConversation(conversation) } + ) + ) + } +) +``` + + + + +--- + +## MenuItem Properties + + + + +`CometChatPopupMenu.MenuItem`: + +| Property | Type | Description | +| --- | --- | --- | +| `id` | `String` | Unique identifier | +| `name` | `String` | Display text | +| `startIcon` | `Drawable?` | Icon at the start | +| `endIcon` | `Drawable?` | Icon at the end | +| `startIconTint` | `@ColorInt Int` | Start icon tint | +| `textColor` | `@ColorInt Int` | Text color | +| `textAppearance` | `@StyleRes Int` | Text appearance | +| `onClick` | `(() -> Unit)?` | Click callback | + + + + +`MenuItem`: + +| Property | Type | Description | +| --- | --- | --- | +| `id` | `String` | Unique identifier | +| `name` | `String` | Display text | +| `startIcon` | `Painter?` | Icon at the start | +| `endIcon` | `Painter?` | Icon at the end | +| `startIconTint` | `Color?` | Start icon tint | +| `textColor` | `Color?` | Text color | +| `textStyle` | `TextStyle?` | Text style | +| `onClick` | `(() -> Unit)?` | Click callback | + + + + +Both modules provide convenience factory methods: + +```kotlin lines +// Simple menu item (no icons) +MenuItem.simple(id = "pin", name = "Pin") { /* onClick */ } + +// Menu item with icons (Compose) +MenuItem.withIcons(id = "pin", name = "Pin", startIcon = painterResource(R.drawable.ic_pin)) { /* onClick */ } +``` + +--- + +## Components with Menu Options + +| Component | Data passed to callback | +| --- | --- | +| `CometChatConversations` | `(Context, Conversation)` | +| `CometChatUsers` | `(Context, User)` | +| `CometChatGroups` | `(Context, Group)` | +| `CometChatGroupMembers` | `(Context, GroupMember)` | +| `CometChatCallLogs` | `(Context, CallLog)` | + +--- + +## Related + +- [Customization Overview](/ui-kit/android/v6/customization-overview) — See all customization categories. diff --git a/ui-kit/android/v6/customization-overview.mdx b/ui-kit/android/v6/customization-overview.mdx new file mode 100644 index 000000000..f680af4b9 --- /dev/null +++ b/ui-kit/android/v6/customization-overview.mdx @@ -0,0 +1,235 @@ +--- +title: "Overview" +description: "Understand the layered architecture and discover all customization entry points in the CometChat Android UI Kit." +--- + +Every component in the UI Kit follows a layered architecture. Understanding these layers is the key to deep customization without rebuilding components from scratch. + +--- + +## Architecture Layers + +Each component is built from four layers, from outermost (UI) to innermost (data): + +| Layer | Role | Example | +| --- | --- | --- | +| View | Renders UI, handles user interaction, exposes setter methods | `CometChatConversations`, `CometChatMessageList` | +| ViewModel | Manages state, business logic, list operations, and SDK listeners | `CometChatConversationsViewModel`, `CometChatMessageListViewModel` | +| Repository | Abstracts data fetching — can be swapped for custom implementations | `ConversationsRepository`, `MessageListRepository` | +| DataSource | Direct SDK calls — the lowest layer that talks to CometChat servers | `ConversationsDataSourceImpl`, `MessageListDataSourceImpl` | + +```mermaid +block-beta + columns 1 + A["View Layer\nCometChatConversations / Compose\nUI rendering, styles, callbacks"] + B["ViewModel Layer\nCometChatConversationsViewModel\nState, ListOperations, SDK listeners"] + C["Repository Layer\nConversationsRepository\nData abstraction — swappable"] + D["DataSource Layer\nConversationsDataSourceImpl\nDirect CometChat SDK calls"] + + A --> B + B --> C + C --> D +``` + +The ViewModel lives in `chatuikit-core` and is shared by both Kotlin XML Views and Jetpack Compose. The View layer is module-specific. + +--- + +## Overriding the ViewModel + +Every component accepts an external ViewModel. This lets you subclass the default ViewModel to override behavior, or provide a completely custom one. + + + + +```kotlin lines +// 1. Subclass the ViewModel to override behavior +class MyConversationsViewModel( + getConversationsUseCase: GetConversationsUseCase, + deleteConversationUseCase: DeleteConversationUseCase, + refreshConversationsUseCase: RefreshConversationsUseCase +) : CometChatConversationsViewModel( + getConversationsUseCase, + deleteConversationUseCase, + refreshConversationsUseCase +) { + // Override any behavior here +} + +// 2. Create a factory with optional custom repository +val factory = CometChatConversationsViewModelFactory( + repository = MyCustomRepository() // or use default +) + +// 3. Create the ViewModel via ViewModelProvider +val viewModel = ViewModelProvider(this, factory) + .get(MyConversationsViewModel::class.java) + +// 4. Inject into the component +val conversations = findViewById(R.id.conversations) +conversations.setViewModel(viewModel) +``` + + + + +```kotlin lines +// 1. Subclass the ViewModel to override behavior +class MyConversationsViewModel( + getConversationsUseCase: GetConversationsUseCase, + deleteConversationUseCase: DeleteConversationUseCase, + refreshConversationsUseCase: RefreshConversationsUseCase +) : CometChatConversationsViewModel( + getConversationsUseCase, + deleteConversationUseCase, + refreshConversationsUseCase +) { + // Override any behavior here +} + +// 2. Create a factory with optional custom repository +val factory = CometChatConversationsViewModelFactory( + repository = MyCustomRepository() // or use default +) + +// 3. Create and pass to the component +val viewModel: MyConversationsViewModel = viewModel(factory = factory) + +CometChatConversations( + conversationsViewModel = viewModel +) +``` + + + + +--- + +## Overriding the Repository + +Each ViewModel is created via a Factory that accepts a custom Repository. Implement the repository interface to change how data is fetched. + +```kotlin lines +// 1. Implement the repository interface +class MyConversationsRepository : ConversationsRepository { + override suspend fun fetchConversations(request: ConversationsRequest): List { + // Custom data fetching logic — local DB, filtered API call, etc. + } + // ... implement other methods +} + +// 2. Create a factory with your custom repository +val factory = CometChatConversationsViewModelFactory( + repository = MyConversationsRepository() +) + +// 3. Create the ViewModel using the factory +val viewModel = ViewModelProvider(this, factory) + .get(CometChatConversationsViewModel::class.java) + +// 4. Set it on the component +conversations.setViewModel(viewModel) +``` + +Available repository interfaces in `chatuikit-core`: + +| Repository | Used by | +| --- | --- | +| `ConversationsRepository` | `CometChatConversationsViewModel` | +| `MessageListRepository` | `CometChatMessageListViewModel` | +| `MessageComposerRepository` | `CometChatMessageComposerViewModel` | +| `MessageHeaderRepository` | `CometChatMessageHeaderViewModel` | +| `UsersRepository` | `CometChatUsersViewModel` | +| `GroupsRepository` | `CometChatGroupsViewModel` | +| `GroupMembersRepository` | `CometChatGroupMembersViewModel` | +| `CallLogsRepository` | `CometChatCallLogsViewModel` | +| `CallButtonsRepository` | `CometChatCallButtonsViewModel` | +| `ReactionListRepository` | `CometChatReactionListViewModel` | +| `MessageInformationRepository` | `CometChatMessageInformationViewModel` | +| `StickerRepository` | `CometChatStickerKeyboardViewModel` | +| `PollRepository` | `CometChatCreatePollViewModel` | + +--- + +## ListOperations API + +All list-based ViewModels implement the `ListOperations` interface, giving you a consistent API to manipulate list data programmatically. + +### Available Operations + +| Method | Description | +| --- | --- | +| `addItem(item)` | Appends an item to the list | +| `addItems(items)` | Appends multiple items | +| `removeItem(item)` | Removes the first matching item | +| `removeItemAt(index)` | Removes item at index | +| `updateItem(item, predicate)` | Replaces the first item matching the predicate | +| `clearItems()` | Removes all items | +| `getItems()` | Returns a copy of all items | +| `getItemAt(index)` | Returns item at index (or null) | +| `getItemCount()` | Returns the item count | +| `moveItemToTop(item)` | Moves an item to index 0 (or adds it there) | +| `batch { }` | Performs multiple operations in a single emission | + +### Example + +```kotlin lines +// Batch operations — emits only once for all changes +viewModel.batch { + add(newConversation1) + add(newConversation2) + remove(oldConversation) + moveToTop(pinnedConversation) +} +``` + +Batch operations are critical for performance when handling rapid updates (e.g., multiple messages arriving simultaneously). + +--- + +## SDK Listeners vs UIKit Events + +ViewModels use two event systems for real-time updates: + +| Aspect | SDK Listeners | UIKit Events | +| --- | --- | --- | +| Source | CometChat server | UIKit components | +| Direction | Server → Client | Component → Component | +| Registration | `CometChat.add*Listener()` | `CometChatEvents.*Events.collect {}` | +| Purpose | Incoming messages, calls, presence | UI-initiated actions (message sent, call accepted) | + +Both are needed for full functionality. SDK listeners handle server-pushed events, UIKit events handle inter-component communication. + +--- + +## Customization Categories + + + + Replace specific regions of a component's UI (leading view, title, subtitle, trailing view). + + + Customize visual appearance using XML theme attributes or Compose style data classes. + + + Configure data fetching, observe state flows, and call mutation methods on the ViewModel. + + + Handle click events, selection mode, and global UI Kit events. + + + Replace or restyle the default empty, error, and loading state views. + + + Create custom text processors for hashtags, mentions, links, or any pattern. + + + Add, replace, or extend context menu actions and composer attachment options. + + + +--- + +## What's Next + +Start with [Styles](/ui-kit/android/v6/customization-styles) for quick visual changes, or [ViewModel & Data](/ui-kit/android/v6/customization-viewmodel-data) for behavior customization. diff --git a/ui-kit/android/v6/customization-state-views.mdx b/ui-kit/android/v6/customization-state-views.mdx new file mode 100644 index 000000000..9296e3703 --- /dev/null +++ b/ui-kit/android/v6/customization-state-views.mdx @@ -0,0 +1,189 @@ +--- +title: "State Views" +description: "Replace the default empty, error, and loading state views with custom layouts." +--- + +Components display state views when the list is empty, an error occurs, or data is loading. You can replace these with your own custom views. + +--- + +## State Types + +| State | When it shows | +| --- | --- | +| Loading | Data is being fetched | +| Empty | No data to display | +| Error | An error occurred during data fetching | + +--- + +## Replacing State Views + + + + +Each component accepts a `View?` for each state: + +```kotlin lines +// Custom empty view +val emptyView = LayoutInflater.from(context) + .inflate(R.layout.custom_empty_state, null) +conversations.setEmptyView(emptyView) + +// Custom error view +val errorView = LayoutInflater.from(context) + .inflate(R.layout.custom_error_state, null) +conversations.setErrorView(errorView) + +// Custom loading view +val loadingView = LayoutInflater.from(context) + .inflate(R.layout.custom_loading_state, null) +conversations.setLoadingView(loadingView) +``` + +Example custom empty layout: + +```xml res/layout/custom_empty_state.xml lines + + + + + + +``` + + + + +Each component accepts `@Composable` lambdas for each state: + +```kotlin lines +CometChatConversations( + emptyView = { + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Icon( + painter = painterResource(R.drawable.ic_empty_conversations), + contentDescription = "No conversations", + modifier = Modifier.size(120.dp), + tint = CometChatTheme.colorScheme.iconTintSecondary + ) + Spacer(modifier = Modifier.height(16.dp)) + Text( + text = "No conversations yet", + style = CometChatTheme.typography.heading2Medium, + color = CometChatTheme.colorScheme.textColorPrimary + ) + } + }, + errorView = { onRetry -> + Column( + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text("Something went wrong") + Spacer(modifier = Modifier.height(8.dp)) + Button(onClick = onRetry) { + Text("Retry") + } + } + }, + loadingView = { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center + ) { + CircularProgressIndicator() + } + } +) +``` + +Note: the `errorView` lambda receives an `onRetry` callback you can wire to a retry button. + + + + +--- + +## Hiding State Views + + + + +Components like `CometChatMessageList` provide explicit hide methods: + +```kotlin lines +messageList.setHideLoadingState(true) +messageList.setHideEmptyState(true) +messageList.setHideErrorState(true) +``` + +For components that don't have dedicated hide methods (e.g., `CometChatConversations`), pass `null` to remove a custom state view: + +```kotlin lines +conversations.setEmptyView(null) +conversations.setErrorView(null) +conversations.setLoadingView(null) +``` + + + + +```kotlin lines +CometChatConversations( + hideEmptyState = true, + hideErrorState = true, + hideLoadingState = true +) + +CometChatMessageList( + hideEmptyState = true, + hideErrorState = true, + hideLoadingState = true +) +``` + + + + +--- + +## Components with State Views + +State views are available on all list-based components: + +| Component | States supported | +| --- | --- | +| `CometChatConversations` | Loading, Empty, Error | +| `CometChatUsers` | Loading, Empty, Error | +| `CometChatGroups` | Loading, Empty, Error | +| `CometChatGroupMembers` | Loading, Empty, Error | +| `CometChatCallLogs` | Loading, Empty, Error | +| `CometChatMessageList` | Loading, Empty, Error | + +--- + +## Related + +- [Customization Overview](/ui-kit/android/v6/customization-overview) — See all customization categories. +- [View Slots](/ui-kit/android/v6/customization-view-slots) — Replace specific regions of list items. diff --git a/ui-kit/android/v6/customization-styles.mdx b/ui-kit/android/v6/customization-styles.mdx new file mode 100644 index 000000000..afa2a6c40 --- /dev/null +++ b/ui-kit/android/v6/customization-styles.mdx @@ -0,0 +1,231 @@ +--- +title: "Styles" +description: "Customize component appearance using XML theme attributes, programmatic setters, or Compose style data classes." +--- + +The UI Kit supports multiple approaches to styling depending on your module. + +--- + +## Styling Approaches + + + + +Two ways to style components: + +1. **XML theme attributes** — declarative, app-wide theming via `themes.xml` +2. **Programmatic `CometChatTheme` setters** — runtime color/font overrides + +Programmatic setters take precedence over XML theme attributes. + +### XML Theme Hierarchy + +```xml themes.xml lines + + + + + + + + +``` + +### Programmatic Overrides + +```kotlin lines +// Override theme colors at runtime +CometChatTheme.setPrimaryColor(Color.parseColor("#6851D6")) +CometChatTheme.setBackgroundColor1(Color.parseColor("#FFFFFF")) +CometChatTheme.setTextColorPrimary(Color.parseColor("#141414")) +CometChatTheme.setTextColorSecondary(Color.parseColor("#727272")) +``` + + + + +Components accept a `style` parameter — a data class with `.default()` factory and `.copy()` for overrides: + +```kotlin lines +CometChatConversations( + style = CometChatConversationsStyle.default().copy( + backgroundColor = Color(0xFFF5F5F5), + titleTextColor = Color(0xFF6851D6), + itemStyle = CometChatConversationsItemStyle.default().copy( + avatarStyle = CometChatAvatarStyle.default().copy( + cornerRadius = 12.dp, + backgroundColor = Color(0xFFE8E0FF) + ), + badgeStyle = CometChatBadgeStyle.default().copy( + backgroundColor = Color(0xFFF76808) + ) + ) + ) +) +``` + +Global theme colors are provided via `CometChatTheme`: + +```kotlin lines +CometChatTheme( + colorScheme = lightColorScheme().copy( + primary = Color(0xFF6851D6), + backgroundColor1 = Color(0xFFFFFFFF), + textColorPrimary = Color(0xFF141414) + ) +) { + // All components inside use these colors as defaults +} +``` + + + + +--- + +## Font Customization + + + + +Override fonts at the theme level: + +```xml themes.xml lines + +``` + +| Attribute | Usage | +| --- | --- | +| `cometchatFontBold` | Headings, titles, emphasized text | +| `cometchatFontMedium` | Subtitles, secondary headings | +| `cometchatFontRegular` | Body text, descriptions, input fields | + + + + +Provide custom typography via `CometChatTheme`: + +```kotlin lines +CometChatTheme( + typography = CometChatTypography( + titleBold = TextStyle(fontFamily = myFontFamily, fontWeight = FontWeight.Bold, fontSize = 20.sp), + bodyRegular = TextStyle(fontFamily = myFontFamily, fontWeight = FontWeight.Normal, fontSize = 14.sp), + caption1Regular = TextStyle(fontFamily = myFontFamily, fontWeight = FontWeight.Normal, fontSize = 12.sp) + ) +) { + // All components use custom typography +} +``` + + + + +--- + +## CometChatTheme Color Tokens + +These tokens are available for programmatic override (Kotlin XML) or via `CometChatColorScheme` (Compose): + +### Colors + +| Token | Description | +| --- | --- | +| `primaryColor` | Brand color for buttons, links, highlights | +| `backgroundColor1` – `backgroundColor4` | Background levels | +| `textColorPrimary` / `Secondary` / `Tertiary` | Text colors | +| `textColorDisabled` / `White` / `Highlight` | Special text colors | +| `errorColor` / `successColor` / `warningColor` / `infoColor` | Alert colors | +| `strokeColorDefault` / `Light` / `Dark` / `Highlight` | Border colors | + +### Icon Tints + +| Token | Description | +| --- | --- | +| `iconTintPrimary` / `Secondary` / `Tertiary` | Icon tints | +| `iconTintWhite` / `Highlight` | Special icon tints | + +### Button Colors + +| Token | Description | +| --- | --- | +| `primaryButtonBackgroundColor` / `TextColor` / `IconTint` | Primary button | +| `secondaryButtonBackgroundColor` / `TextColor` / `IconTint` | Secondary button | + +--- + +## Per-Component Style Properties + +Each component has its own style data class with nested sub-component styles. Here's the pattern for key components: + +### CometChatConversations + +| Property | Description | +| --- | --- | +| `backgroundColor` | List background | +| `titleTextColor` | Toolbar title color | +| `searchBoxStyle` | Search box styling | +| `itemStyle.avatarStyle` | Avatar in each row | +| `itemStyle.badgeStyle` | Unread badge | +| `itemStyle.dateStyle` | Timestamp | +| `itemStyle.receiptStyle` | Read receipts | +| `itemStyle.statusIndicatorStyle` | Online/offline indicator | +| `itemStyle.typingIndicatorStyle` | Typing indicator | + +### CometChatMessageList + +| Property | Description | +| --- | --- | +| `backgroundColor` | List background | +| `incomingMessageBubbleStyle` | Incoming bubble appearance | +| `outgoingMessageBubbleStyle` | Outgoing bubble appearance | +| `actionBubbleStyle` | Group action bubbles | +| `callActionBubbleStyle` | Call action bubbles | + +### CometChatMessageComposer + +| Property | Description | +| --- | --- | +| `backgroundColor` | Composer background | +| `attachmentIconTint` | Attachment button tint | +| `voiceRecordingIconTint` | Voice recording button tint | +| `aiIconTint` | AI button tint | +| `sendButtonStyle` | Send button appearance | + +### CometChatMessageHeader + +| Property | Description | +| --- | --- | +| `backgroundColor` | Header background | +| `titleTextColor` | User/group name color | +| `subtitleTextColor` | Status/typing text color | +| `avatarStyle` | Avatar appearance | +| `callButtonsStyle` | Call button appearance | + +--- + +## Related + +- [Theme Introduction](/ui-kit/android/v6/theme-introduction) — Global theming reference. +- [Component Styling](/ui-kit/android/v6/component-styling) — Detailed per-component style examples with screenshots. +- [Color Resources](/ui-kit/android/v6/color-resources) — Default color palette reference. +- [Customization Overview](/ui-kit/android/v6/customization-overview) — All customization categories. diff --git a/ui-kit/android/v6/customization-text-formatters.mdx b/ui-kit/android/v6/customization-text-formatters.mdx new file mode 100644 index 000000000..ef9f0e3e0 --- /dev/null +++ b/ui-kit/android/v6/customization-text-formatters.mdx @@ -0,0 +1,176 @@ +--- +title: "Text Formatters" +description: "Create custom text processors for hashtags, mentions, links, or any pattern using the CometChatTextFormatter API." +--- + +Text formatters let you process message text with tracking characters, suggestion lists, and spannable transformations. Use them to add hashtag detection, custom mentions, link previews, or any text pattern processing. + +Both modules have their own `CometChatTextFormatter` class with the same API pattern: +- Kotlin XML: `com.cometchat.uikit.kotlin.shared.formatters.CometChatTextFormatter` +- Jetpack Compose: `com.cometchat.uikit.compose.presentation.shared.formatters.CometChatTextFormatter` + +--- + +## CometChatTextFormatter API + +The abstract class takes a `trackingCharacter` that triggers the formatter when typed in the composer (e.g., `@` for mentions, `#` for hashtags). + +### Key Override Methods + +| Method | Purpose | +| --- | --- | +| `search(context, queryString)` | Called when the user types after the tracking character. Fetch and display suggestions. | +| `onScrollToBottom()` | Called when the user scrolls to the bottom of the suggestion list. Use for pagination. | +| `prepareLeftMessageBubbleSpan(context, message, spannable)` | Apply spans to text in incoming message bubbles. | +| `prepareRightMessageBubbleSpan(context, message, spannable)` | Apply spans to text in outgoing message bubbles. | +| `prepareComposerSpan(context, message, spannable)` | Apply spans to text in the message composer. | +| `prepareConversationSpan(context, message, spannable)` | Apply spans to the last message preview in the conversation list. | +| `handlePreMessageSend(context, message)` | Modify a message before it's sent (attach metadata, transform text). | +| `onItemClick(context, suggestionItem, user, group)` | Called when the user selects a suggestion item. | + +### Suggestion System + +| Method | Description | +| --- | --- | +| `setSuggestionItemList(items)` | Set the list of suggestions to display | +| `setShowLoadingIndicator(show)` | Show/hide a loading spinner in the suggestion dropdown | +| `setDisableSuggestions(disable)` | Disable the suggestion dropdown entirely | + +--- + +## Example: Custom Hashtag Formatter + + + + + +```kotlin lines +import com.cometchat.uikit.kotlin.shared.formatters.CometChatTextFormatter +import com.cometchat.uikit.kotlin.shared.formatters.SuggestionItem + +class HashtagFormatter : CometChatTextFormatter('#') { + + override fun search(context: Context, queryString: String?) { + val suggestions = fetchHashtags(queryString) + setSuggestionItemList(suggestions) + } + + override fun onScrollToBottom() { + // Load more suggestions + } + + override fun prepareLeftMessageBubbleSpan( + context: Context, + baseMessage: BaseMessage, + spannable: SpannableStringBuilder + ): SpannableStringBuilder? { + applyHashtagSpans(spannable, context) + return spannable + } + + override fun prepareRightMessageBubbleSpan( + context: Context, + baseMessage: BaseMessage, + spannable: SpannableStringBuilder + ): SpannableStringBuilder? { + applyHashtagSpans(spannable, context) + return spannable + } +} +``` + + + + +```kotlin lines +import com.cometchat.uikit.compose.presentation.shared.formatters.CometChatTextFormatter +import com.cometchat.uikit.compose.presentation.shared.formatters.SuggestionItem + +class HashtagFormatter : CometChatTextFormatter('#') { + + override fun search(context: Context, queryString: String?) { + val suggestions = fetchHashtags(queryString) + setSuggestionItemList(suggestions) + } + + override fun onScrollToBottom() { + // Load more suggestions + } + + override fun prepareLeftMessageBubbleSpan( + context: Context, + baseMessage: BaseMessage, + spannable: SpannableStringBuilder + ): SpannableStringBuilder? { + applyHashtagSpans(spannable, context) + return spannable + } + + override fun prepareRightMessageBubbleSpan( + context: Context, + baseMessage: BaseMessage, + spannable: SpannableStringBuilder + ): SpannableStringBuilder? { + applyHashtagSpans(spannable, context) + return spannable + } +} +``` + + + + +--- + +## Registering Formatters + + + + +```kotlin lines +val hashtagFormatter = HashtagFormatter() +conversations.setTextFormatters(listOf(hashtagFormatter)) + +// Or on message composer / message list +messageComposer.setTextFormatters(listOf(hashtagFormatter)) +messageList.setTextFormatters(listOf(hashtagFormatter)) +``` + + + + +```kotlin lines +CometChatConversations( + textFormatters = listOf(HashtagFormatter()) +) + +CometChatMessageComposer( + textFormatters = listOf(HashtagFormatter()) +) + +CometChatMessageList( + textFormatters = listOf(HashtagFormatter()) +) +``` + + + + +--- + +## Built-in Formatter: CometChatMentionsFormatter + +The UI Kit includes `CometChatMentionsFormatter` as a built-in formatter that handles `@mention` detection, user suggestion lists, and spannable highlighting. It's automatically added to components when mentions are enabled. + +Each module has its own implementation: +- Kotlin XML: `com.cometchat.uikit.kotlin.shared.formatters.CometChatMentionsFormatter` +- Jetpack Compose: `com.cometchat.uikit.compose.presentation.shared.formatters.CometChatMentionsFormatter` + +See the [Mentions Formatter Guide](/ui-kit/android/v6/mentions-formatter-guide) for details. + +--- + +## Related + +- [Mentions Formatter Guide](/ui-kit/android/v6/mentions-formatter-guide) — Built-in mentions formatter reference. +- [Customization Overview](/ui-kit/android/v6/customization-overview) — See all customization categories. diff --git a/ui-kit/android/v6/customization-view-slots.mdx b/ui-kit/android/v6/customization-view-slots.mdx new file mode 100644 index 000000000..eb27f7c3d --- /dev/null +++ b/ui-kit/android/v6/customization-view-slots.mdx @@ -0,0 +1,263 @@ +--- +title: "View Slots" +description: "Replace specific regions of a component's UI without rebuilding the entire component." +--- + +View Slots let you swap out specific parts of a component's list item — the avatar area, title, subtitle, trailing section, or the entire row — while keeping the rest of the component's behavior intact. + +--- + +## Available View Slots + +| Slot | Region | Description | +| --- | --- | --- | +| `leadingView` | Left section | Replaces the avatar / leading area | +| `titleView` | Title text | Replaces the name / title text | +| `subtitleView` | Subtitle text | Replaces the last message preview | +| `trailingView` | Right section | Replaces the timestamp / badge area | +| `itemView` | Entire row | Replaces the entire list item layout | + + +When you use `itemView`, all other slot setters are ignored since the entire row is replaced. + + +--- + +## How It Works + + + + +Each list-based component defines a `ViewHolderListener` abstract class with two callbacks: + +| Callback | Purpose | +| --- | --- | +| `createView(context, binding)` | Return a `View` for the slot. Called once when the ViewHolder is created. | +| `bindView(context, createdView, data, ...)` | Bind data to your custom view. Called every time the item is bound. | + +Pass the listener to the component via `setLeadingView()`, `setTitleView()`, `setSubtitleView()`, `setTrailingView()`, or `setItemView()`. + + + + +Each component accepts `@Composable` lambda parameters for each slot: + +```kotlin lines +CometChatConversations( + leadingView = { conversation, typingIndicator -> /* your composable */ }, + titleView = { conversation, typingIndicator -> /* your composable */ }, + subtitleView = { conversation, typingIndicator -> /* your composable */ }, + trailingView = { conversation, typingIndicator -> /* your composable */ }, + itemView = { conversation, typingIndicator -> /* your composable */ } +) +``` + +The lambda receives the data model directly — no `createView`/`bindView` split needed. + + + + +--- + +## Example: Custom Leading View + +Replace the default avatar with a custom view showing the first letter of the conversation name. + + + + +```kotlin lines +conversations.setLeadingView(object : ConversationsViewHolderListener() { + override fun createView( + context: Context, + binding: CometchatConversationsListItemsBinding + ): View { + return TextView(context).apply { + layoutParams = ViewGroup.LayoutParams(48.dp, 48.dp) + gravity = Gravity.CENTER + textSize = 18f + setTextColor(Color.WHITE) + } + } + + override fun bindView( + context: Context, + createdView: View, + conversation: Conversation, + typingIndicator: TypingIndicator?, + holder: RecyclerView.ViewHolder, + conversations: List, + position: Int + ) { + val textView = createdView as TextView + val name = conversation.conversationWith?.name ?: "" + textView.text = name.firstOrNull()?.uppercase() ?: "?" + textView.background = GradientDrawable().apply { + shape = GradientDrawable.OVAL + setColor(Color.parseColor("#6851D6")) + } + } +}) +``` + + + + +```kotlin lines +CometChatConversations( + leadingView = { conversation, _ -> + val name = conversation.conversationWith?.name ?: "" + val initial = name.firstOrNull()?.uppercase() ?: "?" + + Box( + modifier = Modifier + .size(48.dp) + .background(Color(0xFF6851D6), CircleShape), + contentAlignment = Alignment.Center + ) { + Text( + text = initial, + color = Color.White, + fontSize = 18.sp + ) + } + } +) +``` + + + + +--- + +## Example: Custom Subtitle View + +Show a custom last message format in the subtitle area. + + + + +```kotlin lines +conversations.setSubtitleView(object : ConversationsViewHolderListener() { + override fun createView( + context: Context, + binding: CometchatConversationsListItemsBinding + ): View { + return TextView(context).apply { + maxLines = 1 + ellipsize = TextUtils.TruncateAt.END + } + } + + override fun bindView( + context: Context, + createdView: View, + conversation: Conversation, + typingIndicator: TypingIndicator?, + holder: RecyclerView.ViewHolder, + conversations: List, + position: Int + ) { + val textView = createdView as TextView + // Show typing indicator if available + if (typingIndicator != null) { + textView.text = "typing..." + return + } + textView.text = when (val msg = conversation.lastMessage) { + is TextMessage -> msg.text + is MediaMessage -> "📎 ${msg.attachment?.fileExtension ?: "Media"}" + else -> "New conversation" + } + } +}) +``` + + + + +```kotlin lines +CometChatConversations( + subtitleView = { conversation, typingIndicator -> + val text = if (typingIndicator != null) { + "typing..." + } else { + when (val msg = conversation.lastMessage) { + is TextMessage -> msg.text + is MediaMessage -> "📎 ${msg.attachment?.fileExtension ?: "Media"}" + else -> "New conversation" + } + } + + Text( + text = text, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + style = CometChatTheme.typography.bodyRegular, + color = CometChatTheme.colorScheme.textColorSecondary + ) + } +) +``` + + + + +--- + +## Toolbar Overflow Menu + +Inject a custom view into the component's toolbar area. This is separate from list item view slots. + + + + +```kotlin lines +val menuButton = ImageButton(context).apply { + setImageResource(R.drawable.ic_filter) + setOnClickListener { /* show filter dialog */ } +} +conversations.setOverflowMenu(menuButton) +``` + + + + +```kotlin lines +CometChatConversations( + overflowMenu = { + IconButton(onClick = { /* show filter dialog */ }) { + Icon( + painter = painterResource(R.drawable.ic_filter), + contentDescription = "Filter" + ) + } + } +) +``` + + + + +--- + +## Components with View Slots + +View slots are available on all list-based components: + +| Component | ViewHolderListener (Kotlin XML) | Composable Lambdas (Compose) | +| --- | --- | --- | +| `CometChatConversations` | `ConversationsViewHolderListener` | `(Conversation, TypingIndicator?) -> Unit` | +| `CometChatUsers` | `UsersViewHolderListener` | `(User) -> Unit` | +| `CometChatGroups` | `GroupsViewHolderListener` | `(Group) -> Unit` | +| `CometChatGroupMembers` | `GroupMembersViewHolderListener` | `(GroupMember) -> Unit` | +| `CometChatCallLogs` | `CallLogsViewHolderListener` | `(CallLog) -> Unit` | +| `CometChatReactionList` | `ReactionListViewHolderListener` | `(Reaction) -> Unit` | +| `CometChatMessageHeader` | `MessageHeaderViewHolderListener` | `(User?, Group?) -> Unit` | + +--- + +## Related + +- [Styles](/ui-kit/android/v6/customization-styles) — Customize visual appearance without replacing views. +- [Customization Overview](/ui-kit/android/v6/customization-overview) — See all customization categories. diff --git a/ui-kit/android/v6/customization-viewmodel-data.mdx b/ui-kit/android/v6/customization-viewmodel-data.mdx new file mode 100644 index 000000000..8c51cde9f --- /dev/null +++ b/ui-kit/android/v6/customization-viewmodel-data.mdx @@ -0,0 +1,339 @@ +--- +title: "ViewModel & Data" +description: "Access and configure the ViewModel layer to customize data fetching, state management, and list operations." +--- + +Each component's ViewModel lives in `chatuikit-core` and manages data fetching, state transitions, real-time listeners, and list operations via `StateFlow`. The same ViewModel is shared by both Kotlin XML Views and Jetpack Compose modules. + +--- + +## Creating and Providing a ViewModel + +By default, each component creates its own ViewModel internally. To customize behavior, create the ViewModel externally using the factory and pass it to the component. + + + + +```kotlin lines +// 1. Create the factory (optionally with a custom repository) +val factory = CometChatConversationsViewModelFactory() + +// 2. Create the ViewModel using ViewModelProvider +val viewModel = ViewModelProvider(this, factory) + .get(CometChatConversationsViewModel::class.java) + +// 3. Configure the ViewModel before passing it +viewModel.setConversationsRequestBuilder( + ConversationsRequest.ConversationsRequestBuilder() + .setLimit(20) + .withTags(true) +) + +// 4. Pass it to the component +val conversations = findViewById(R.id.conversations) +conversations.setViewModel(viewModel) +``` + + + + +```kotlin lines +// 1. Create the factory (optionally with a custom repository) +val factory = CometChatConversationsViewModelFactory() + +// 2. Create the ViewModel using Compose's viewModel() +val viewModel: CometChatConversationsViewModel = viewModel(factory = factory) + +// 3. Pass it to the component +CometChatConversations( + conversationsViewModel = viewModel +) +``` + + + + +This pattern applies to all components — `CometChatUsers`, `CometChatGroups`, `CometChatMessageList`, `CometChatCallLogs`, etc. Each has a corresponding factory class. + +--- + +## State Observation + +ViewModels expose state via Kotlin `StateFlow` (not LiveData). The key state flows are: + +| StateFlow | Type | Description | +| --- | --- | --- | +| `uiState` | `StateFlow` | Current screen state: `Loading`, `Empty`, `Error(exception)`, `Content(list)` | +| `conversations` | `StateFlow>` | The current list of conversations | +| `typingIndicators` | `StateFlow>` | Active typing indicators by conversation ID | +| `deleteState` | `StateFlow` | Delete operation state: `Idle`, `InProgress`, `Success`, `Failure(exception)` | +| `playSoundEvent` | `SharedFlow` | Emits when a message sound should play | +| `scrollToTopEvent` | `SharedFlow` | Emits when the list should scroll to top | + +### UIState + +```kotlin lines +sealed class UIState { + object Loading : UIState() + object Empty : UIState() + data class Error(val exception: CometChatException) : UIState() + data class Content(val conversations: List) : UIState() +} +``` + +### Observing State + + + + +```kotlin lines +// Collect in a lifecycle-aware scope +lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.STARTED) { + viewModel.uiState.collect { state -> + when (state) { + is UIState.Loading -> { /* show loading */ } + is UIState.Empty -> { /* show empty */ } + is UIState.Error -> { /* show error: state.exception */ } + is UIState.Content -> { /* data ready: state.conversations */ } + } + } + } +} +``` + + + + +```kotlin lines +val uiState by viewModel.uiState.collectAsState() + +when (uiState) { + is UIState.Loading -> CircularProgressIndicator() + is UIState.Empty -> Text("No conversations") + is UIState.Error -> Text("Error: ${(uiState as UIState.Error).exception.message}") + is UIState.Content -> { /* render list */ } +} +``` + + + + +--- + +## Configuring Data Fetching + +Pass a custom `ConversationsRequestBuilder` to control what data the component fetches. You can set it during ViewModel creation or directly on the component: + + + + +```kotlin lines +// Option 1: Set on the component directly +conversations.setConversationsRequestBuilder( + ConversationsRequest.ConversationsRequestBuilder() + .setLimit(20) + .setTags(listOf("important", "pinned")) + .withTags(true) +) + +// Option 2: Set on the ViewModel after creation +viewModel.setConversationsRequestBuilder( + ConversationsRequest.ConversationsRequestBuilder() + .setLimit(20) +) +``` + + + + +```kotlin lines +CometChatConversations( + conversationsRequestBuilder = ConversationsRequest.ConversationsRequestBuilder() + .setLimit(20) + .setTags(listOf("important", "pinned")) + .withTags(true) +) +``` + + + + + +Pass the builder object, not the result of `.build()`. The component calls `.build()` internally. + + +--- + +## ListOperations API + +All list-based ViewModels implement `ListOperations`, giving you a consistent API to manipulate list data: + +```kotlin lines +// Add items +viewModel.addItem(conversation) +viewModel.addItems(conversations) + +// Remove items +viewModel.removeItem(conversation) +viewModel.removeItemAt(0) + +// Update items +viewModel.updateItem(updatedConversation) { + it.conversationId == updatedConversation.conversationId +} + +// Move to top +viewModel.moveItemToTop(importantConversation) + +// Query +val items = viewModel.getItems() +val count = viewModel.getItemCount() +val first = viewModel.getItemAt(0) + +// Clear +viewModel.clearItems() +``` + +### Batch Operations + +Perform multiple operations in a single emission — critical for performance with rapid updates: + +```kotlin lines +viewModel.batch { + add(newConversation1) + add(newConversation2) + remove(oldConversation) + moveToTop(pinnedConversation) +} +// Only one StateFlow emission for all four operations +``` + +--- + +## ViewModel Methods + +| Method | Description | +| --- | --- | +| `fetchConversations()` | Fetch the next page (pagination) | +| `refreshList()` | Clear and re-fetch from the server (silent refresh) | +| `deleteConversation(conversation)` | Delete a conversation via the SDK | +| `resetDeleteState()` | Reset delete state to `Idle` | +| `setConversationsRequestBuilder(builder)` | Set a custom request builder for filtering | +| `setDisableReceipt(disable)` | Disable read receipts | +| `setDisableSoundForMessages(disable)` | Disable message sounds | +| `setCustomSoundForMessage(rawRes)` | Set a custom sound resource | + +--- + +## Providing a Custom ViewModel + +Subclass the ViewModel to override behavior, then inject it: + +```kotlin lines +class MyConversationsViewModel( + getConversationsUseCase: GetConversationsUseCase, + deleteConversationUseCase: DeleteConversationUseCase, + refreshConversationsUseCase: RefreshConversationsUseCase +) : CometChatConversationsViewModel( + getConversationsUseCase, + deleteConversationUseCase, + refreshConversationsUseCase +) { + // Override list operations to add custom behavior + override fun addItem(item: Conversation) { + // Example: filter out blocked users before adding + val blockedUser = item.conversationWith as? User + if (blockedUser?.isBlockedByMe == true) return + super.addItem(item) + } + + override fun moveItemToTop(item: Conversation) { + // Example: log when a conversation is moved to top + Log.d("MyVM", "Moving ${item.conversationId} to top") + super.moveItemToTop(item) + } +} +``` + +Create it via the factory with a custom repository if needed: + +```kotlin lines +val factory = CometChatConversationsViewModelFactory( + repository = MyCustomRepository() +) +``` + + + + +```kotlin lines +val viewModel = ViewModelProvider(this, factory) + .get(CometChatConversationsViewModel::class.java) + +conversations.setViewModel(viewModel) +``` + + + + +```kotlin lines +val viewModel = viewModel(factory = factory) + +CometChatConversations( + conversationsViewModel = viewModel +) +``` + + + + +--- + +## Lifecycle Callbacks + +Intercept data loading events on the View: + + + + +```kotlin lines +conversations.setOnLoad { list -> + Log.d("Conversations", "Loaded ${list.size} conversations") +} + +conversations.setOnEmpty { + Log.d("Conversations", "No conversations found") +} + +conversations.setOnError { exception -> + Log.e("Conversations", "Error: ${exception.message}") +} +``` + + + + +```kotlin lines +CometChatConversations( + onLoad = { list -> + Log.d("Conversations", "Loaded ${list.size} conversations") + }, + onEmpty = { + Log.d("Conversations", "No conversations found") + }, + onError = { exception -> + Log.e("Conversations", "Error: ${exception.message}") + } +) +``` + + + + +--- + +## Related + +- [Customization Overview](/ui-kit/android/v6/customization-overview) — Architecture overview with repository and ListOperations details. +- [Events & Callbacks](/ui-kit/android/v6/customization-events) — Handle click events and global UI Kit events. diff --git a/ui-kit/android/v6/events.mdx b/ui-kit/android/v6/events.mdx new file mode 100644 index 000000000..3baae1188 --- /dev/null +++ b/ui-kit/android/v6/events.mdx @@ -0,0 +1,535 @@ +--- +title: "Events" +description: "Listen to UI Kit events for user actions, group changes, messages, and call lifecycle updates using CometChatEvents SharedFlow." +--- + + + +| Field | Value | +| --- | --- | +| Kotlin (XML Views) | `com.cometchat:chatuikit-kotlin-android` | +| Jetpack Compose | `com.cometchat:chatuikit-compose-android` | +| Import | `com.cometchat.uikit.core.events.CometChatEvents` | +| Event flows | `CometChatEvents.messageEvents`, `CometChatEvents.callEvents`, `CometChatEvents.conversationEvents`, `CometChatEvents.groupEvents`, `CometChatEvents.userEvents`, `CometChatEvents.uiEvents` | +| Pattern | Kotlin `SharedFlow` with sealed class event types — collect in `viewModelScope` or `lifecycleScope` | +| Purpose | Decoupled communication between UI Kit components — subscribe to event flows to react to changes without direct component references | + + + +Events enable a decoupled, flexible architecture in the CometChat UI Kit. Components emit events via the `CometChatEvents` singleton, and other parts of your application collect these `SharedFlow` streams to react without direct references between components. + +## When to use this + +- You need to update your UI when a user is blocked or unblocked. +- You need to respond to group actions such as member joins, kicks, bans, or ownership transfers. +- You need to track conversation deletions or updates in real time. +- You need to react to messages being sent, edited, deleted, or read. +- You need to handle call lifecycle events (outgoing, accepted, rejected, ended). +- You need to respond to UI-level events such as panel visibility changes or active chat changes. + +## Prerequisites + +- The `com.cometchat:chatuikit-kotlin-android` or `com.cometchat:chatuikit-compose-android` dependency added to your project. +- `CometChatUIKit.init()` called and completed successfully. +- A logged-in CometChat user (call `CometChatUIKit.login()` before collecting events). + +## CometChatEvents Singleton + +All events are accessed through the `CometChatEvents` singleton in `chatuikit-core`. Each domain has a dedicated `SharedFlow` that emits sealed class event types: + +```kotlin +import com.cometchat.uikit.core.events.CometChatEvents +``` + +| Flow | Sealed Class | Description | +|------|-------------|-------------| +| `CometChatEvents.messageEvents` | `MessageEvent` | Message sent, edited, deleted, read, reactions | +| `CometChatEvents.callEvents` | `CallEvent` | Call initiated, accepted, rejected, ended | +| `CometChatEvents.conversationEvents` | `ConversationEvent` | Conversation deleted, updated | +| `CometChatEvents.groupEvents` | `GroupEvent` | Group created, deleted, member changes | +| `CometChatEvents.userEvents` | `UserEvent` | User blocked, unblocked | +| `CometChatEvents.uiEvents` | `UIEvent` | Panel visibility, active chat changes | + +## API reference + +### Message Events + +`CometChatEvents.messageEvents` emits `MessageEvent` sealed class instances when messages are sent, edited, deleted, or read. + +**Event types:** + +| Event | Description | +| ----- | ----------- | +| `MessageEvent.Sent(message, status)` | Triggered when a message is sent. Status can be `inProgress` or `sent`. | +| `MessageEvent.Edited(message, status)` | Triggered when a message is edited. Status can be `inProgress` or `sent`. | +| `MessageEvent.Deleted(message)` | Triggered when a message is deleted. | +| `MessageEvent.Read(message)` | Triggered when a message is read. | +| `MessageEvent.LiveReaction(icon)` | Triggered when a live reaction is sent. | +| `MessageEvent.FormReceived(message)` | Triggered when a form message is received. | +| `MessageEvent.CardReceived(message)` | Triggered when a card message is received. | +| `MessageEvent.CustomInteractiveReceived(message)` | Triggered when a custom interactive message is received. | +| `MessageEvent.InteractionGoalCompleted(message)` | Triggered when an interaction goal is completed. | +| `MessageEvent.SchedulerReceived(message)` | Triggered when a scheduler message is received. | + +**Collecting events:** + + + +```kotlin +// In an Activity or Fragment — use lifecycleScope +lifecycleScope.launch { + CometChatEvents.messageEvents.collect { event -> + when (event) { + is MessageEvent.Sent -> { + val message = event.message + val status = event.status + // Update UI when message is sent + } + is MessageEvent.Edited -> { + val message = event.message + // Update UI when message is edited + } + is MessageEvent.Deleted -> { + val message = event.message + // Remove message from UI + } + is MessageEvent.Read -> { + val message = event.message + // Update read receipts + } + is MessageEvent.LiveReaction -> { + val icon = event.icon + // Show live reaction animation + } + is MessageEvent.FormReceived -> { /* Handle form message */ } + is MessageEvent.CardReceived -> { /* Handle card message */ } + is MessageEvent.CustomInteractiveReceived -> { /* Handle custom interactive */ } + is MessageEvent.InteractionGoalCompleted -> { /* Handle goal completion */ } + is MessageEvent.SchedulerReceived -> { /* Handle scheduler message */ } + } + } +} +``` + + + +```kotlin +@Composable +fun MessageEventsHandler() { + LaunchedEffect(Unit) { + CometChatEvents.messageEvents.collect { event -> + when (event) { + is MessageEvent.Sent -> { + val message = event.message + val status = event.status + // Update UI when message is sent + } + is MessageEvent.Edited -> { + val message = event.message + // Update UI when message is edited + } + is MessageEvent.Deleted -> { + val message = event.message + // Remove message from UI + } + is MessageEvent.Read -> { + val message = event.message + // Update read receipts + } + is MessageEvent.LiveReaction -> { + val icon = event.icon + // Show live reaction animation + } + is MessageEvent.FormReceived -> { /* Handle form message */ } + is MessageEvent.CardReceived -> { /* Handle card message */ } + is MessageEvent.CustomInteractiveReceived -> { /* Handle custom interactive */ } + is MessageEvent.InteractionGoalCompleted -> { /* Handle goal completion */ } + is MessageEvent.SchedulerReceived -> { /* Handle scheduler message */ } + } + } + } +} +``` + + + +> **What this does:** Collects the `messageEvents` SharedFlow and pattern-matches on the sealed class to handle each message lifecycle event. + +--- + +### Call Events + +`CometChatEvents.callEvents` emits `CallEvent` sealed class instances for call lifecycle changes. + +**Event types:** + +| Event | Description | +| ----- | ----------- | +| `CallEvent.OutgoingCall(call)` | Triggered when the logged-in user initiates an outgoing call. | +| `CallEvent.Accepted(call)` | Triggered when a call is accepted. | +| `CallEvent.Rejected(call)` | Triggered when a call is rejected. | +| `CallEvent.Ended(call)` | Triggered when a call is ended. | + +**Collecting events:** + + + +```kotlin +lifecycleScope.launch { + CometChatEvents.callEvents.collect { event -> + when (event) { + is CallEvent.OutgoingCall -> { + val call = event.call + // Handle outgoing call initiated + } + is CallEvent.Accepted -> { + val call = event.call + // Handle call accepted + } + is CallEvent.Rejected -> { + val call = event.call + // Handle call rejected + } + is CallEvent.Ended -> { + val call = event.call + // Handle call ended + } + } + } +} +``` + + + +```kotlin +@Composable +fun CallEventsHandler() { + LaunchedEffect(Unit) { + CometChatEvents.callEvents.collect { event -> + when (event) { + is CallEvent.OutgoingCall -> { + // Handle outgoing call initiated + } + is CallEvent.Accepted -> { + // Handle call accepted + } + is CallEvent.Rejected -> { + // Handle call rejected + } + is CallEvent.Ended -> { + // Handle call ended + } + } + } + } +} +``` + + + +--- + +### Conversation Events + +`CometChatEvents.conversationEvents` emits `ConversationEvent` sealed class instances when conversations are deleted or updated. + +**Event types:** + +| Event | Description | +| ----- | ----------- | +| `ConversationEvent.Deleted(conversation)` | Triggered when the logged-in user deletes a conversation. | +| `ConversationEvent.Updated(conversation)` | Triggered when there is an update in the conversation. | + +**Collecting events:** + + + +```kotlin +lifecycleScope.launch { + CometChatEvents.conversationEvents.collect { event -> + when (event) { + is ConversationEvent.Deleted -> { + val conversation = event.conversation + // Remove conversation from UI + } + is ConversationEvent.Updated -> { + val conversation = event.conversation + // Update conversation in UI + } + } + } +} +``` + + + +```kotlin +@Composable +fun ConversationEventsHandler() { + LaunchedEffect(Unit) { + CometChatEvents.conversationEvents.collect { event -> + when (event) { + is ConversationEvent.Deleted -> { + // Remove conversation from UI + } + is ConversationEvent.Updated -> { + // Update conversation in UI + } + } + } + } +} +``` + + + +--- + +### Group Events + +`CometChatEvents.groupEvents` emits `GroupEvent` sealed class instances when the logged-in user performs group-related actions. + +**Event types:** + +| Event | Description | +| ----- | ----------- | +| `GroupEvent.Created(group)` | Triggered when the logged-in user creates a group. | +| `GroupEvent.Deleted(group)` | Triggered when the logged-in user deletes a group. | +| `GroupEvent.Left(actionMessage, leftUser, leftGroup)` | Triggered when the logged-in user leaves a group. | +| `GroupEvent.MemberScopeChanged(actionMessage, updatedUser, scopeChangedTo, scopeChangedFrom, group)` | Triggered when a member's scope is changed. | +| `GroupEvent.MemberBanned(actionMessage, bannedUser, bannedBy, bannedFrom)` | Triggered when a member is banned from a group. | +| `GroupEvent.MemberKicked(actionMessage, kickedUser, kickedBy, kickedFrom)` | Triggered when a member is kicked from a group. | +| `GroupEvent.MemberUnBanned(actionMessage, unbannedUser, unBannedBy, unBannedFrom)` | Triggered when a member is unbanned from a group. | +| `GroupEvent.MemberJoined(joinedUser, joinedGroup)` | Triggered when the logged-in user joins a group. | +| `GroupEvent.MemberAdded(actionMessages, usersAdded, userAddedIn, addedBy)` | Triggered when members are added to a group. | +| `GroupEvent.OwnershipChanged(group, newOwner)` | Triggered when group ownership is transferred. | + +**Collecting events:** + + + +```kotlin +lifecycleScope.launch { + CometChatEvents.groupEvents.collect { event -> + when (event) { + is GroupEvent.Created -> { + val group = event.group + // Add new group to UI + } + is GroupEvent.Deleted -> { + val group = event.group + // Remove group from UI + } + is GroupEvent.Left -> { + val leftUser = event.leftUser + val leftGroup = event.leftGroup + // Handle user leaving group + } + is GroupEvent.MemberScopeChanged -> { + val updatedUser = event.updatedUser + val newScope = event.scopeChangedTo + // Update member scope in UI + } + is GroupEvent.MemberBanned -> { + val bannedUser = event.bannedUser + // Remove banned user from member list + } + is GroupEvent.MemberKicked -> { + val kickedUser = event.kickedUser + // Remove kicked user from member list + } + is GroupEvent.MemberUnBanned -> { + val unbannedUser = event.unbannedUser + // Handle unbanned user + } + is GroupEvent.MemberJoined -> { + val joinedUser = event.joinedUser + // Add user to member list + } + is GroupEvent.MemberAdded -> { + val usersAdded = event.usersAdded + // Add users to member list + } + is GroupEvent.OwnershipChanged -> { + val newOwner = event.newOwner + // Update group owner in UI + } + } + } +} +``` + + + +```kotlin +@Composable +fun GroupEventsHandler() { + LaunchedEffect(Unit) { + CometChatEvents.groupEvents.collect { event -> + when (event) { + is GroupEvent.Created -> { /* Add new group to UI */ } + is GroupEvent.Deleted -> { /* Remove group from UI */ } + is GroupEvent.Left -> { /* Handle user leaving group */ } + is GroupEvent.MemberScopeChanged -> { /* Update member scope */ } + is GroupEvent.MemberBanned -> { /* Remove banned user */ } + is GroupEvent.MemberKicked -> { /* Remove kicked user */ } + is GroupEvent.MemberUnBanned -> { /* Handle unbanned user */ } + is GroupEvent.MemberJoined -> { /* Add user to member list */ } + is GroupEvent.MemberAdded -> { /* Add users to member list */ } + is GroupEvent.OwnershipChanged -> { /* Update group owner */ } + } + } + } +} +``` + + + +--- + +### User Events + +`CometChatEvents.userEvents` emits `UserEvent` sealed class instances when the logged-in user blocks or unblocks another user. + +**Event types:** + +| Event | Description | +| ----- | ----------- | +| `UserEvent.Blocked(user)` | Triggered when the logged-in user blocks another user. | +| `UserEvent.Unblocked(user)` | Triggered when the logged-in user unblocks another user. | + +**Collecting events:** + + + +```kotlin +lifecycleScope.launch { + CometChatEvents.userEvents.collect { event -> + when (event) { + is UserEvent.Blocked -> { + val user = event.user + // Update UI to reflect blocked user + } + is UserEvent.Unblocked -> { + val user = event.user + // Update UI to reflect unblocked user + } + } + } +} +``` + + + +```kotlin +@Composable +fun UserEventsHandler() { + LaunchedEffect(Unit) { + CometChatEvents.userEvents.collect { event -> + when (event) { + is UserEvent.Blocked -> { + // Update UI to reflect blocked user + } + is UserEvent.Unblocked -> { + // Update UI to reflect unblocked user + } + } + } + } +} +``` + + + +--- + +### UI Events + +`CometChatEvents.uiEvents` emits `UIEvent` sealed class instances for UI-level actions such as panel visibility and active chat changes. + +**Event types:** + +| Event | Description | +| ----- | ----------- | +| `UIEvent.ShowPanel(id, alignment, view)` | Triggered to show an additional UI panel with custom elements. | +| `UIEvent.HidePanel(id, alignment)` | Triggered to hide a previously shown UI panel. | +| `UIEvent.ActiveChatChanged(id, message, user, group)` | Triggered when the active chat changes. | +| `UIEvent.OpenChat(user, group)` | Triggered to open a chat with a specific user or group. | + +**Collecting events:** + + + +```kotlin +lifecycleScope.launch { + CometChatEvents.uiEvents.collect { event -> + when (event) { + is UIEvent.ShowPanel -> { + val alignment = event.alignment + // Show custom UI panel + } + is UIEvent.HidePanel -> { + val alignment = event.alignment + // Hide custom UI panel + } + is UIEvent.ActiveChatChanged -> { + val user = event.user + val group = event.group + // React to active chat change + } + is UIEvent.OpenChat -> { + val user = event.user + val group = event.group + // Navigate to chat with user or group + } + } + } +} +``` + + + +```kotlin +@Composable +fun UIEventsHandler() { + LaunchedEffect(Unit) { + CometChatEvents.uiEvents.collect { event -> + when (event) { + is UIEvent.ShowPanel -> { /* Show custom UI panel */ } + is UIEvent.HidePanel -> { /* Hide custom UI panel */ } + is UIEvent.ActiveChatChanged -> { /* React to active chat change */ } + is UIEvent.OpenChat -> { /* Navigate to chat */ } + } + } + } +} +``` + + + +--- + +## Lifecycle Management + +Since `SharedFlow` collection is coroutine-based, lifecycle management is handled automatically: + +- In XML Views, use `lifecycleScope.launch` — the coroutine is cancelled when the lifecycle owner is destroyed. +- In Jetpack Compose, use `LaunchedEffect` — the coroutine is cancelled when the composable leaves the composition. + +No manual `removeListener` calls are needed, unlike the old static listener pattern. + +--- + +## Next steps + + + + UI Kit wrapper methods for initialization, authentication, and sending messages + + + Display and manage the conversation list, which reacts to conversation events + + + Display messages in a chat, which reacts to message events + + diff --git a/ui-kit/android/v6/extensions.mdx b/ui-kit/android/v6/extensions.mdx new file mode 100644 index 000000000..3c254551f --- /dev/null +++ b/ui-kit/android/v6/extensions.mdx @@ -0,0 +1,105 @@ +--- +title: "Extensions" +description: "Enable built-in CometChat extensions like reactions, stickers, polls, and link previews from the dashboard." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin-android` (Java), `com.cometchat:chatuikit-kotlin-android` (Kotlin XML), `com.cometchat:chatuikit-compose-android` (Jetpack Compose) | +| Required setup | `CometChatUIKit.init()` then `CometChatUIKit.login()` + Extensions enabled in [CometChat Dashboard](/fundamentals/extensions-overview) | +| Built-in extensions | Stickers, Polls, Collaborative Whiteboard, Collaborative Document, Message Translation, Link Preview, Thumbnail Generation, Profanity Filter | +| Key components | [Message Composer](/ui-kit/android/v6/message-composer) (Stickers, Polls, Whiteboard, Document), [Message List](/ui-kit/android/v6/message-list) (Translation, Link Preview, Thumbnails) | +| Activation | Enable each extension from the CometChat Dashboard — UI Kit auto-integrates them, no additional code required | +| Related | [Core Features](/ui-kit/android/v6/core-features), [AI Features](/ui-kit/android/v6/ai-features), [Extensions Overview](/fundamentals/extensions-overview) | + + + +CometChat’s UI Kit comes with built-in support for a wide variety of extensions that provide additional functionality. These extensions enhance the chatting experience, making it more interactive, secure, and efficient. + +Activating any of the extensions in CometChat is a simple process done through your application's dashboard. Refer to our guide for detailed information on [Extensions](/fundamentals/extensions-overview). + +Once you have successfully enabled the desired extension in your dashboard, it will be reflected in your CometChat application upon initialization and successful login. Please note that extension features will only be available if they are supported by the CometChat UI Kit. + +CometChat’s UI Kit offers built-in support for 8 extensions. This seamless integration makes it easy for you to enhance your chat application with engaging features without any extra coding effort. Just enable the desired extensions from the CometChat Dashboard, and they will be automatically reflected in the relevant components of your application, providing a richer and more engaging experience for your users. + +## Built-in Extensions + +Here's a guide on how you can enable and integrate these extensions: + +### Stickers + +The Stickers extension allows users to express their emotions more creatively. It adds a much-needed fun element to the chat by allowing users to send various pre-designed stickers. For a comprehensive understanding and guide on implementing and using the Sticker Extension, refer to our specific guide on the [Sticker Extension](/fundamentals/stickers). + +Once you have successfully activated the [Sticker Extension](/fundamentals/stickers) from your CometChat Dashboard, the feature will automatically be incorporated into the [Message Composer](/ui-kit/android/v6/message-composer) component of UI Kits. + + + + + +### Polls + +The Polls extension enhances group discussions by allowing users to create polls. Users can ask questions with a predefined list of answers, enabling a quick, organized way to gather group opinions. For a comprehensive understanding and guide on implementing and using the Polls Extension, refer to our specific guide on the [Polls Extension](/fundamentals/polls). + +Once you have successfully activated the [Polls Extension](/fundamentals/polls) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/android/v6/message-composer) component of UI Kits. + + + + + +### Collaborative Whiteboard + +The Collaborative Whiteboard extension facilitates real-time collaboration. Users can draw, brainstorm, and share ideas on a shared digital whiteboard. For a comprehensive understanding and guide on implementing and using the Collaborative Whiteboard Extension, refer to our specific guide on the [Collaborative Whiteboard Extension](/ui-kit/android/v6/message-bubble-styling#collaborative-bubble). + +Once you have successfully activated the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/android/v6/message-composer) component of UI Kits. + + + + + +### Collaborative Document + +With the Collaborative Document extension, users can work together on a shared document. This feature is essential for remote teams where document collaboration is a recurring requirement. For a comprehensive understanding and guide on implementing and using the Collaborative Document Extension, refer to our specific guide on the [Collaborative Document Extension](/ui-kit/android/v6/message-bubble-styling#collaborative-bubble). + +Once you have successfully activated the [Collaborative Document Extension](/fundamentals/collaborative-document) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/android/v6/message-composer) component of UI Kits. + + + + + +### Message Translation + +The Message Translation extension in CometChat is designed to translate any message into your local locale. It eliminates language barriers, making the chat more inclusive. For a comprehensive understanding and guide on implementing and using the Message Translation Extension, refer to our specific guide on the [Message Translation Extension](/fundamentals/message-translation). + +Once you have successfully activated the [Message Translation Extension](/fundamentals/message-translation) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of [MessageList Component](/ui-kit/android/v6/message-list) component of UI Kits. + + + + + +### Link Preview + +The Link Preview extension provides a summary of the URL shared in the chat. It includes the title, a description, and a thumbnail image from the web page. For a comprehensive understanding and guide on implementing and using the Link Preview Extension, refer to our specific guide on the [Link Preview Extension](/fundamentals/link-preview). + +Once you have successfully activated the [Link Preview Extension](/fundamentals/link-preview) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/android/v6/message-list) component of UI Kits. + + + + + +### Thumbnail Generation + +The Thumbnail Generation extension automatically creates a smaller preview image whenever a larger image is shared, helping to reduce the upload/download time and bandwidth usage. For a comprehensive understanding and guide on implementing and using the Thumbnail Generation Extension, refer to our specific guide on the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation). + +Once you have successfully activated the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/android/v6/message-list) component of UI Kits. + + + + + +### Profanity Filter + +The Profanity Filter extension helps in maintaining the chat decorum by censoring obscene and inappropriate words in the messages. For a comprehensive understanding and guide on implementing and using the Profanity Filter Extension, refer to our specific guide on the [Legacy Extensions](/moderation/legacy-extensions). + +Once you have successfully activated the Profanity Filter Extension from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/android/v6/message-list) component of UI Kits. diff --git a/ui-kit/android/v6/getting-started-jetpack.mdx b/ui-kit/android/v6/getting-started-jetpack.mdx new file mode 100644 index 000000000..d43964e57 --- /dev/null +++ b/ui-kit/android/v6/getting-started-jetpack.mdx @@ -0,0 +1,257 @@ +--- +title: "Getting Started With Jetpack Compose UI Kit" +sidebarTitle: "Jetpack Compose" +description: "Step-by-step guide to integrate the CometChat Jetpack Compose UI Kit into your Android app." +--- + + + +| Field | Value | +| --- | --- | +| Package | `com.cometchat:chatuikit-compose-android` | +| UI Layer | Jetpack Compose (Material 3) | +| Init | `CometChatUIKit.init(context, UIKitSettings, callback)` — must resolve before `login()` | +| Login | `CometChatUIKit.login("UID", callback)` — must resolve before rendering components | +| Order | `init()` → `login()` → render. Breaking this order = blank screen | +| Auth Key | Dev/testing only. Use Auth Token in production | +| Calling | Optional. Add `com.cometchat:calls-sdk-android` to enable voice/video | +| Min SDK | Android 9.0 (API 28) | + + + +This guide walks you through integrating the CometChat Jetpack Compose UI Kit into an Android app. All UI components are native Compose composables built with Material 3. By the end you'll have a working chat UI. + +--- + +## Prerequisites + +You need three things from the [CometChat Dashboard](https://app.cometchat.com/): + +| Credential | Where to find it | +| --- | --- | +| App ID | Dashboard → Your App → Credentials | +| Auth Key | Dashboard → Your App → Credentials | +| Region | Dashboard → Your App → Credentials (e.g. `us`, `eu`, `in`) | + +You also need: +- Android Studio (Hedgehog or later recommended) +- An Android emulator or physical device running Android 9.0 (API 28) or higher +- Kotlin configured with Compose compiler plugin +- Gradle plugin 8.0+ with Kotlin DSL + + +Auth Key is for development only. In production, generate Auth Tokens server-side via the [REST API](https://api-explorer.cometchat.com/) and use `loginWithAuthToken()`. Never ship Auth Keys in client code. + + +--- + +## Step 1 — Create an Android Project + +1. Open Android Studio and start a new project. +2. Choose Empty Activity (Compose) as the project template. +3. Set minimum API level to 28 or higher. + +--- + +## Step 2 — Install Dependencies + +### Add the CometChat Repository + +Add the CometChat Maven repository to your `settings.gradle.kts`: + +```kotlin settings.gradle.kts lines +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + maven("https://dl.cloudsmith.io/public/cometchat/cometchat/maven/") + } +} +``` + +### Add Dependencies + + +Open your app-level `build.gradle.kts` and enable Compose, then add the dependencies: + +```kotlin build.gradle.kts lines +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.android) + alias(libs.plugins.kotlin.compose) +} + +android { + // ... + buildFeatures { + compose = true + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = "11" + } +} + +dependencies { + // CometChat Jetpack Compose UI Kit + implementation("com.cometchat:chatuikit-compose-android:6.0.0") + + // (Optional) Voice/video calling + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") +} +``` + +--- + +## Step 3 — Initialize and Login + +Create your `MainActivity.kt` with the CometChat initialization and login flow. Since Compose uses a declarative approach, we track the auth state and render UI conditionally: + +```kotlin MainActivity.kt lines +import android.os.Bundle +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import com.cometchat.chat.core.CometChat +import com.cometchat.chat.exceptions.CometChatException +import com.cometchat.chat.models.User +import com.cometchat.uikit.core.CometChatUIKit +import com.cometchat.uikit.core.UIKitSettings + +class MainActivity : ComponentActivity() { + + private val TAG = "MainActivity" + + private val appID = "APP_ID" // Replace with your App ID + private val region = "REGION" // Replace with your App Region + private val authKey = "AUTH_KEY" // Replace with your Auth Key + + private var isReady by mutableStateOf(false) + private var error by mutableStateOf(null) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + + val uiKitSettings = UIKitSettings.UIKitSettingsBuilder() + .setRegion(region) + .setAppId(appID) + .setAuthKey(authKey) + .subscribePresenceForAllUsers() + .build() + + CometChatUIKit.init(this, uiKitSettings, object : CometChat.CallbackListener() { + override fun onSuccess(s: String?) { + Log.d(TAG, "Initialization completed successfully") + loginUser() + } + + override fun onError(e: CometChatException?) { + error = "Init failed: ${e?.message}" + } + }) + + setContent { + when { + error != null -> { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text(error ?: "Unknown error") + } + } + !isReady -> { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + } + else -> { + ChatApp() + } + } + } + } + + private fun loginUser() { + CometChatUIKit.login("cometchat-uid-1", object : CometChat.CallbackListener() { + override fun onSuccess(user: User) { + Log.d(TAG, "Login successful: ${user.uid}") + isReady = true + } + + override fun onError(e: CometChatException) { + error = "Login failed: ${e.message}" + } + }) + } +} +``` + + +`init()` must resolve before you call `login()`. Calling `login()` before init completes will fail silently. + + +--- + +## Step 4 — Choose a Chat Experience + +Integrate a conversation view that suits your app's UX. Each option below includes a step-by-step guide. + +### Conversation List + Message View + +Sequential navigation — conversation list as the entry point, tap a conversation to open a full-screen message view. + + + Step-by-step guide to build this layout with Jetpack Compose + + +--- + +### One-to-One / Group Chat + +Single chat window — no sidebar. Loads a specific user or group chat directly. Ideal for support chat, direct messages, or notification-driven flows. + + + Step-by-step guide to build this layout + + +--- + +### Tab-Based Chat + +Bottom navigation with tabs for Chats, Calls, Users, and Settings. + + + Step-by-step guide to build this layout + + +--- + +## Next Steps + + + + Browse all available UI Kit components + + + Customize colors, fonts, and styles + + + Chat features included out of the box + + + Common issues and fixes + + diff --git a/ui-kit/android/v6/getting-started-kotlin.mdx b/ui-kit/android/v6/getting-started-kotlin.mdx new file mode 100644 index 000000000..7a4988449 --- /dev/null +++ b/ui-kit/android/v6/getting-started-kotlin.mdx @@ -0,0 +1,231 @@ +--- +title: "Getting Started With Kotlin UI Kit" +sidebarTitle: "Kotlin (XML Views)" +description: "Step-by-step guide to integrate the CometChat Kotlin UI Kit with XML Views into your Android app." +--- + + + +| Field | Value | +| --- | --- | +| Package | `com.cometchat:chatuikit-kotlin-android` | +| UI Layer | Kotlin + XML Views (View Binding) | +| Init | `CometChatUIKit.init(context, UIKitSettings, callback)` — must resolve before `login()` | +| Login | `CometChatUIKit.login("UID", callback)` — must resolve before rendering components | +| Order | `init()` → `login()` → render. Breaking this order = blank screen | +| Auth Key | Dev/testing only. Use Auth Token in production | +| Calling | Optional. Add `com.cometchat:calls-sdk-android` to enable voice/video | +| Min SDK | Android 9.0 (API 28) | + + + +This guide walks you through integrating the CometChat Kotlin UI Kit into an Android app using XML Views and View Binding. By the end you'll have a working chat UI. + +--- + +## Prerequisites + +You need three things from the [CometChat Dashboard](https://app.cometchat.com/): + +| Credential | Where to find it | +| --- | --- | +| App ID | Dashboard → Your App → Credentials | +| Auth Key | Dashboard → Your App → Credentials | +| Region | Dashboard → Your App → Credentials (e.g. `us`, `eu`, `in`) | + +You also need: +- Android Studio installed +- An Android emulator or physical device running Android 9.0 (API 28) or higher +- Kotlin configured in your project +- Gradle plugin 8.0+ with Kotlin DSL + + +Auth Key is for development only. In production, generate Auth Tokens server-side via the [REST API](https://api-explorer.cometchat.com/) and use `loginWithAuthToken()`. Never ship Auth Keys in client code. + + +--- + +## Step 1 — Create an Android Project + +1. Open Android Studio and start a new project. +2. Choose Empty Activity as the project template. +3. Select Kotlin as the language. +4. Set minimum API level to 28 or higher. + +--- + +## Step 2 — Install Dependencies + +### Add the CometChat Repository + +Add the CometChat Maven repository to your `settings.gradle.kts`: + +```kotlin settings.gradle.kts lines +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + maven("https://dl.cloudsmith.io/public/cometchat/cometchat/maven/") + } +} +``` + +### Add Dependencies + + +Open your app-level `build.gradle.kts` and enable View Binding, then add the dependencies: + +```kotlin build.gradle.kts lines +android { + // ... + buildFeatures { + viewBinding = true + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = "11" + } +} + +dependencies { + // CometChat Kotlin UI Kit + implementation("com.cometchat:chatuikit-kotlin-android:6.0.0") + + // (Optional) Voice/video calling + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") +} +``` + +### Add AndroidX Support + +Verify this line is present in `gradle.properties`: + +```properties gradle.properties lines +android.enableJetifier=true +``` + +--- + +## Step 3 — Initialize and Login + +Create your `MainActivity.kt` with the CometChat initialization and login flow: + +```kotlin MainActivity.kt lines +import android.os.Bundle +import android.util.Log +import androidx.activity.enableEdgeToEdge +import androidx.appcompat.app.AppCompatActivity +import com.cometchat.chat.core.CometChat +import com.cometchat.chat.exceptions.CometChatException +import com.cometchat.chat.models.User +import com.cometchat.uikit.core.CometChatUIKit +import com.cometchat.uikit.core.UIKitSettings + +class MainActivity : AppCompatActivity() { + + private val TAG = "MainActivity" + + private val appID = "APP_ID" // Replace with your App ID + private val region = "REGION" // Replace with your App Region + private val authKey = "AUTH_KEY" // Replace with your Auth Key + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + + val uiKitSettings = UIKitSettings.UIKitSettingsBuilder() + .setRegion(region) + .setAppId(appID) + .setAuthKey(authKey) + .subscribePresenceForAllUsers() + .build() + + CometChatUIKit.init(this, uiKitSettings, object : CometChat.CallbackListener() { + override fun onSuccess(s: String?) { + Log.d(TAG, "Initialization completed successfully") + loginUser() + } + + override fun onError(e: CometChatException?) { + Log.e(TAG, "Initialization failed: ${e?.message}") + } + }) + } + + private fun loginUser() { + CometChatUIKit.login("cometchat-uid-1", object : CometChat.CallbackListener() { + override fun onSuccess(user: User) { + Log.d(TAG, "Login successful: ${user.uid}") + + // Navigate to your chat screen after login + // startActivity(Intent(this@MainActivity, ConversationActivity::class.java)) + } + + override fun onError(e: CometChatException) { + Log.e(TAG, "Login failed: ${e.message}") + } + }) + } +} +``` + + +`init()` must resolve before you call `login()`. Calling `login()` before init completes will fail silently. + + +--- + +## Step 4 — Choose a Chat Experience + +Integrate a conversation view that suits your app's UX. Each option below includes a step-by-step guide. + +### Conversation List + Message View + +Sequential navigation — conversation list as the entry point, tap a conversation to open a full-screen message view. + + + Step-by-step guide to build this layout with Kotlin XML Views + + +--- + +### One-to-One / Group Chat + +Single chat window — no sidebar. Loads a specific user or group chat directly. Ideal for support chat, direct messages, or notification-driven flows. + + + Step-by-step guide to build this layout + + +--- + +### Tab-Based Chat + +Bottom navigation with tabs for Chats, Calls, Users, and Settings. + + + Step-by-step guide to build this layout + + +--- + +## Next Steps + + + + Browse all available UI Kit components + + + Customize colors, fonts, and styles + + + Chat features included out of the box + + + Common issues and fixes + + diff --git a/ui-kit/android/v6/getting-started.mdx b/ui-kit/android/v6/getting-started.mdx new file mode 100644 index 000000000..3ee397a3f --- /dev/null +++ b/ui-kit/android/v6/getting-started.mdx @@ -0,0 +1,219 @@ +--- +title: "Getting Started With CometChat Android UI Kit" +sidebarTitle: "Integration" +description: "Install, configure, and launch the CometChat Android UI Kit in your app — choose Kotlin (XML Views) or Jetpack Compose." +--- + + + +| Field | Value | +| --- | --- | +| Kotlin (XML Views) | `com.cometchat:chatuikit-kotlin-android` v6.x | +| Jetpack Compose | `com.cometchat:chatuikit-compose-android` v6.x | +| Init | `CometChatUIKit.init(context, UIKitSettings, callback)` — must resolve before `login()` | +| Login | `CometChatUIKit.login("UID", callback)` — must resolve before rendering components | +| Order | `init()` → `login()` → render. Breaking this order = blank screen | +| Auth Key | Dev/testing only. Use Auth Token in production | +| Theme | Set `CometChatTheme.DayNight` as parent theme in `themes.xml` | +| Calling | Optional. Add `com.cometchat:calls-sdk-android` to enable voice/video | +| Min SDK | Android 7.0 (API 24) | + + + +This guide walks you through adding CometChat to an Android app. By the end you'll have a working chat UI. + + + + + +--- + +## Prerequisites + +You need three things from the [CometChat Dashboard](https://app.cometchat.com/): + +| Credential | Where to find it | +| --- | --- | +| App ID | Dashboard → Your App → Credentials | +| Auth Key | Dashboard → Your App → Credentials | +| Region | Dashboard → Your App → Credentials (e.g. `us`, `eu`, `in`) | + +You also need: +- Android Studio installed +- An Android emulator or physical device running Android 7.0 (API 24) or higher +- Java 8 or higher +- Gradle plugin 4.0.1 or later + + +Auth Key is for development only. In production, generate Auth Tokens server-side via the [REST API](https://api-explorer.cometchat.com/) and use [`loginWithAuthToken()`](/ui-kit/android/v6/methods#login-using-auth-token). Never ship Auth Keys in client code. + + +--- + +## Step 1 — Create an Android Project + +1. Open Android Studio and start a new project. +2. Choose Empty Activity as the project template. +3. Enter a project name and choose Kotlin as the language. +4. Set minimum API level to 24 or higher. + +--- + +## Step 2 — Install Dependencies + +Add the CometChat repository and dependencies to your Gradle configuration. + +### Add the CometChat Repository + +Add the CometChat Maven repository to your project-level `settings.gradle.kts` file: + +```kotlin settings.gradle.kts +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + maven("https://dl.cloudsmith.io/public/cometchat/cometchat/maven/") + } +} +``` + +### Add the CometChat Dependency + +Choose the module that matches your UI toolkit: + + + +Inside `libs.versions.toml`, add the versions: + +```toml libs.versions.toml +[versions] +cometchat-ui-kit = "6.0.0" +cometchat-calls-sdk = "5.0.0-beta.2" +``` + +Define the libraries — pick the module for your UI toolkit: + + + +```toml libs.versions.toml +[libraries] +cometchat-ui-kit = { module = "com.cometchat:chatuikit-kotlin-android", version.ref = "cometchat-ui-kit" } +cometchat-calls-sdk = { module = "com.cometchat:calls-sdk-android", version.ref = "cometchat-calls-sdk" } +``` + + + +```toml libs.versions.toml +[libraries] +cometchat-ui-kit = { module = "com.cometchat:chatuikit-compose-android", version.ref = "cometchat-ui-kit" } +cometchat-calls-sdk = { module = "com.cometchat:calls-sdk-android", version.ref = "cometchat-calls-sdk" } +``` + + + +Now, in your app-level `build.gradle.kts` file: + +```kotlin build.gradle.kts +dependencies { + implementation(libs.cometchat.ui.kit) + + // (Optional) Include if using voice/video calling features + implementation(libs.cometchat.calls.sdk) +} +``` + + + + +Open the app-level `build.gradle.kts` file and add the dependency for your chosen UI toolkit: + + + +```kotlin build.gradle.kts +dependencies { + implementation("com.cometchat:chatuikit-kotlin-android:6.0.0") + + // (Optional) Include if using voice/video calling features + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") +} +``` + + + +```kotlin build.gradle.kts +dependencies { + implementation("com.cometchat:chatuikit-compose-android:6.0.0") + + // (Optional) Include if using voice/video calling features + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") +} +``` + + + + + + +### Add AndroidX Support + +The Jetifier tool helps migrate legacy support libraries to AndroidX. Open `gradle.properties` and verify this line is present: + +```properties gradle.properties +android.enableJetifier=true +``` + +--- + +## Choose Your UI Toolkit + +The remaining integration steps (initialization, login, theming, and rendering components) differ depending on your chosen UI toolkit. Follow the guide that matches your project: + + + + Step-by-step integration using `chatuikit-kotlin` with XML layouts and ViewBinding + + + Step-by-step integration using `chatuikit-jetpack` with Composables + + + +--- + +## Build Your Own Chat Experience + +Need full control over the UI? Use individual components, customize themes, and wire up your own layouts. + + + + Working reference app to compare against + + + All prebuilt UI elements with customization options + + + Messaging, real-time updates, and other capabilities + + + Colors, fonts, dark mode, and custom styling + + + +--- + +## Next Steps + + + + Browse all prebuilt UI components + + + Customize colors, fonts, and styles + + + Chat features included out of the box + + + Common issues and fixes + + diff --git a/ui-kit/android/v6/group-members.mdx b/ui-kit/android/v6/group-members.mdx new file mode 100644 index 000000000..518c7b105 --- /dev/null +++ b/ui-kit/android/v6/group-members.mdx @@ -0,0 +1,966 @@ +--- +title: "Group Members" +description: "Scrollable list of all members in a group with search, avatars, names, scope badges, and online/offline status." +--- + +`CometChatGroupMembers` renders a scrollable list of all members in a specific group with real-time updates for membership changes, search, avatars, scope badges, and online/offline status indicators. Requires a `Group` object to load data. + + + + + +--- + +## Where It Fits + +`CometChatGroupMembers` is a list component. It renders all members of a given group and emits the selected `GroupMember` via `onItemClick`. Use it inside a group detail screen or as a standalone member browser. + + + + +```xml activity_group_members.xml lines + +``` + +```kotlin lines +val groupMembers = findViewById(R.id.group_members) +groupMembers.setGroup(group) + +groupMembers.setOnItemClick { groupMember -> + // Navigate to member profile or start DM +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + modifier = Modifier.fillMaxSize(), + onItemClick = { groupMember -> + // Navigate to member profile or start DM + } +) +``` + + + + +--- + +## Quick Start + + + + +Add to your layout XML: + +```xml lines + +``` + +Then set the group in your Activity: + +```kotlin lines +override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_group_members) + + val groupMembers = findViewById(R.id.group_members) + groupMembers.setGroup(group) // Required — must be called before data loads +} +``` + + + + +```kotlin lines +@Composable +fun GroupMembersScreen(group: Group) { + CometChatGroupMembers( + group = group, + modifier = Modifier.fillMaxSize() + ) +} +``` + + + + +Prerequisites: CometChat SDK initialized with `CometChatUIKit.init()`, a user logged in, and the UI Kit dependency added. + +Or in a Fragment: + + + + +```kotlin lines +override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + val view = CometChatGroupMembers(requireContext()) + view.setGroup(group) + return view +} +``` + + + + +```kotlin lines +override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + return ComposeView(requireContext()).apply { + setContent { CometChatGroupMembers(group = group) } + } +} +``` + + + + +--- + +## Filtering Group Members + + + + +Pass a `GroupMembersRequest.GroupMembersRequestBuilder` to control what loads: + +```kotlin lines +groupMembers.setGroupMembersRequestBuilder( + GroupMembersRequest.GroupMembersRequestBuilder(group.guid) + .setLimit(20) + .setScopes(listOf("admin", "moderator")) +) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + groupMembersRequestBuilder = GroupMembersRequest.GroupMembersRequestBuilder(group.guid) + .setLimit(20) + .setScopes(listOf("admin", "moderator")) +) +``` + + + + +### Filter Recipes + +| Recipe | Builder method | +| --- | --- | +| Limit per page | `.setLimit(10)` | +| Search by keyword | `.setSearchKeyword("john")` | +| Filter by scopes | `.setScopes(listOf("admin", "moderator"))` | + + +Pass the builder object, not the result of `.build()`. The component calls `.build()` internally. Default page size is 30 with infinite scroll. + + +--- + +## Actions and Events + +### Callback Methods + +#### `onItemClick` + +Fires when a member row is tapped. Primary navigation hook. + + + + +```kotlin lines +groupMembers.setOnItemClick { groupMember -> + // Navigate to member profile +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + onItemClick = { groupMember -> + // Navigate to member profile + } +) +``` + + + + +> Replaces the default item-click behavior. Your custom lambda executes instead of the built-in navigation. + +#### `onItemLongClick` + +Fires when a member row is long-pressed. Use for additional actions like kick or ban. + + + + +```kotlin lines +groupMembers.setOnItemLongClick { groupMember -> + // Show context menu +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + onItemLongClick = { groupMember -> + // Show context menu + } +) +``` + + + + +#### `onBackPress` + +Fires when the user presses the back button in the toolbar. + + + + +```kotlin lines +groupMembers.setOnBackPress { + finish() +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + onBackPress = { /* navigate back */ } +) +``` + + + + +#### `onSearchClick` + +Fires when the user taps the search icon in the toolbar. + + + + +```kotlin lines +groupMembers.setOnSearchClick { + // Open search screen +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + onSearchClick = { /* open search */ } +) +``` + + + + +#### `onSelection` + +Fires when members are selected/deselected in multi-select mode. + + + + +```kotlin lines +groupMembers.setSelectionMode(UIKitConstants.SelectionMode.MULTIPLE) +groupMembers.setOnSelection { selectedMembers -> + updateToolbar(selectedMembers.size) +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + selectionMode = UIKitConstants.SelectionMode.MULTIPLE, + onSelection = { selectedMembers -> + updateToolbar(selectedMembers.size) + } +) +``` + + + + +#### `onError` + +Fires on internal errors (network failure, auth issue, SDK exception). + + + + +```kotlin lines +groupMembers.setOnError { exception -> + Log.e("GroupMembers", "Error: ${exception.message}") +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + onError = { exception -> + Log.e("GroupMembers", "Error: ${exception.message}") + } +) +``` + + + + +#### `onLoad` + +Fires when the list is successfully fetched and loaded. + + + + +```kotlin lines +groupMembers.setOnLoad { memberList -> + Log.d("GroupMembers", "Loaded ${memberList.size}") +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + onLoad = { memberList -> + Log.d("GroupMembers", "Loaded ${memberList.size}") + } +) +``` + + + + +#### `onEmpty` + +Fires when the list is empty after loading. + + + + +```kotlin lines +groupMembers.setOnEmpty { + Log.d("GroupMembers", "No members found") +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + onEmpty = { /* no members */ } +) +``` + + + + +### SDK Events (Real-Time, Automatic) + +The component listens to these SDK events internally. No manual setup needed. + +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberJoined` | Adds the new member to the list | +| `onGroupMemberLeft` | Removes the member from the list | +| `onGroupMemberKicked` | Removes the kicked member | +| `onGroupMemberBanned` | Removes the banned member | +| `onGroupMemberUnbanned` | Updates the member list | +| `onGroupMemberScopeChanged` | Updates the member's scope badge | +| `onMemberAddedToGroup` | Adds new members to the list | + +--- + +## Functionality + +| Method (Kotlin XML) | Compose Parameter | Description | +| --- | --- | --- | +| `setGroup(group)` | `group = group` | Set the group to load members for (required) | +| `setBackIconVisibility(View.VISIBLE)` | `hideBackIcon = false` | Toggle back button | +| `setToolbarVisibility(View.GONE)` | `hideToolbar = true` | Toggle toolbar | +| `setSearchBoxVisibility(View.GONE)` | `hideSearchBox = true` | Toggle search box | +| `setSeparatorVisibility(View.GONE)` | `hideSeparator = true` | Toggle list separators | +| `setSelectionMode(MULTIPLE)` | `selectionMode = MULTIPLE` | Enable selection mode | +| `setTitle("Members")` | `title = "Members"` | Custom toolbar title | +| `setSearchPlaceholderText("Find...")` | `searchPlaceholderText = "Find..."` | Search placeholder | + +--- + +## Custom View Slots + +### Leading View + +Replace the avatar / left section. + + + + + + + + +```kotlin lines +groupMembers.setLeadingView(object : GroupMembersViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return ImageView(context).apply { + layoutParams = ViewGroup.LayoutParams(48.dp, 48.dp) + } + } + + override fun bindView( + context: Context, createdView: View, groupMember: GroupMember, + holder: RecyclerView.ViewHolder, memberList: List, position: Int + ) { + val imageView = createdView as ImageView + // Load member avatar + } +}) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + leadingView = { groupMember -> + CometChatAvatar( + imageUrl = groupMember.avatar, + name = groupMember.name + ) + } +) +``` + + + + +### Title View + +Replace the name / title text. + + + + + + + + +```kotlin lines +groupMembers.setTitleView(object : GroupMembersViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context) + } + + override fun bindView( + context: Context, createdView: View, groupMember: GroupMember, + holder: RecyclerView.ViewHolder, memberList: List, position: Int + ) { + (createdView as TextView).text = groupMember.name ?: "" + } +}) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + titleView = { groupMember -> + Text( + text = groupMember.name ?: "", + style = CometChatTheme.typography.heading4Medium + ) + } +) +``` + + + + +### Subtitle View + +Replace the subtitle text below the member's name. + + + + + + + + +```kotlin lines +groupMembers.setSubtitleView(object : GroupMembersViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context).apply { maxLines = 1; ellipsize = TextUtils.TruncateAt.END } + } + + override fun bindView( + context: Context, createdView: View, groupMember: GroupMember, + holder: RecyclerView.ViewHolder, memberList: List, position: Int + ) { + (createdView as TextView).text = "Scope: ${groupMember.scope}" + } +}) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + subtitleView = { groupMember -> + Text( + text = "Scope: ${groupMember.scope}", + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } +) +``` + + + + +### Trailing View + +Replace the right section of each member item. + + + + + + + + +```kotlin lines +groupMembers.setTrailingView(object : GroupMembersViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context) + } + + override fun bindView( + context: Context, createdView: View, groupMember: GroupMember, + holder: RecyclerView.ViewHolder, memberList: List, position: Int + ) { + (createdView as TextView).text = groupMember.scope ?: "" + } +}) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + trailingView = { groupMember -> + Text(text = groupMember.scope ?: "") + } +) +``` + + + + +### Item View + +Replace the entire list item row. + + + + + + + + +```kotlin lines +groupMembers.setItemView(object : GroupMembersViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return LayoutInflater.from(context).inflate(R.layout.custom_member_item, null) + } + + override fun bindView( + context: Context, createdView: View, groupMember: GroupMember, + holder: RecyclerView.ViewHolder, memberList: List, position: Int + ) { + val avatar = createdView.findViewById(R.id.custom_avatar) + val title = createdView.findViewById(R.id.tvName) + title.text = groupMember.name + avatar.setAvatar(groupMember.name, groupMember.avatar) + } +}) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + itemView = { groupMember -> + Row( + modifier = Modifier.fillMaxWidth().padding(12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + CometChatAvatar(imageUrl = groupMember.avatar, name = groupMember.name) + Spacer(Modifier.width(12.dp)) + Column { + Text(groupMember.name ?: "", style = CometChatTheme.typography.heading4Medium) + Text(groupMember.scope ?: "", style = CometChatTheme.typography.body3Regular) + } + } + } +) +``` + + + + +### State Views + + + + +```kotlin lines +groupMembers.setEmptyView(R.layout.custom_empty_view) +groupMembers.setErrorView(R.layout.custom_error_view) +groupMembers.setLoadingView(R.layout.custom_loading_view) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + emptyView = { Text("No members found") }, + errorView = { onRetry -> Button(onClick = onRetry) { Text("Retry") } }, + loadingView = { CircularProgressIndicator() } +) +``` + + + + +### Overflow Menu + + + + +```kotlin lines +groupMembers.setOverflowMenu(ImageButton(context).apply { + setImageResource(R.drawable.ic_add_member) + setOnClickListener { /* add member */ } +}) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + overflowMenu = { + IconButton(onClick = { /* add member */ }) { + Icon(painterResource(R.drawable.ic_add_member), "Add Member") + } + } +) +``` + + + + +--- + +## Menu Options + + + + +```kotlin lines +// Replace all options +groupMembers.setOptions { context, groupMember -> + listOf( + CometChatPopupMenu.MenuItem(id = "kick", name = "Kick", onClick = { /* ... */ }), + CometChatPopupMenu.MenuItem(id = "ban", name = "Ban", onClick = { /* ... */ }) + ) +} + +// Append to defaults +groupMembers.setAddOptions { context, groupMember -> + listOf( + CometChatPopupMenu.MenuItem(id = "promote", name = "Promote", onClick = { /* ... */ }) + ) +} +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + options = { context, groupMember -> + listOf( + MenuItem(id = "kick", name = "Kick", onClick = { /* ... */ }), + MenuItem(id = "ban", name = "Ban", onClick = { /* ... */ }) + ) + }, + addOptions = { context, groupMember -> + listOf(MenuItem(id = "promote", name = "Promote", onClick = { /* ... */ })) + } +) +``` + + + + +--- + +## Common Patterns + +### Minimal list — hide all chrome + + + + +```kotlin lines +groupMembers.setToolbarVisibility(View.GONE) +groupMembers.setSearchBoxVisibility(View.GONE) +groupMembers.setSeparatorVisibility(View.GONE) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + hideToolbar = true, + hideSearchBox = true, + hideSeparator = true +) +``` + + + + +### Admins and moderators only + + + + +```kotlin lines +groupMembers.setGroupMembersRequestBuilder( + GroupMembersRequest.GroupMembersRequestBuilder(group.guid) + .setScopes(listOf("admin", "moderator")) +) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + groupMembersRequestBuilder = GroupMembersRequest.GroupMembersRequestBuilder(group.guid) + .setScopes(listOf("admin", "moderator")) +) +``` + + + + +--- + +## Advanced Methods + +### Programmatic Selection + + + + +```kotlin lines +// Enable selection +groupMembers.setSelectionMode(UIKitConstants.SelectionMode.MULTIPLE) + +// Select a member +groupMembers.selectGroupMember(member, UIKitConstants.SelectionMode.MULTIPLE) + +// Get selected +val selected = groupMembers.getSelectedGroupMembers() + +// Clear +groupMembers.clearSelection() +``` + + + + +Selection is managed via the `selectionMode` and `onSelection` parameters. The component handles selection state internally. + + + + +### ViewModel Access + +```kotlin lines +val factory = CometChatGroupMembersViewModelFactory() +val viewModel = ViewModelProvider(this, factory) + .get(CometChatGroupMembersViewModel::class.java) +``` + + + + +```kotlin lines +groupMembers.setViewModel(viewModel) +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + groupMembersViewModel = viewModel +) +``` + + + + +See [ViewModel & Data](/ui-kit/android/v6/customization-viewmodel-data) for ListOperations, state observation, and custom repositories. + +--- + +## Style + + + + + + + + +Define a custom style in `themes.xml`: + +```xml themes.xml lines + + + + + +``` + + + + +```kotlin lines +CometChatGroupMembers( + group = group, + style = CometChatGroupMembersStyle.default().copy( + backgroundColor = Color(0xFFF5F5F5), + titleTextColor = Color(0xFF141414), + itemStyle = CometChatGroupMembersItemStyle.default().copy( + backgroundColor = Color.White, + titleTextColor = Color(0xFF141414), + subtitleTextColor = Color(0xFF727272), + avatarStyle = CometChatAvatarStyle.default().copy(cornerRadius = 12.dp), + statusIndicatorStyle = CometChatStatusIndicatorStyle.default().copy() + ) + ) +) +``` + + + + +### Style Properties + +| Property | Description | +| --- | --- | +| `backgroundColor` | List background color | +| `titleTextColor` | Toolbar title color | +| `searchBoxStyle` | Search box appearance | +| `itemStyle.backgroundColor` | Row background | +| `itemStyle.selectedBackgroundColor` | Selected row background | +| `itemStyle.titleTextColor` | Member name color | +| `itemStyle.subtitleTextColor` | Subtitle text color | +| `itemStyle.separatorColor` | Row separator color | +| `itemStyle.avatarStyle` | Avatar appearance | +| `itemStyle.statusIndicatorStyle` | Online/offline indicator | + +See [Component Styling](/ui-kit/android/v6/component-styling) for the full reference. + +--- + +## Next Steps + + + + Browse and search available groups + + + Browse recent conversations + + + Detailed styling reference with screenshots + + + Custom ViewModels, repositories, and ListOperations + + diff --git a/ui-kit/android/v6/groups.mdx b/ui-kit/android/v6/groups.mdx new file mode 100644 index 000000000..80b72af5a --- /dev/null +++ b/ui-kit/android/v6/groups.mdx @@ -0,0 +1,974 @@ +--- +title: "Groups" +description: "Scrollable list of all available groups with search, avatars, names, and group type indicators." +--- + +`CometChatGroups` renders a scrollable list of all available groups with real-time updates for membership changes, search, avatars, and group type indicators (public, private, password-protected). + + + + + +--- + +## Where It Fits + +`CometChatGroups` is a list component. It renders all available groups and emits the selected `Group` via `onItemClick`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a group messaging layout. + + + + +```xml activity_chat.xml lines + +``` + +```kotlin lines +val groups = findViewById(R.id.groups) + +groups.setOnItemClick { group -> + messageHeader.setGroup(group) + messageList.setGroup(group) + messageComposer.setGroup(group) +} +``` + + + + +```kotlin lines +CometChatGroups( + modifier = Modifier.fillMaxSize(), + onItemClick = { group -> + messageHeader.setGroup(group) + messageList.setGroup(group) + messageComposer.setGroup(group) + } +) +``` + + + + +--- + +## Quick Start + + + + +Add to your layout XML: + +```xml lines + +``` + +Or programmatically: + +```kotlin lines +override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(CometChatGroups(this)) +} +``` + + + + +```kotlin lines +@Composable +fun GroupsScreen() { + CometChatGroups( + modifier = Modifier.fillMaxSize() + ) +} +``` + + + + +Prerequisites: CometChat SDK initialized with `CometChatUIKit.init()`, a user logged in, and the UI Kit dependency added. + +Or in a Fragment: + + + + +```kotlin lines +override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + return CometChatGroups(requireContext()) +} +``` + + + + +```kotlin lines +override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { + return ComposeView(requireContext()).apply { + setContent { CometChatGroups() } + } +} +``` + + + + +--- + +## Filtering Groups + + + + +Pass a `GroupsRequest.GroupsRequestBuilder` to control what loads: + +```kotlin lines +groups.setGroupsRequestBuilder( + GroupsRequest.GroupsRequestBuilder() + .joinedOnly(true) + .setLimit(20) +) +``` + + + + +```kotlin lines +CometChatGroups( + groupsRequestBuilder = GroupsRequest.GroupsRequestBuilder() + .joinedOnly(true) + .setLimit(20) +) +``` + + + + +### Filter Recipes + +| Recipe | Builder method | +| --- | --- | +| Joined only | `.joinedOnly(true)` | +| Limit per page | `.setLimit(10)` | +| Search by keyword | `.setSearchKeyWord("design")` | +| Filter by tags | `.setTags(listOf("vip"))` | +| With tags | `.withTags(true)` | + + +Pass the builder object, not the result of `.build()`. The component calls `.build()` internally. Default page size is 30 with infinite scroll. + + +--- + +## Actions and Events + +### Callback Methods + +#### `onItemClick` + +Fires when a group row is tapped. Primary navigation hook. + + + + +```kotlin lines +groups.setOnItemClick { group -> + // Navigate to group chat screen +} +``` + + + + +```kotlin lines +CometChatGroups( + onItemClick = { group -> + // Navigate to group chat screen + } +) +``` + + + + +> Replaces the default item-click behavior. Your custom lambda executes instead of the built-in navigation. + +#### `onItemLongClick` + +Fires when a group row is long-pressed. Use for additional actions like delete or leave. + + + + +```kotlin lines +groups.setOnItemLongClick { group -> + // Show context menu +} +``` + + + + +```kotlin lines +CometChatGroups( + onItemLongClick = { group -> + // Show context menu + } +) +``` + + + + +#### `onBackPress` + +Fires when the user presses the back button in the toolbar. + + + + +```kotlin lines +groups.setOnBackPress { + finish() +} +``` + + + + +```kotlin lines +CometChatGroups( + onBackPress = { /* navigate back */ } +) +``` + + + + +#### `onSearchClick` + +Fires when the user taps the search icon in the toolbar. + + + + +```kotlin lines +groups.setOnSearchClick { + // Open search screen +} +``` + + + + +```kotlin lines +CometChatGroups( + onSearchClick = { /* open search */ } +) +``` + + + + +#### `onSelection` + +Fires when groups are selected/deselected in multi-select mode. + + + + +```kotlin lines +groups.setSelectionMode(UIKitConstants.SelectionMode.MULTIPLE) +groups.setOnSelection { selectedGroups -> + updateToolbar(selectedGroups.size) +} +``` + + + + +```kotlin lines +CometChatGroups( + selectionMode = UIKitConstants.SelectionMode.MULTIPLE, + onSelection = { selectedGroups -> + updateToolbar(selectedGroups.size) + } +) +``` + + + + +#### `onError` + +Fires on internal errors (network failure, auth issue, SDK exception). + + + + +```kotlin lines +groups.setOnError { exception -> + Log.e("Groups", "Error: ${exception.message}") +} +``` + + + + +```kotlin lines +CometChatGroups( + onError = { exception -> + Log.e("Groups", "Error: ${exception.message}") + } +) +``` + + + + +#### `onLoad` + +Fires when the list is successfully fetched and loaded. + + + + +```kotlin lines +groups.setOnLoad { groupList -> + Log.d("Groups", "Loaded ${groupList.size}") +} +``` + + + + +```kotlin lines +CometChatGroups( + onLoad = { groupList -> + Log.d("Groups", "Loaded ${groupList.size}") + } +) +``` + + + + +#### `onEmpty` + +Fires when the list is empty after loading. + + + + +```kotlin lines +groups.setOnEmpty { + Log.d("Groups", "No groups found") +} +``` + + + + +```kotlin lines +CometChatGroups( + onEmpty = { /* no groups */ } +) +``` + + + + +### SDK Events (Real-Time, Automatic) + +The component listens to these SDK events internally. No manual setup needed. + +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberJoined` | Updates the group list when a member joins | +| `onGroupMemberLeft` | Updates the group list when a member leaves | +| `onGroupMemberKicked` | Updates the group list when a member is kicked | +| `onGroupMemberBanned` | Updates the group list when a member is banned | +| `onGroupMemberUnbanned` | Updates the group list when a member is unbanned | +| `onGroupMemberScopeChanged` | Updates the group list when a member's scope changes | +| `onMemberAddedToGroup` | Updates the group list when members are added | + +--- + +## Functionality + +| Method (Kotlin XML) | Compose Parameter | Description | +| --- | --- | --- | +| `setBackIconVisibility(View.VISIBLE)` | `hideBackIcon = false` | Toggle back button | +| `setToolbarVisibility(View.GONE)` | `hideToolbar = true` | Toggle toolbar | +| `setSearchBoxVisibility(View.GONE)` | `hideSearchBox = true` | Toggle search box | +| `setGroupTypeVisibility(View.GONE)` | `hideGroupType = true` | Toggle group type indicator | +| `setSeparatorVisibility(View.GONE)` | `hideSeparator = true` | Toggle list separators | +| `setSelectionMode(MULTIPLE)` | `selectionMode = MULTIPLE` | Enable selection mode | +| `setTitle("My Groups")` | `title = "My Groups"` | Custom toolbar title | +| `setSearchPlaceholderText("Find...")` | `searchPlaceholderText = "Find..."` | Search placeholder | + +--- + +## Custom View Slots + +### Leading View + +Replace the avatar / left section. + + + + + + + + +```kotlin lines +groups.setLeadingView(object : GroupsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return ImageView(context).apply { + layoutParams = ViewGroup.LayoutParams(48.dp, 48.dp) + } + } + + override fun bindView( + context: Context, createdView: View, group: Group, + holder: RecyclerView.ViewHolder, groupList: List, position: Int + ) { + val imageView = createdView as ImageView + // Load group avatar + } +}) +``` + + + + +```kotlin lines +CometChatGroups( + leadingView = { group -> + CometChatAvatar( + imageUrl = group.icon, + name = group.name + ) + } +) +``` + + + + +### Title View + +Replace the name / title text. + + + + + + + + +```kotlin lines +groups.setTitleView(object : GroupsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context) + } + + override fun bindView( + context: Context, createdView: View, group: Group, + holder: RecyclerView.ViewHolder, groupList: List, position: Int + ) { + (createdView as TextView).text = group.name ?: "" + } +}) +``` + + + + +```kotlin lines +CometChatGroups( + titleView = { group -> + Text( + text = group.name ?: "", + style = CometChatTheme.typography.heading4Medium + ) + } +) +``` + + + + +### Subtitle View + +Replace the subtitle text below the group name. + + + + + + + + +```kotlin lines +groups.setSubtitleView(object : GroupsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context).apply { maxLines = 1; ellipsize = TextUtils.TruncateAt.END } + } + + override fun bindView( + context: Context, createdView: View, group: Group, + holder: RecyclerView.ViewHolder, groupList: List, position: Int + ) { + (createdView as TextView).text = "${group.membersCount} members" + } +}) +``` + + + + +```kotlin lines +CometChatGroups( + subtitleView = { group -> + Text( + text = "${group.membersCount} members", + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } +) +``` + + + + +### Trailing View + +Replace the right section of each group item. + + + + + + + + +```kotlin lines +groups.setTrailingView(object : GroupsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return TextView(context) + } + + override fun bindView( + context: Context, createdView: View, group: Group, + holder: RecyclerView.ViewHolder, groupList: List, position: Int + ) { + (createdView as TextView).text = if (group.isJoined) "Joined" else "Join" + } +}) +``` + + + + +```kotlin lines +CometChatGroups( + trailingView = { group -> + Text(text = if (group.isJoined) "Joined" else "Join") + } +) +``` + + + + +### Item View + +Replace the entire list item row. + + + + + + + + +```kotlin lines +groups.setItemView(object : GroupsViewHolderListener() { + override fun createView(context: Context, binding: CometchatListBaseItemsBinding): View { + return LayoutInflater.from(context).inflate(R.layout.custom_group_item, null) + } + + override fun bindView( + context: Context, createdView: View, group: Group, + holder: RecyclerView.ViewHolder, groupList: List, position: Int + ) { + val avatar = createdView.findViewById(R.id.custom_avatar) + val title = createdView.findViewById(R.id.tvName) + title.text = group.name + avatar.setAvatar(group.name, group.icon) + } +}) +``` + + + + +```kotlin lines +CometChatGroups( + itemView = { group -> + Row( + modifier = Modifier.fillMaxWidth().padding(12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + CometChatAvatar(imageUrl = group.icon, name = group.name) + Spacer(Modifier.width(12.dp)) + Column { + Text(group.name ?: "", style = CometChatTheme.typography.heading4Medium) + Text("${group.membersCount} members", style = CometChatTheme.typography.body3Regular) + } + } + } +) +``` + + + + +### State Views + + + + +```kotlin lines +groups.setEmptyView(R.layout.custom_empty_view) +groups.setErrorView(R.layout.custom_error_view) +groups.setLoadingView(R.layout.custom_loading_view) +``` + + + + +```kotlin lines +CometChatGroups( + emptyView = { Text("No groups found") }, + errorView = { onRetry -> Button(onClick = onRetry) { Text("Retry") } }, + loadingView = { CircularProgressIndicator() } +) +``` + + + + +### Overflow Menu + + + + + + + + +```kotlin lines +groups.setOverflowMenu(ImageButton(context).apply { + setImageResource(R.drawable.ic_create_group) + setOnClickListener { /* create group */ } +}) +``` + + + + +```kotlin lines +CometChatGroups( + overflowMenu = { + IconButton(onClick = { /* create group */ }) { + Icon(painterResource(R.drawable.ic_create_group), "Create Group") + } + } +) +``` + + + + +--- + +## Menu Options + + + + +```kotlin lines +// Replace all options +groups.setOptions { context, group -> + listOf( + CometChatPopupMenu.MenuItem(id = "leave", name = "Leave", onClick = { /* ... */ }), + CometChatPopupMenu.MenuItem(id = "delete", name = "Delete", onClick = { /* ... */ }) + ) +} + +// Append to defaults +groups.setAddOptions { context, group -> + listOf( + CometChatPopupMenu.MenuItem(id = "pin", name = "Pin", onClick = { /* ... */ }) + ) +} +``` + + + + +```kotlin lines +CometChatGroups( + options = { context, group -> + listOf( + MenuItem(id = "leave", name = "Leave", onClick = { /* ... */ }), + MenuItem(id = "delete", name = "Delete", onClick = { /* ... */ }) + ) + }, + addOptions = { context, group -> + listOf(MenuItem(id = "pin", name = "Pin", onClick = { /* ... */ })) + } +) +``` + + + + +--- + +## Common Patterns + +### Minimal list — hide all chrome + + + + +```kotlin lines +groups.setToolbarVisibility(View.GONE) +groups.setSearchBoxVisibility(View.GONE) +groups.setGroupTypeVisibility(View.GONE) +``` + + + + +```kotlin lines +CometChatGroups( + hideToolbar = true, + hideSearchBox = true, + hideGroupType = true +) +``` + + + + +### Joined groups only + + + + +```kotlin lines +groups.setGroupsRequestBuilder( + GroupsRequest.GroupsRequestBuilder() + .joinedOnly(true) +) +``` + + + + +```kotlin lines +CometChatGroups( + groupsRequestBuilder = GroupsRequest.GroupsRequestBuilder() + .joinedOnly(true) +) +``` + + + + +### Tagged groups + + + + +```kotlin lines +groups.setGroupsRequestBuilder( + GroupsRequest.GroupsRequestBuilder() + .setTags(listOf("support")) + .withTags(true) +) +``` + + + + +```kotlin lines +CometChatGroups( + groupsRequestBuilder = GroupsRequest.GroupsRequestBuilder() + .setTags(listOf("support")) + .withTags(true) +) +``` + + + + +--- + +## Advanced Methods + +### Programmatic Selection + + + + +```kotlin lines +// Enable selection +groups.setSelectionMode(UIKitConstants.SelectionMode.MULTIPLE) + +// Select a group +groups.selectGroup(group, UIKitConstants.SelectionMode.MULTIPLE) + +// Get selected +val selected = groups.getSelectedGroups() + +// Clear +groups.clearSelection() +``` + + + + +Selection is managed via the `selectionMode` and `onSelection` parameters. The component handles selection state internally. + + + + +### ViewModel Access + +```kotlin lines +val factory = CometChatGroupsViewModelFactory() +val viewModel = ViewModelProvider(this, factory) + .get(CometChatGroupsViewModel::class.java) +``` + + + + +```kotlin lines +groups.setViewModel(viewModel) +``` + + + + +```kotlin lines +CometChatGroups( + groupsViewModel = viewModel +) +``` + + + + +See [ViewModel & Data](/ui-kit/android/v6/customization-viewmodel-data) for ListOperations, state observation, and custom repositories. + +--- + +## Style + + + + + + + + +Define a custom style in `themes.xml`: + +```xml themes.xml lines + + + + + +``` + + + + +```kotlin lines +CometChatGroups( + style = CometChatGroupsStyle.default().copy( + backgroundColor = Color(0xFFF5F5F5), + titleTextColor = Color(0xFF141414), + itemStyle = CometChatGroupsItemStyle.default().copy( + backgroundColor = Color.White, + titleTextColor = Color(0xFF141414), + subtitleTextColor = Color(0xFF727272), + avatarStyle = CometChatAvatarStyle.default().copy(cornerRadius = 12.dp), + statusIndicatorStyle = CometChatStatusIndicatorStyle.default().copy() + ) + ) +) +``` + + + + +### Style Properties + +| Property | Description | +| --- | --- | +| `backgroundColor` | List background color | +| `titleTextColor` | Toolbar title color | +| `searchBoxStyle` | Search box appearance | +| `itemStyle.backgroundColor` | Row background | +| `itemStyle.selectedBackgroundColor` | Selected row background | +| `itemStyle.titleTextColor` | Group name color | +| `itemStyle.subtitleTextColor` | Subtitle text color | +| `itemStyle.separatorColor` | Row separator color | +| `itemStyle.avatarStyle` | Avatar appearance | +| `itemStyle.statusIndicatorStyle` | Group type indicator | + +See [Component Styling](/ui-kit/android/v6/component-styling) for the full reference. + +--- + +## Next Steps + + + + View and manage group members + + + Browse recent conversations + + + Detailed styling reference with screenshots + + + Custom ViewModels, repositories, and ListOperations + + diff --git a/ui-kit/android/v6/guide-ai-agent.mdx b/ui-kit/android/v6/guide-ai-agent.mdx new file mode 100644 index 000000000..2da496105 --- /dev/null +++ b/ui-kit/android/v6/guide-ai-agent.mdx @@ -0,0 +1,419 @@ +--- +title: "AI Agent Integration" +sidebarTitle: "AI Agent Integration" +description: "Enable AI-powered conversational assistance with chat history, contextual responses, and seamless handoffs." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin-android` · `com.cometchat:chatuikit-compose-android` | +| Key components | `CometChatAIAssistantChatHistory`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader` | +| Purpose | Enable AI-powered conversational assistance with chat history, contextual responses, and seamless handoffs. | +| Related | [AI Assistant Chat History](/ui-kit/android/v6/ai-assistant-chat-history), [AI Features](/ui-kit/android/v6/ai-features), [All Guides](/ui-kit/android/v6/guide-overview) | + + + +Enable intelligent conversational AI capabilities in your Android app using CometChat UIKit v6 with AI Agent integration: + +- **AI Assistant Chat History** +- **Chat History Management** +- **Contextual Responses** +- **Agent Detection** +- **Seamless Handoffs** + +Transform your chat experience with AI-powered assistance that provides intelligent responses and seamless integration with your existing chat infrastructure. + +## Overview + +Users can interact with AI agents through a dedicated chat interface that: + +- Provides intelligent responses based on conversation context. +- Maintains chat history for continuity. +- Seamlessly integrates with your existing user chat system. + +The AI Agent chat interface provides a familiar messaging experience enhanced with AI capabilities, accessible through your main chat flow or as a standalone feature. + + + + + +## Prerequisites + +- Android Studio project with `com.cometchat:chatuikit-kotlin-android` or `com.cometchat:chatuikit-compose-android` in `build.gradle`. +- Internet permission in `AndroidManifest.xml`. +- Valid CometChat **App ID**, **Region**, and **Auth Key** configured via `UIKitSettings`. +- User logged in with `CometChatUIKit.login()`. +- AI Agent configured in your CometChat dashboard. + +## Components + +| Component / Class | Role | +|:----------------------------------|:-----| +| `AIAssistantChatActivity` | Main activity for AI agent chat. | +| `CometChatAIAssistantChatHistory` | Displays previous AI conversation history. | +| `CometChatMessageList` | Shows AI messages with threading support. | +| `CometChatMessageComposer` | Input interface for AI conversations. | +| `CometChatMessageHeader` | Header with AI agent info and controls. | + +## Integration Steps + +### Step 1 — Activity / Screen Setup + +Create the AI Assistant chat screen with proper layout configuration. + + + +```kotlin AIAssistantChatActivity.kt lines +class AIAssistantChatActivity : AppCompatActivity() { + private lateinit var binding: ActivityAiAssistantChatBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityAiAssistantChatBinding.inflate(layoutInflater) + setContentView(binding.root) + + val messageJson = intent.getStringExtra(getString(R.string.app_base_message)) + val userJson = intent.getStringExtra(getString(R.string.app_user)) + + var user: User? = null + var parentMessage: BaseMessage? = null + + if (!userJson.isNullOrEmpty()) + user = User.fromJson(userJson) + if (!messageJson.isNullOrEmpty()) + parentMessage = BaseMessage.processMessage(JSONObject(messageJson)) + + initializeComponents(user, parentMessage) + initClickListeners() + } + + private fun initializeComponents(user: User?, parentMessage: BaseMessage?) { + user?.let { + binding.messageHeader.user = it + binding.messageList.user = it + binding.messageComposer.user = it + } + + if (parentMessage != null) { + binding.messageList.setParentMessage(parentMessage.getId()) + binding.messageComposer.setParentMessageId(parentMessage.getId()) + } + + binding.messageList.setStyle(R.style.CustomCometChatMessageListStyle) + binding.messageComposer.style = R.style.CustomMessageComposerStyle + } +} +``` + + + +```kotlin AIAssistantChatScreen.kt lines +import com.cometchat.uikit.compose.presentation.messageheader.ui.CometChatMessageHeader +import com.cometchat.uikit.compose.presentation.messagelist.ui.CometChatMessageList +import com.cometchat.uikit.compose.presentation.messagecomposer.ui.CometChatMessageComposer + +@Composable +fun AIAssistantChatScreen( + user: User, + parentMessageId: Int? = null, + onNewChatClick: () -> Unit = {}, + onChatHistoryClick: () -> Unit = {} +) { + Column(modifier = Modifier.fillMaxSize()) { + CometChatMessageHeader( + user = user + ) + + CometChatMessageList( + user = user, + parentMessageId = parentMessageId ?: 0, + modifier = Modifier.weight(1f) + ) + + CometChatMessageComposer( + user = user, + parentMessageId = parentMessageId ?: 0 + ) + } +} +``` + + + +**File reference:** +[`AIAssistantChatActivity.kt`](https://github.com/cometchat/cometchat-uikit-android/blob/v6/ai-sample-app/src/main/java/com/cometchat/ai/sampleapp/ui/activity/AIAssistantChatActivity.kt) + +### Step 2 — Layout (XML Views only) + +Add `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to your layout. + +```xml activity_ai_assistant_chat.xml lines + + + + + + + + + +``` + +> **Note:** In Jetpack Compose, layout is handled declaratively in the composable function — no XML needed. + +### Step 3 — Style of Message List & Composer (XML Views only) + +Define custom styles for the message list and composer to differentiate AI agent chats. + +```xml themes.xml lines + + + + + +``` + +> **Jetpack Compose:** Pass a custom style object via the `style` parameter on each composable instead of XML styles. + +### Step 4 — Initialize click listeners + +Initialize click listeners to handle new chat creation and chat history access. + + + +```kotlin AIAssistantChatActivity.kt lines +private fun initClickListeners() { + // New chat creation + binding.messageHeader.setNewChatButtonClick { + Utils.hideKeyBoard(this@AIAssistantChatActivity, binding.root) + val intent = Intent(this@AIAssistantChatActivity, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), user.toJson().toString()) + startActivity(intent) + finish() + } + + // Chat history access + binding.messageHeader.setChatHistoryButtonClick { + val intent = Intent(this@AIAssistantChatActivity, AIAssistantChatHistoryActivity::class.java) + intent.putExtra(getString(R.string.app_user), user.toJson().toString()) + startActivity(intent) + } +} +``` + + + +```kotlin AIAssistantChatScreen.kt lines +// In Jetpack Compose, pass callbacks as lambda parameters: +AIAssistantChatScreen( + user = aiUser, + onNewChatClick = { + // Navigate to a fresh AI chat screen + navController.navigate("ai_chat/${Gson().toJson(aiUser)}") + }, + onChatHistoryClick = { + // Navigate to chat history screen + navController.navigate("ai_chat_history/${Gson().toJson(aiUser)}") + } +) +``` + + + +### Step 5 — AI Assistant Chat History screen + +Create a screen to host the `CometChatAIAssistantChatHistory` component. + + + +```kotlin AIAssistantChatHistoryActivity.kt lines +class AIAssistantChatHistoryActivity : AppCompatActivity() { + private lateinit var binding: ActivityAiAssistantChatHistoryBinding + private var user: User? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityAiAssistantChatHistoryBinding.inflate(layoutInflater) + setContentView(binding.root) + + val userJson = intent.getStringExtra(getString(R.string.app_user)) + + if (userJson != null && userJson.isNotEmpty()) { + user = User.fromJson(userJson) + binding.cometchatAiAssistantChatHistory.setUser(user) + } + + initClickListeners() + } + + private fun initClickListeners() { + binding.cometchatAiAssistantChatHistory.setOnItemClickListener { view, position, message -> + val appEntity = message.getReceiver() + if (appEntity is User) { + user = appEntity + val intent = Intent(this, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), appEntity.toJson().toString()) + intent.putExtra(getString(R.string.app_base_message), message.getRawMessage().toString()) + startActivity(intent) + finish() + } + } + + binding.cometchatAiAssistantChatHistory.setOnNewChatClickListener { + val intent = Intent(this, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), user!!.toJson().toString()) + startActivity(intent) + finish() + } + + binding.cometchatAiAssistantChatHistory.setOnCloseClickListener { + finish() + } + } +} +``` + + + +```kotlin AIAssistantChatHistoryScreen.kt lines +import com.cometchat.uikit.compose.presentation.aiassistantchathistory.ui.CometChatAIAssistantChatHistory + +@Composable +fun AIAssistantChatHistoryScreen( + user: User, + navController: NavController +) { + CometChatAIAssistantChatHistory( + modifier = Modifier.fillMaxSize(), + onCloseClick = { + navController.popBackStack() + }, + onNewChatClick = { + navController.navigate("ai_chat/${Gson().toJson(user)}") + }, + onItemClick = { message -> + val receiver = message.receiver + if (receiver is User) { + navController.navigate( + "ai_chat/${Gson().toJson(receiver)}/${message.rawMessage}" + ) + } + } + ) +} +``` + + + +### Step 6 — Chat History layout (XML Views only) + +```xml activity_ai_assistant_chat_history.xml lines + + + + + +``` + +> **Note:** In Jetpack Compose, the `CometChatAIAssistantChatHistory` composable is used directly — no XML layout needed. + +### Step 7 — Launching AI Chat + + + +```kotlin lines +fun launchAIAssistantChat(aiUser: User) { + val intent = Intent(this, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), aiUser.toJson().toString()) + startActivity(intent) +} +``` + + + +```kotlin lines +// In your NavHost setup: +composable("ai_chat/{userJson}") { backStackEntry -> + val userJson = backStackEntry.arguments?.getString("userJson") + val user = Gson().fromJson(userJson, User::class.java) + AIAssistantChatScreen(user = user) +} + +composable("ai_chat_history/{userJson}") { backStackEntry -> + val userJson = backStackEntry.arguments?.getString("userJson") + val user = Gson().fromJson(userJson, User::class.java) + AIAssistantChatHistoryScreen(user = user, navController = navController) +} +``` + + + +## Implementation Flow Summary + +| Step | Action | +|:-----|:-------| +| 1 | User selects AI agent from chat list | +| 2 | AI chat screen launches | +| 3 | Parse intent data and detect agent chat (Role of user must be "@agentic") | +| 4 | Initialize UI with AI-specific styling | +| 5 | Configure chat history and navigation | +| 6 | Launch chat with AI agent | + +## Customization Options + +- **Custom AI Assistant Empty Chat View:** Customize the empty state view using `setAIAssistantEmptyChatGreetingView()` (XML Views) or the `emptyView` composable slot (Compose). +- **Streaming Speed:** Adjust AI response streaming speed via `setStreamingSpeed()`. +- **AI Assistant Suggested Messages:** Create custom list of suggested messages using `setAIAssistantSuggestedMessages()`. +- **AI Assistant Tools:** Set tools for the AI agent using `setAIAssistantTools()`. + +## Feature Matrix + +| Feature | Kotlin (XML Views) | Jetpack Compose | +|:--------|:-------------------|:----------------| +| AI Chat Interface | `AIAssistantChatActivity` | `AIAssistantChatScreen` composable | +| Chat History | `CometChatAIAssistantChatHistory` XML | `CometChatAIAssistantChatHistory()` composable | +| Message List | `CometChatMessageList` XML | `CometChatMessageList()` composable | +| Message Composer | `CometChatMessageComposer` XML | `CometChatMessageComposer()` composable | + + + + Explore this feature in the CometChat AI Builder: + [GitHub → AI Builder](https://github.com/cometchat/cometchat-uikit-android/tree/v6/ai-sample-app) + + + Explore this feature in the CometChat SampleApp: + [GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-android/tree/v6/sample-app-kotlin) + + diff --git a/ui-kit/android/v6/guide-block-unblock-user.mdx b/ui-kit/android/v6/guide-block-unblock-user.mdx new file mode 100644 index 000000000..c70dd069c --- /dev/null +++ b/ui-kit/android/v6/guide-block-unblock-user.mdx @@ -0,0 +1,277 @@ +--- +title: "Block/Unblock User" +sidebarTitle: "Block/Unblock User" +description: "Let users block and unblock others directly within chat to control unwanted communication." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin` · `com.cometchat:chatuikit-jetpack` | +| Key components | `CometChatMessageComposer`, `CometChat.blockUsers()`, `CometChat.unblockUsers()`, `User.isBlockedByMe()` | +| Purpose | Let users block and unblock others directly within chat to control unwanted communication. | +| Related | [Message Composer](/ui-kit/android/v6/message-composer), [Message List](/ui-kit/android/v6/message-list), [All Guides](/ui-kit/android/v6/guide-overview) | + + + +Enable users to block and unblock others directly within chat using CometChat's Android UI Kit v5+, preventing unwanted communication and giving users more control. + +## Overview + +Blocking a user stops them from sending messages to the blocker. The CometChat UIKit handles most behaviors internally: + +- **Composer Hidden:** The message composer is hidden when chatting with a blocked user. +- **Unblock Prompt:** An "Unblock" button is displayed to reverse the block. +- **Message Restrictions:** Blocked users cannot send messages to the blocker. + +## Prerequisites + +- Android Studio project with CometChat Android UI Kit v5 added to `build.gradle`. +- CometChat **App ID**, **Auth Key**, and **Region** configured and initialized. +- `` in `AndroidManifest.xml`. +- Logged-in user via `CometChatUIKit.login()`. +- Existing one-on-one chat screen using `CometChatMessageList` and `CometChatMessageComposer`. + +## Components + +| Component / Class | Role | +|:-------------------------------------|:------------------------------------------------------------| +| `UserDetailActivity` | Displays user profile and provides block/unblock options. | +| `MessagesActivity` | Hosts the chat screen and toggles UI based on block state. | +| `CometChat.blockUsers()` | SDK API to block one or more users by UID. | +| `CometChat.unblockUsers()` | SDK API to unblock one or more users by UID. | +| `User.isBlockedByMe()` | Checks if the current user has blocked this user. | +| `unblockLayout` (View) | Layout shown when a user is blocked, containing unblock. | +| `CometChatMessageComposer` | Hidden when chatting with a blocked user. | + +## Integration Steps + +### 1. Detect Block Status + +Update UI when block state changes. + + + +```kotlin lines +// In MessagesActivity.kt +import com.cometchat.uikit.kotlin.presentation.messagecomposer.ui.CometChatMessageComposer + +private fun updateUserBlockStatus(user: User) { + val blocked = user.isBlockedByMe + binding.messageComposer.visibility = if (blocked) View.GONE else View.VISIBLE + binding.unblockLayout.visibility = if (blocked) View.VISIBLE else View.GONE +} +``` + + + +```kotlin lines +// In MessagesScreen.kt +import com.cometchat.uikit.compose.presentation.messagecomposer.ui.CometChatMessageComposer + +@Composable +fun MessagesScreen(user: User) { + val blocked = user.isBlockedByMe + + Column(modifier = Modifier.fillMaxSize()) { + // Message list... + + if (blocked) { + UnblockPrompt(onUnblock = { /* unblock logic */ }) + } else { + CometChatMessageComposer(user = user) + } + } +} +``` + + + +**File reference:** +[`MessagesActivity.kt`](https://github.com/cometchat/cometchat-uikit-android/blob/v6/sample-app-kotlin) + +Ensures the composer and unblock UI reflect the current block state. + +### 2. Hide Composer & Show Unblock UI + +Define layout elements and their visibility toggles. + +```xml activity_messages.xml lines + + + + + + @@ -219,6 +358,10 @@ function CreateGroupForm({ onCreate }: { onCreate: (group: CometChat.Group) => v ## Complete Example + +The **"New Group"** button lives in the conversation list's `headerView` slot — not in a separate `
` stacked above the list — so the list header stays intact and the layout doesn't shift. Because `headerView` replaces the entire default header, re-render the default title (**"Chats"**) alongside the button. + + ```tsx GroupChat.tsx import { useState } from "react"; import { CometChat } from "@cometchat/chat-sdk-javascript"; @@ -233,21 +376,27 @@ import { function CreateGroupForm({ onCreate }: { onCreate: (group: CometChat.Group) => void }) { const [name, setName] = useState(""); const [type, setType] = useState(CometChat.GROUP_TYPE.PUBLIC); + const [password, setPassword] = useState(""); + + const isPasswordType = type === CometChat.GROUP_TYPE.PASSWORD; async function handleSubmit(e: React.FormEvent) { e.preventDefault(); if (!name.trim()) return; + if (isPasswordType && !password) return; const group = new CometChat.Group( "group-" + Date.now(), name.trim(), - type as typeof CometChat.GROUP_TYPE.PUBLIC + type, + isPasswordType ? password : "" ); try { const createdGroup = await CometChat.createGroup(group); onCreate(createdGroup); setName(""); + setPassword(""); } catch (error) { console.error("Group creation failed:", error); } @@ -267,9 +416,18 @@ function CreateGroupForm({ onCreate }: { onCreate: (group: CometChat.Group) => v style={{ width: "100%", marginBottom: "8px", padding: "8px" }} > - + + {isPasswordType && ( + setPassword(e.target.value)} + placeholder="Group password" + style={{ width: "100%", marginBottom: "8px", padding: "8px" }} + /> + )} @@ -310,19 +468,21 @@ function GroupChat() { return (
-
- -
- {showCreateForm && }
- + + Chats + +
+ } + />
@@ -353,6 +513,8 @@ export default App; ## Next Steps - [Groups](/ui-kit/react/components/groups) — browse and join existing groups -- [Group Members](/ui-kit/react/components/group-members) — manage group membership +- [Group Members](/ui-kit/react/components/group-members) — manage group membership with role-based actions +- [Kick / Ban Members](/sdk/javascript/group-kick-ban-members) · [Change Member Scope](/sdk/javascript/group-change-member-scope) · [Transfer Ownership](/sdk/javascript/transfer-group-ownership) — SDK references - [Message Header](/ui-kit/react/components/message-header) — customize the group header +- [Event System](/ui-kit/react/event-system#user--group-actions) — react to `ui:group/created` and other group action events - [CometChatProvider](/ui-kit/react/cometchat-provider) — configure the root provider diff --git a/ui-kit/react/guide-message-privately.mdx b/ui-kit/react/guide-message-privately.mdx index 02454e238..ae0bf8111 100644 --- a/ui-kit/react/guide-message-privately.mdx +++ b/ui-kit/react/guide-message-privately.mdx @@ -105,6 +105,10 @@ async function handleMessagePrivately(uid: string) { Use `useCometChatEvents` to subscribe to the `ui:open-chat` event, which is published internally when a user clicks "Message Privately" from the context menu. When the event fires, extract the user and open the private panel. + +`ui:open-chat` is one of the UI Kit's [Event System — Navigation events](/ui-kit/react/event-system#navigation). See that page for the event payload and the full list of navigation and UI events. + + ```tsx import { useCometChatEvents } from "@cometchat/chat-uikit-react"; import type { CometChatEvent } from "@cometchat/chat-uikit-react"; @@ -260,6 +264,7 @@ export default App; ## Next Steps +- [Event System](/ui-kit/react/event-system#navigation) — reference for `ui:open-chat` and other navigation events - [Message Composer](/ui-kit/react/components/message-composer) — customize the composer for private chats - [Conversations](/ui-kit/react/components/conversations) — manage the conversations list - [Users](/ui-kit/react/components/users) — browse and select users directly diff --git a/ui-kit/react/guide-new-chat-creation.mdx b/ui-kit/react/guide-new-chat-creation.mdx index 2572cbc7f..67d708109 100644 --- a/ui-kit/react/guide-new-chat-creation.mdx +++ b/ui-kit/react/guide-new-chat-creation.mdx @@ -49,7 +49,7 @@ export default App; ## Step 2: Add a "New Chat" trigger -Create a button that opens a selection panel. Use component state to toggle between the conversations view and the user/group selection view. +Create a button that opens a selection panel. Use component state to toggle between the conversations view and the user/group selection view. Put the **"New Chat"** trigger in the conversation list's `headerView` slot rather than a separate `
` stacked above the list — that keeps the header intact and the layout stable. Because `headerView` replaces the entire default header, re-render the default title (**"Chats"**) next to the button. ```tsx NewChatApp.tsx import { useState } from "react"; @@ -67,17 +67,9 @@ function NewChatApp() { return (
-
- -
- {showNewChat ? ( setShowNewChat(false)} onSelectUser={(user) => { setActiveChat({ type: "user", entity: user }); setShowNewChat(false); @@ -90,6 +82,13 @@ function NewChatApp() { ) : (
+ Chats + +
+ } onItemClick={(conversation) => { const entity = conversation.getConversationWith(); if (entity instanceof CometChat.User) { @@ -127,9 +126,11 @@ import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatUsers, CometChatGroups } from "@cometchat/chat-uikit-react"; function UserGroupSelector({ + onCancel, onSelectUser, onSelectGroup, }: { + onCancel: () => void; onSelectUser: (user: CometChat.User) => void; onSelectGroup: (group: CometChat.Group) => void; }) { @@ -137,6 +138,10 @@ function UserGroupSelector({ return (
+
+ New Chat + +
+
-
- {showNewChat ? ( setShowNewChat(false)} onSelectUser={(user) => { setActiveChat({ type: "user", entity: user }); setShowNewChat(false); @@ -374,6 +377,13 @@ function NewChatApp() { ) : (
+ Chats + +
+ } onItemClick={(conversation) => { const entity = conversation.getConversationWith(); if (entity instanceof CometChat.User) { diff --git a/ui-kit/react/guide-threaded-messages.mdx b/ui-kit/react/guide-threaded-messages.mdx index ced528be6..72f48f797 100644 --- a/ui-kit/react/guide-threaded-messages.mdx +++ b/ui-kit/react/guide-threaded-messages.mdx @@ -45,6 +45,10 @@ function ChatWithThreads() { Use the `onThreadRepliesClick` callback on `CometChatMessageList` to capture when a user clicks "Reply in Thread." This sets the threaded message and opens the panel — no events required. + +This guide uses a state-based approach, but the UI Kit also emits `ui:thread/opened` and `ui:thread/closed` on its [Event System — Thread events](/ui-kit/react/event-system#thread). Subscribe to those with `useCometChatEvents` if you need to react to thread open/close from another component. + + _File: ChatWithThreads.tsx_ ```tsx @@ -211,4 +215,5 @@ export default App; - [Thread Header](/ui-kit/react/components/thread-header) — customize the thread header appearance - [Message List](/ui-kit/react/components/message-list) — configure message list rendering and options +- [Event System](/ui-kit/react/event-system#thread) — subscribe to `ui:thread/opened` and `ui:thread/closed` events - [CometChatProvider](/ui-kit/react/cometchat-provider) — learn about provider configuration diff --git a/ui-kit/react/integration-react.mdx b/ui-kit/react/integration-react.mdx index be1b58400..ac75d7735 100644 --- a/ui-kit/react/integration-react.mdx +++ b/ui-kit/react/integration-react.mdx @@ -188,6 +188,82 @@ Open `http://localhost:5173` (Vite) or `http://localhost:3000` (CRA). You should --- +## Layout & Sizing + +The UI Kit components are `height: 100%` / flex-fill — they **fill their parent** rather than sizing to their content. If the host layout doesn't give them room, they collapse to a sliver or overflow. The bare `height: 100vh` in the example above is the minimum; keep these rules in mind: + +- **Give the container a content-independent height _and_ width.** Use `height: 100dvh` (or `100vh`) on the outer wrapper — not `min-height` or `auto`, which collapse to ~0px because the components have no intrinsic height. +- **Constrain flex children so they scroll instead of growing.** Add `min-height: 0` (and `overflow: hidden`) to flex columns that hold a message list; without it, a long list pushes the whole layout taller instead of scrolling internally. +- **Reset any app scaffold that caps `#root`.** A fresh Vite/CRA `#root` is often `max-width`-capped, centered, and padded (from the starter's `index.css`/`App.css`) — which renders the chat gutter-boxed. Clear those: + ```css title="src/index.css" + #root { + max-width: none; + margin: 0; + padding: 0; + width: 100%; + height: 100dvh; + } + ``` +- **Don't put `transform` or `filter` on an ancestor.** Either property creates a new containing block that clips the kit's `position: fixed` overlays — context menus, the emoji keyboard, and the call screen. + +### Responsive layout + +The two-panel example is a fixed side-by-side layout, which squashes on a phone. On narrow viewports, show **one pane at a time** — the conversation list, then the message view with a back button. Drive it off a breakpoint: + +```tsx +import { useEffect, useState } from "react"; + +function useIsMobile(breakpoint = 768) { + const [isMobile, setIsMobile] = useState( + () => window.matchMedia(`(max-width: ${breakpoint}px)`).matches + ); + + useEffect(() => { + const media = window.matchMedia(`(max-width: ${breakpoint}px)`); + const onChange = () => setIsMobile(media.matches); + media.addEventListener("change", onChange); + return () => media.removeEventListener("change", onChange); + }, [breakpoint]); + + return isMobile; +} +``` + +On mobile, render **either** the list **or** the message pane based on `isMobile` and whether a conversation is selected, and use `CometChatMessageHeader`'s built-in back button (it renders by default; wire `onBack` to clear the selection, or set `hideBackButton` to control it) to return to the list: + +```tsx +// Inside App, with `chatUser`/`chatGroup` state from the example above: +const isMobile = useIsMobile(); +const hasSelection = Boolean(chatUser || chatGroup); + +if (isMobile) { + return ( + +
+ {!hasSelection ? ( + + ) : ( +
+ { + setChatUser(undefined); + setChatGroup(undefined); + }} + /> + + +
+ )} +
+
+ ); +} +``` + +--- + ## Choose a Chat Experience ### Conversation List + Message View diff --git a/ui-kit/react/llms-react-v7.mdx b/ui-kit/react/llms-react-v7.mdx new file mode 100644 index 000000000..d5ac71012 --- /dev/null +++ b/ui-kit/react/llms-react-v7.mdx @@ -0,0 +1,126 @@ +--- +title: "React UI Kit v7 — LLM docs index" +description: "Machine-readable, React-v7-scoped index of every UI Kit page as a clean .md twin. Built for AI coding agents; kept out of the human sidebar." +--- + +{/* + SCOPED LLM INDEX for the React v7 UI Kit. + - UNLISTED, NOT hidden: intentionally omitted from docs.json navigation so it never shows in + the human sidebar — but it IS built, served as a clean .md twin, and INDEXED for search + + AI assistants (so AI tools, and this pack's skill via its docs-map, can discover and read it). + - We deliberately do NOT use `hidden: true`/`noindex` here: in Mintlify `hidden` auto-applies + noindex, which would drop this page from search AND the auto global llms.txt / AI context. + We want it discoverable, so it stays indexable. + - Fetch this file's own .md twin as a lightweight, React-only routing index instead of the + site-wide /docs/llms.txt (which spans every product and is far larger). +*/} + +# React UI Kit v7 — LLM docs index (Latest) + +> Stateful, drop-in React chat/calling UI. Package `@cometchat/chat-uikit-react@7` + +> `@cometchat/chat-sdk-javascript@4`. This page is a **React-v7-only** routing index for AI +> agents — a scoped alternative to the site-wide `/docs/llms.txt`. + +## How to use this index +Each link points to the docs page; **append `.md`** to its URL to fetch the clean Markdown twin +(verbatim code + an "AI Integration Quick Reference" block with prop names, types, and defaults). +Pick the page for the intent, then read the props there. +- Convention: any docs page URL + `.md` → raw Markdown. +- Fallback: if a `.md` twin 404s, fetch the same URL **without** `.md` (HTML). Never read a + package `.d.ts` and never answer props from memory. + +## Hot path — usually no fetch needed +For a plain "add chat" the install, `init → login → render`, provider, and the core drop-in props +are stable; a well-built agent skill bakes them. Fetch below only for exhaustive props, long-tail +components, theming tokens, or feature enablement. +- Setup: [React.js Integration](/ui-kit/react/integration-react) +- Provider/lifecycle: [CometChatProvider](/ui-kit/react/cometchat-provider) +- Core drop-ins: [Conversations](/ui-kit/react/components/conversations) · [Message Header](/ui-kit/react/components/message-header) · [Message List](/ui-kit/react/components/message-list) · [Message Composer](/ui-kit/react/components/message-composer) + +## Getting started / integration +- [React.js Integration](/ui-kit/react/integration-react) +- [Next.js Integration](/ui-kit/react/integration-nextjs) +- [React Router Integration](/ui-kit/react/integration-react-router) +- [Astro Integration](/ui-kit/react/integration-astro) +- [React UI Kit — Overview](/ui-kit/react/overview) +- [Components Overview](/ui-kit/react/components-overview) + +## Core & configuration +- [CometChatProvider](/ui-kit/react/cometchat-provider) +- [Core Features](/ui-kit/react/core-features) +- [Methods](/ui-kit/react/methods) +- [Event System](/ui-kit/react/event-system) +- [Sound Manager](/ui-kit/react/sound-manager) +- [Localization](/ui-kit/react/localization) +- [Extensions](/ui-kit/react/extensions) +- [Troubleshooting](/ui-kit/react/troubleshooting) + +## Theming +- [Theming (`--cometchat-*` tokens, light/dark)](/ui-kit/react/theming) + +## Components — conversations & lists +- [Conversations](/ui-kit/react/components/conversations) +- [Users](/ui-kit/react/components/users) +- [Groups](/ui-kit/react/components/groups) +- [Group Members](/ui-kit/react/components/group-members) + +## Components — messages +- [Message Header](/ui-kit/react/components/message-header) +- [Message List](/ui-kit/react/components/message-list) +- [Message Composer](/ui-kit/react/components/message-composer) +- [Message Bubble](/ui-kit/react/components/message-bubble) +- [Thread Header](/ui-kit/react/components/thread-header) +- [Message Information](/ui-kit/react/components/message-information) +- [Reactions](/ui-kit/react/components/reactions) +- [Reaction List](/ui-kit/react/components/reaction-list) +- [Flag Message Dialog](/ui-kit/react/components/flag-message-dialog) + +## Components — message bubbles +- [Text Bubble](/ui-kit/react/components/text-bubble) +- [Image Bubble](/ui-kit/react/components/image-bubble) +- [Video Bubble](/ui-kit/react/components/video-bubble) +- [Audio Bubble](/ui-kit/react/components/audio-bubble) +- [Voice Note Bubble](/ui-kit/react/components/voice-note-bubble) +- [File Bubble](/ui-kit/react/components/file-bubble) +- [Poll Bubble](/ui-kit/react/components/poll-bubble) +- [Sticker Bubble](/ui-kit/react/components/sticker-bubble) +- [Card Bubble](/ui-kit/react/components/card-bubble) +- [Collaborative Document Bubble](/ui-kit/react/components/collaborative-document-bubble) +- [Collaborative Whiteboard Bubble](/ui-kit/react/components/collaborative-whiteboard-bubble) +- [Call Bubble](/ui-kit/react/components/call-bubble) +- [Call Action Bubble](/ui-kit/react/components/call-action-bubble) +- [Group Action Bubble](/ui-kit/react/components/group-action-bubble) +- [Delete Bubble](/ui-kit/react/components/delete-bubble) + +## Components — calling +- [Call Buttons](/ui-kit/react/components/call-buttons) +- [Incoming Call](/ui-kit/react/components/incoming-call) +- [Outgoing Call](/ui-kit/react/components/outgoing-call) +- [Call Logs](/ui-kit/react/components/call-logs) +- [Calling Integration](/ui-kit/react/calling-integration) +- [Call Features](/ui-kit/react/call-features) + +## Components — search, AI & notifications +- [Search](/ui-kit/react/components/search) +- [AI Assistant Chat](/ui-kit/react/components/ai-assistant-chat) +- [Smart / AI Features](/ui-kit/react/ai-features) +- [Notification Feed](/ui-kit/react/components/notification-feed) + +## Task guides (recipes) +- [New Chat Creation](/ui-kit/react/guide-new-chat-creation) +- [Group Chat Setup](/ui-kit/react/guide-group-chat-setup) +- [Search Messages](/ui-kit/react/guide-search-messages) +- [Threaded Messages](/ui-kit/react/guide-threaded-messages) +- [Message Privately](/ui-kit/react/guide-message-privately) +- [Block / Unblock User](/ui-kit/react/guide-block-unblock-user) + +## Framework recipes (full-page layouts) +- React: [Conversation + Messages](/ui-kit/react/react-conversation) · [One-to-One / Group](/ui-kit/react/react-one-to-one-chat) · [Tab-Based](/ui-kit/react/react-tab-based-chat) +- Next.js: [Conversation + Messages](/ui-kit/react/next-conversation) · [One-to-One / Group](/ui-kit/react/next-one-to-one-chat) · [Tab-Based](/ui-kit/react/next-tab-based-chat) +- React Router: [Conversation + Messages](/ui-kit/react/react-router-conversation) · [One-to-One / Group](/ui-kit/react/react-router-one-to-one-chat) · [Tab-Based](/ui-kit/react/react-router-tab-based-chat) +- Astro: [Conversation + Messages](/ui-kit/react/astro-conversation) · [One-to-One / Group](/ui-kit/react/astro-one-to-one-chat) · [Tab-Based](/ui-kit/react/astro-tab-based-chat) + +## Migration & misc +- [Upgrading from v6 to v7](/ui-kit/react/migration-overview) +- [v6 → v7 Property Changes](/ui-kit/react/migration-property-changes) +- [Campaigns](/ui-kit/react/campaigns) diff --git a/ui-kit/react/next-tab-based-chat.mdx b/ui-kit/react/next-tab-based-chat.mdx index 35b9649ed..ee8ee4c54 100644 --- a/ui-kit/react/next-tab-based-chat.mdx +++ b/ui-kit/react/next-tab-based-chat.mdx @@ -55,6 +55,7 @@ import { CometChatConversations, CometChatUsers, CometChatCallLogs, + CometChatGroupMembers, CometChatMessageHeader, CometChatMessageList, CometChatMessageComposer, @@ -67,6 +68,8 @@ export default function CometChatClient() { const [activeTab, setActiveTab] = useState("chat"); const [selectedUser, setSelectedUser] = useState(undefined); const [selectedGroup, setSelectedGroup] = useState(undefined); + const [selectedConversation, setSelectedConversation] = useState(undefined); + const [showDetails, setShowDetails] = useState(false); useEffect(() => { const settings = new UIKitSettingsBuilder() @@ -85,6 +88,7 @@ export default function CometChatClient() { if (!ready) return
Loading chat...
; const handleConversationClick = (conversation: CometChat.Conversation) => { + setSelectedConversation(conversation); // highlights the open row in the Conversations list const entity = conversation.getConversationWith(); if (conversation.getConversationType() === "user") { setSelectedUser(entity as CometChat.User); @@ -144,20 +148,27 @@ export default function CometChatClient() {
{activeTab === "chat" && ( - + )} {activeTab === "calls" && ( )} {activeTab === "users" && ( - + )}
{selectedUser || selectedGroup ? (
- + setShowDetails(true)} + />
@@ -166,6 +177,16 @@ export default function CometChatClient() { Select a conversation to start chatting
)} + + {/* Details / members side panel — opened from the header, closed via onBack */} + {showDetails && selectedGroup && ( +
+ setShowDetails(false)} + /> +
+ )}
); @@ -228,6 +249,15 @@ export default function CometChatClient() { flex-direction: column; } +.details-panel { + width: 320px; + height: 100%; + border-left: 1px solid #eee; + overflow: hidden; + display: flex; + flex-direction: column; +} + .empty-conversation { flex: 1; display: flex; @@ -259,6 +289,8 @@ export default function ChatPage() { 4. **Conditional rendering** — only the active tab's component mounts. Switching tabs unmounts the previous list and mounts the new one. 5. **Unified selection** — all three tabs feed into the same `selectedUser` / `selectedGroup` state. Clicking any item (conversation, call log, or user) updates the message panel. 6. **Call log handling** — when a call log is clicked, the receiver (user or group) is extracted and passed to the message components. +7. **Active highlight** — the current selection is passed back to each list as `activeConversation` / `activeUser` (and `activeGroup` on a Groups tab), so the open row stays highlighted while its chat is on screen. +8. **Details panel round-trip** — clicking the message header opens a group details / members side panel (`CometChatGroupMembers`). Its `onBack` sets `showDetails` back to `false`, closing the panel — the full open→close cycle, not just opening it. --- @@ -287,6 +319,7 @@ type Tab = "chat" | "calls" | "users" | "groups"; setSelectedGroup(group); setSelectedUser(undefined); }} + activeGroup={selectedGroup} /> )} ``` diff --git a/ui-kit/react/plugins/custom-plugin.mdx b/ui-kit/react/plugins/custom-plugin.mdx index a0b3dab77..51b6d7450 100644 --- a/ui-kit/react/plugins/custom-plugin.mdx +++ b/ui-kit/react/plugins/custom-plugin.mdx @@ -214,10 +214,12 @@ The `context` object passed to every plugin method: | `onFlagMessage` | `(msg) => void` | Open flag/report dialog | | `showToast` | `(text) => void` | Show a toast notification | | `getTextFormatters` | `() => Formatter[]` | Get text formatters for caption rendering | -| `publish` | `(event) => void` | Publish a UI event | +| `publish` | `(event) => void` | Publish a UI event — part of the UI Kit's [Event System](/ui-kit/react/event-system). Use it to drive other components (e.g. navigation, composer commands) from your plugin. | ## Tips +- **External API keys are your responsibility** — the map preview above calls the Google Maps Static API with `key=YOUR_API_KEY`. Replace it with your own Google Maps API key (an external dependency; not provided by CometChat). +- **Use `context.publish`** — to communicate with the rest of the UI, publish [UI events](/ui-kit/react/event-system) rather than reaching into other components directly - **Lazy-load heavy components** — use `React.lazy()` + `Suspense` for bubble components that import large libraries - **Use `context.getLocalizedString`** — for any user-facing text in options or bubbles - **Return `[]` from `getOptions`** — for system messages that shouldn't have a context menu diff --git a/ui-kit/react/plugins/overview.mdx b/ui-kit/react/plugins/overview.mdx index 5b466ef20..f23823b73 100644 --- a/ui-kit/react/plugins/overview.mdx +++ b/ui-kit/react/plugins/overview.mdx @@ -96,7 +96,11 @@ function App() { ## Built-in Plugins -These plugins are included automatically — no configuration needed. Each routes its message type to a bubble component; follow the component link for the full rendering behavior, props, and CSS. +These plugins are included automatically — no code configuration needed to render their message type. Each routes its message type to a bubble component; follow the component link for the full rendering behavior, props, and CSS. + + +**Extension-backed plugins require a Dashboard extension.** The renderer for the four extension plugins — **Polls** (`extension_poll`), **Stickers** (`extension_sticker`), **Collaborative Document** (`extension_document`), and **Collaborative Whiteboard** (`extension_whiteboard`) — ships with the UI Kit, but the messages themselves are only produced once the matching extension is enabled in the [CometChat Dashboard](https://app.cometchat.com). Enable each one before the composer can send it or the bubble can appear: [Polls](/fundamentals/polls), [Stickers](/fundamentals/stickers), [Collaborative Document](/fundamentals/collaborative-document), [Collaborative Whiteboard](/fundamentals/collaborative-whiteboard). + | Plugin | Message type(s) | Category | What it renders | Component | | --- | --- | --- | --- | --- | @@ -105,10 +109,10 @@ These plugins are included automatically — no configuration needed. Each route | **Video** | `video` | `message` | Video grid with poster thumbnails, duration overlays, and a fullscreen viewer | [Video Bubble](/ui-kit/react/components/video-bubble) | | **File** | `file` | `message` | Stacked file cards with type icons, size, and download | [File Bubble](/ui-kit/react/components/file-bubble) | | **Audio** | `audio` | `message` | Attached audio as stacked player cards; recorded voice notes as a waveform player | [Audio Bubble](/ui-kit/react/components/audio-bubble) | -| **Polls** | `extension_poll` | `custom` | Interactive poll with voting and live results | [Poll Bubble](/ui-kit/react/components/poll-bubble) | -| **Stickers** | `extension_sticker` | `custom` | Sticker image extracted from the message metadata | [Sticker Bubble](/ui-kit/react/components/sticker-bubble) | -| **Collaborative Document** | `extension_document` | `custom` | Document card with an "Open Document" button | [Collaborative Document Bubble](/ui-kit/react/components/collaborative-document-bubble) | -| **Collaborative Whiteboard** | `extension_whiteboard` | `custom` | Whiteboard card with an "Open Whiteboard" button | [Collaborative Whiteboard Bubble](/ui-kit/react/components/collaborative-whiteboard-bubble) | +| **Polls** ([enable in Dashboard](/fundamentals/polls)) | `extension_poll` | `custom` | Interactive poll with voting and live results | [Poll Bubble](/ui-kit/react/components/poll-bubble) | +| **Stickers** ([enable in Dashboard](/fundamentals/stickers)) | `extension_sticker` | `custom` | Sticker image extracted from the message metadata | [Sticker Bubble](/ui-kit/react/components/sticker-bubble) | +| **Collaborative Document** ([enable in Dashboard](/fundamentals/collaborative-document)) | `extension_document` | `custom` | Document card with an "Open Document" button | [Collaborative Document Bubble](/ui-kit/react/components/collaborative-document-bubble) | +| **Collaborative Whiteboard** ([enable in Dashboard](/fundamentals/collaborative-whiteboard)) | `extension_whiteboard` | `custom` | Whiteboard card with an "Open Whiteboard" button | [Collaborative Whiteboard Bubble](/ui-kit/react/components/collaborative-whiteboard-bubble) | | **Card** | any | `card` | Developer-defined card messages, drawn by the `CometChatCardView` renderer | [Card Bubble](/ui-kit/react/components/card-bubble) | | **Group Action** | `groupMember` | `action` | Centered system messages (joined, left, kicked, banned, scope change) | [Group Action Bubble](/ui-kit/react/components/group-action-bubble) | | **Call Action** | `audio` / `video` | `call` | Centered call status messages (missed, outgoing, incoming, ended) | [Call Action Bubble](/ui-kit/react/components/call-action-bubble) | diff --git a/ui-kit/react/plugins/text-formatters.mdx b/ui-kit/react/plugins/text-formatters.mdx index 13def11c9..315e9a077 100644 --- a/ui-kit/react/plugins/text-formatters.mdx +++ b/ui-kit/react/plugins/text-formatters.mdx @@ -11,14 +11,14 @@ Text formatters detect patterns in message text and transform them into formatte | Formatter | Priority | Detects | Output | | --- | --- | --- | --- | | `CometChatMarkdownFormatter` | 10 | `**bold**`, `_italic_`, `` `code` ``, `> quote`, lists, links | HTML tags (``, ``, ``, etc.) | -| `CometChatMentionsFormatter` | 50 | `<@uid:xxx>` tokens | Styled `@DisplayName` chips | +| `CometChatMentionsFormatter` | 20 | `<@uid:xxx>` tokens | Styled `@DisplayName` chips | | `CometChatUrlFormatter` | 100 | `https://...`, `www.` | Clickable `
` links | ``` Raw text: "Hey **@Alice**, check https://example.com" ↓ MarkdownFormatter (priority 10) "Hey @Alice, check https://example.com" - ↓ MentionsFormatter (priority 50) + ↓ MentionsFormatter (priority 20) "Hey @Alice, check https://example.com" ↓ UrlFormatter (priority 100) "Hey @Alice, check https://example.com" @@ -59,7 +59,7 @@ import { CometChatTextFormatter } from "@cometchat/chat-uikit-react"; export class HashtagFormatter extends CometChatTextFormatter { readonly id = "hashtag-formatter"; - override priority = 90; // After mentions (50), before URLs (100) + override priority = 90; // After mentions (20), before URLs (100) private hashtags: string[] = []; @@ -101,6 +101,8 @@ export class HashtagFormatter extends CometChatTextFormatter { ## Registering Custom Formatters +A custom formatter is not registered on its own — it must be wrapped in a custom **text plugin** (see [Plugins overview](/ui-kit/react/plugins/overview)) and that plugin registered via the provider's `plugins` prop (see [With Additional Plugins](/ui-kit/react/cometchat-provider#with-additional-plugins)). + Custom formatters are registered by creating a custom text plugin that provides them: ```typescript title="src/plugins/CustomTextPlugin.ts" @@ -120,7 +122,7 @@ export const CustomTextPlugin = { getTextFormatters(): CometChatTextFormatter[] { return [ new CometChatMarkdownFormatter(), // priority 10 - new CometChatMentionsFormatter(), // priority 50 + new CometChatMentionsFormatter(), // priority 20 new HashtagFormatter(), // priority 90 new CometChatUrlFormatter(), // priority 100 ]; diff --git a/ui-kit/react/react-conversation.mdx b/ui-kit/react/react-conversation.mdx index e4f13a2e3..342ffaab5 100644 --- a/ui-kit/react/react-conversation.mdx +++ b/ui-kit/react/react-conversation.mdx @@ -48,6 +48,7 @@ import { CometChat } from "@cometchat/chat-sdk-javascript"; import { CometChatProvider, CometChatConversations, + CometChatGroupMembers, CometChatMessageHeader, CometChatMessageList, CometChatMessageComposer, @@ -57,8 +58,11 @@ import "./App.css"; function App() { const [selectedUser, setSelectedUser] = useState(undefined); const [selectedGroup, setSelectedGroup] = useState(undefined); + const [selectedConversation, setSelectedConversation] = useState(undefined); + const [showDetails, setShowDetails] = useState(false); const handleConversationClick = (conversation: CometChat.Conversation) => { + setSelectedConversation(conversation); // highlights the open row in the Conversations list const entity = conversation.getConversationWith(); if (conversation.getConversationType() === "user") { setSelectedUser(entity as CometChat.User); @@ -73,12 +77,19 @@ function App() {
- +
{selectedUser || selectedGroup ? (
- + setShowDetails(true)} + />
@@ -87,6 +98,16 @@ function App() { Select a conversation to start chatting
)} + + {/* Details / members side panel — opened from the header, closed via onBack */} + {showDetails && selectedGroup && ( +
+ setShowDetails(false)} + /> +
+ )}
); @@ -118,6 +139,15 @@ export default App; flex-direction: column; } +.details-panel { + width: 320px; + height: 100%; + border-left: 1px solid #eee; + overflow: hidden; + display: flex; + flex-direction: column; +} + .empty-conversation { flex: 1; display: flex; @@ -138,6 +168,8 @@ export default App; 3. **handleConversationClick** extracts the `User` or `Group` from the conversation and stores it in state. 4. **Message components** (`MessageHeader`, `MessageList`, `MessageComposer`) receive either `user` or `group` as a prop — never both at the same time. 5. When the user switches conversations, state updates and the message panel re-renders with the new chat. +6. **Active highlight** — the selected conversation is passed back to the list as `activeConversation`, so the open row stays highlighted while its chat is on screen. +7. **Details panel round-trip** — clicking the message header opens a group details / members side panel (`CometChatGroupMembers`). Its `onBack` sets `showDetails` back to `false` to close it — the full open→close cycle for the side panel, not just opening it. --- diff --git a/ui-kit/react/react-router-tab-based-chat.mdx b/ui-kit/react/react-router-tab-based-chat.mdx index e6ee11cf7..023621579 100644 --- a/ui-kit/react/react-router-tab-based-chat.mdx +++ b/ui-kit/react/react-router-tab-based-chat.mdx @@ -51,6 +51,7 @@ import { CometChatConversations, CometChatUsers, CometChatCallLogs, + CometChatGroupMembers, CometChatMessageHeader, CometChatMessageList, CometChatMessageComposer, @@ -63,8 +64,11 @@ export default function TabbedChatPage() { const [activeTab, setActiveTab] = useState("chat"); const [selectedUser, setSelectedUser] = useState(undefined); const [selectedGroup, setSelectedGroup] = useState(undefined); + const [selectedConversation, setSelectedConversation] = useState(undefined); + const [showDetails, setShowDetails] = useState(false); const handleConversationClick = (conversation: CometChat.Conversation) => { + setSelectedConversation(conversation); // highlights the open row in the Conversations list const entity = conversation.getConversationWith(); if (conversation.getConversationType() === "user") { setSelectedUser(entity as CometChat.User); @@ -124,20 +128,27 @@ export default function TabbedChatPage() {
{activeTab === "chat" && ( - + )} {activeTab === "calls" && ( )} {activeTab === "users" && ( - + )}
{selectedUser || selectedGroup ? (
- + setShowDetails(true)} + />
@@ -146,6 +157,16 @@ export default function TabbedChatPage() { Select a conversation to start chatting )} + + {/* Details / members side panel — opened from the header, closed via onBack */} + {showDetails && selectedGroup && ( +
+ setShowDetails(false)} + /> +
+ )} ); @@ -208,6 +229,15 @@ export default function TabbedChatPage() { flex-direction: column; } +.details-panel { + width: 320px; + height: 100%; + border-left: 1px solid #eee; + overflow: hidden; + display: flex; + flex-direction: column; +} + .empty-conversation { flex: 1; display: flex; @@ -248,6 +278,8 @@ export default App; 3. **Unified selection** — all three tabs feed into the same `selectedUser` / `selectedGroup` state. Clicking any item (conversation, call log, or user) updates the message panel. 4. **Call log handling** — when a call log is clicked, the receiver (user or group) is extracted and passed to the message components. 5. **React Router** handles navigation — the tabbed chat page is a route component at `/chat`. +6. **Active highlight** — the current selection is passed back to each list as `activeConversation` / `activeUser` (and `activeGroup` on a Groups tab), so the open row stays highlighted while its chat is on screen. +7. **Details panel round-trip** — clicking the message header opens a group details / members side panel (`CometChatGroupMembers`). Its `onBack` sets `showDetails` back to `false`, closing the panel — the full open→close cycle, not just opening it. --- @@ -276,6 +308,7 @@ type Tab = "chat" | "calls" | "users" | "groups"; setSelectedGroup(group); setSelectedUser(undefined); }} + activeGroup={selectedGroup} /> )} ``` diff --git a/ui-kit/react/react-tab-based-chat.mdx b/ui-kit/react/react-tab-based-chat.mdx index ba4b4146d..b4b2b3106 100644 --- a/ui-kit/react/react-tab-based-chat.mdx +++ b/ui-kit/react/react-tab-based-chat.mdx @@ -50,6 +50,7 @@ import { CometChatConversations, CometChatUsers, CometChatCallLogs, + CometChatGroupMembers, CometChatMessageHeader, CometChatMessageList, CometChatMessageComposer, @@ -62,8 +63,11 @@ function App() { const [activeTab, setActiveTab] = useState("chat"); const [selectedUser, setSelectedUser] = useState(undefined); const [selectedGroup, setSelectedGroup] = useState(undefined); + const [selectedConversation, setSelectedConversation] = useState(undefined); + const [showDetails, setShowDetails] = useState(false); const handleConversationClick = (conversation: CometChat.Conversation) => { + setSelectedConversation(conversation); // highlights the open row in the Conversations list const entity = conversation.getConversationWith(); if (conversation.getConversationType() === "user") { setSelectedUser(entity as CometChat.User); @@ -123,20 +127,27 @@ function App() {
{activeTab === "chat" && ( - + )} {activeTab === "calls" && ( )} {activeTab === "users" && ( - + )}
{selectedUser || selectedGroup ? (
- + setShowDetails(true)} + />
@@ -145,6 +156,16 @@ function App() { Select a conversation to start chatting )} + + {/* Details / members side panel — opened from the header, closed via onBack */} + {showDetails && selectedGroup && ( +
+ setShowDetails(false)} + /> +
+ )} ); @@ -209,6 +230,15 @@ export default App; flex-direction: column; } +.details-panel { + width: 320px; + height: 100%; + border-left: 1px solid #eee; + overflow: hidden; + display: flex; + flex-direction: column; +} + .empty-conversation { flex: 1; display: flex; @@ -228,6 +258,8 @@ export default App; 2. **Conditional rendering** — only the active tab's component mounts. Switching tabs unmounts the previous list and mounts the new one. 3. **Unified selection** — all three tabs feed into the same `selectedUser` / `selectedGroup` state. Clicking any item (conversation, call log, or user) updates the message panel. 4. **Call log handling** — when a call log is clicked, the receiver (user or group) is extracted and passed to the message components. +5. **Active highlight** — the current selection is passed back to each list as `activeConversation` / `activeUser` (and `activeGroup` on a Groups tab), so the open row stays highlighted while its chat is on screen. +6. **Details panel round-trip** — clicking the message header opens a group details / members side panel (`CometChatGroupMembers`). Its `onBack` sets `showDetails` back to `false`, closing the panel — the full open→close cycle, not just opening it. --- @@ -256,6 +288,7 @@ type Tab = "chat" | "calls" | "users" | "groups"; setSelectedGroup(group); setSelectedUser(undefined); }} + activeGroup={selectedGroup} /> )} ``` diff --git a/ui-kit/react/theming.mdx b/ui-kit/react/theming.mdx index 2de7a9dbe..7581b2173 100644 --- a/ui-kit/react/theming.mdx +++ b/ui-kit/react/theming.mdx @@ -57,6 +57,50 @@ function ThemeToggle() { --- +## Follow the System (OS) Theme + +The UI Kit ships `light` and `dark` themes but **does not follow the operating system's color-scheme setting on its own** — there is no `theme="system"`. A fresh app stays on the default `light` theme even when the OS is in dark mode. To follow the OS, read `prefers-color-scheme` and drive the theme yourself. + +Seed the initial theme from the OS setting when you mount the provider: + +```tsx title="src/main.tsx" +const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; + + + +; +``` + +Then keep it in sync at runtime by subscribing to the media query's `change` event from inside the provider (so `useTheme` is available): + +```tsx +import { useEffect } from "react"; +import { useTheme } from "@cometchat/chat-uikit-react"; + +function useFollowSystemTheme() { + const { setTheme } = useTheme(); + + useEffect(() => { + const media = window.matchMedia("(prefers-color-scheme: dark)"); + + // Apply the current OS setting immediately. + setTheme(media.matches ? "dark" : "light"); + + // Update whenever the OS toggles light/dark. + const onChange = (event: MediaQueryListEvent) => + setTheme(event.matches ? "dark" : "light"); + media.addEventListener("change", onChange); + return () => media.removeEventListener("change", onChange); + }, [setTheme]); +} +``` + + +Call `useFollowSystemTheme()` from a component rendered **inside** `CometChatProvider`. If you also expose a manual toggle, stop calling `setTheme` from this hook once the user overrides the theme — otherwise the next OS change will revert their choice. + + +--- + ## Customizing Tokens Override CSS variables to change the look of all components at once: @@ -77,15 +121,19 @@ import "./cometchat-overrides.css"; ### Per-Theme Overrides -Target a specific theme with the `data-theme` selector: +Target a specific theme with the `data-theme` selector. The `data-theme` attribute and the `.cometchat` class sit on the **same** wrapper `
`, so use the **same-element** selector `.cometchat[data-theme="dark"]` — not the descendant form `[data-theme="dark"] .cometchat`, which matches only a `.cometchat` *nested inside* another `[data-theme]` element and therefore misses the root wrapper: ```css -[data-theme="dark"] .cometchat { +.cometchat[data-theme="dark"] { --cometchat-primary-color: #bb86fc; --cometchat-background-color-01: #121212; } ``` + +Component-class overrides *are* descendants of the wrapper, so the descendant form is correct for them — e.g. `[data-theme="dark"] .cometchat-message-list { … }`. It's only overriding tokens on the **root wrapper** that requires the same-element `.cometchat[data-theme="dark"]` selector. + + ### Per-Component Overrides Target a specific component by its BEM class name: @@ -108,6 +156,20 @@ Or wrap the component in your own class: } ``` +### Differentiating the Thread Panel + +Some surfaces paint their **own opaque token** rather than inheriting a background from their wrapper. The clearest example is the thread panel: its `CometChatMessageList` fills itself with `--cometchat-message-list-bg` (default `--cometchat-background-color-03`), while the thread header uses `--cometchat-thread-header-background` (which falls back to `--cometchat-background-color-01`). Because the list background is opaque, setting a `background` on the wrapping `
` has **no visible effect** — the list paints over it, and the panel looks mismatched against its header and composer. + +To style such a surface, override its own token instead of a wrapper background. For example, to make the thread panel's message list match its header: + +```css +/* Scope to the thread wrapper in your app */ +.my-thread-panel { + --cometchat-message-list-bg: var(--cometchat-background-color-01); + --cometchat-thread-header-background: var(--cometchat-background-color-01); +} +``` + --- ## Design Token Categories @@ -133,6 +195,8 @@ Or wrap the component in your own class: | Token | Purpose | | --- | --- | | `--cometchat-background-color-01` to `04` | Background layers (01 = base, 04 = elevated) | +| `--cometchat-message-list-bg` | Opaque background painted by `CometChatMessageList` (default `--cometchat-background-color-03`). Set this — not a wrapper `background` — to recolor the list surface | +| `--cometchat-thread-header-background` | Background of the thread panel header (falls back to `--cometchat-background-color-01`) | | `--cometchat-border-color-light` / `default` / `dark` / `highlight` | Border variants | | `--cometchat-text-color-primary` / `secondary` / `tertiary` / `disabled` / `highlight` | Text colors | | `--cometchat-icon-color-primary` / `secondary` / `tertiary` / `highlight` | Icon colors |