diff --git a/docs.json b/docs.json index 40eea0779..7cf566d09 100644 --- a/docs.json +++ b/docs.json @@ -459,6 +459,7 @@ "group": "Chat", "pages": [ "ui-kit/react/core-features", + "ui-kit/react/offline-support", "ui-kit/react/extensions", "ui-kit/react/ai-features" ] diff --git a/ui-kit/react/cometchat-provider.mdx b/ui-kit/react/cometchat-provider.mdx index 669713707..fff1a668b 100644 --- a/ui-kit/react/cometchat-provider.mdx +++ b/ui-kit/react/cometchat-provider.mdx @@ -50,6 +50,8 @@ export default App; For production, use `CometChatUIKit.loginWithAuthToken(token)` instead of `login(uid)`. +To turn on offline support (saved chats without a network, queued sends), add `.setOfflineConfig({ enabled: true })` to the builder before `build()`. See [Offline Support](/ui-kit/react/offline-support). + --- ## Props diff --git a/ui-kit/react/components/audio-bubble.mdx b/ui-kit/react/components/audio-bubble.mdx index 3d7afd903..38e7c7d29 100644 --- a/ui-kit/react/components/audio-bubble.mdx +++ b/ui-kit/react/components/audio-bubble.mdx @@ -39,6 +39,7 @@ Key capabilities: - **Download button** — download individual audio files - **Batch grouping** — rendered as one connected group when several media messages are sent together (handled by the [message list](/ui-kit/react/components/message-list#multi-attachment-batch-grouping)) - **Caption support** — optional caption rendered below the cards +- **Offline support** — with [offline support](/ui-kit/react/offline-support) on, media downloaded while online is shown from the device; a file that isn't saved shows "Available when online" while offline, and tapping it asks the SDK to download it **Live Preview** — interact with the audio bubble. diff --git a/ui-kit/react/components/conversations.mdx b/ui-kit/react/components/conversations.mdx index e997cd480..16e94cb09 100644 --- a/ui-kit/react/components/conversations.mdx +++ b/ui-kit/react/components/conversations.mdx @@ -53,6 +53,7 @@ description: "Scrollable list of recent one-on-one and group conversations for t "hideUnreadCount": { "type": "boolean", "default": false }, "hideDeleteConversation": { "type": "boolean", "default": false }, "hidePinConversation": { "type": "boolean", "default": false }, + "hideOfflineNotices": { "type": "boolean", "default": false, "since": "7.3.0", "note": "Offline support only." }, "showSearchBar": { "type": "boolean", "default": true }, "showScrollbar": { "type": "boolean", "default": false } }, @@ -165,6 +166,7 @@ The component handles: - Search filtering - Selection mode (single/multiple) - Pin conversation — pin a chat to the top of the list, with a pin indicator on the row +- Offline support (when turned on) — saved conversations first, "Connect to load chats" when nothing is saved, and a notice if unsent messages were lost. See [Offline Support](/ui-kit/react/offline-support) --- @@ -1090,6 +1092,17 @@ Remove the built-in **Pin / Unpin** option from the conversation item's context --- +### hideOfflineNotices + +Hide the notice that [offline support](/ui-kit/react/offline-support#hide-the-offline-notices) shows after a cache reset lost, or may have lost, unsent messages. Has no effect with offline support off. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + ### showSearchBar Whether to show the search bar. Set to `false` to hide it entirely. diff --git a/ui-kit/react/components/file-bubble.mdx b/ui-kit/react/components/file-bubble.mdx index d7dd901b2..0ffc1f976 100644 --- a/ui-kit/react/components/file-bubble.mdx +++ b/ui-kit/react/components/file-bubble.mdx @@ -32,6 +32,7 @@ Key capabilities: - **Download button** — download individual files - **Batch grouping** — rendered as one connected group when several media messages are sent together (handled by the [message list](/ui-kit/react/components/message-list#multi-attachment-batch-grouping)) - **Caption support** — optional caption rendered below the cards +- **Offline support** — with [offline support](/ui-kit/react/offline-support) on, media downloaded while online is shown from the device; a file that isn't saved shows "Available when online" while offline, and tapping it asks the SDK to download it **Live Preview** — interact with the file bubble. diff --git a/ui-kit/react/components/group-members.mdx b/ui-kit/react/components/group-members.mdx index f69f0b1f5..256b6b90a 100644 --- a/ui-kit/react/components/group-members.mdx +++ b/ui-kit/react/components/group-members.mdx @@ -44,6 +44,7 @@ The component handles: - Search filtering - Role-based action menus (kick, ban, change scope) - Selection mode (single/multiple) +- Offline support (when turned on) — saved members first, and "Connect to load members" or "Connect to search" when nothing is saved. See [Offline Support](/ui-kit/react/offline-support) --- diff --git a/ui-kit/react/components/groups.mdx b/ui-kit/react/components/groups.mdx index 0a3b8ae83..4df459408 100644 --- a/ui-kit/react/components/groups.mdx +++ b/ui-kit/react/components/groups.mdx @@ -45,6 +45,7 @@ The component handles: - Search filtering - Swipe/hover options - Selection mode (single/multiple) +- Offline support (when turned on) — saved groups first, and "Connect to load groups" or "Connect to search" when nothing is saved. See [Offline Support](/ui-kit/react/offline-support) --- diff --git a/ui-kit/react/components/image-bubble.mdx b/ui-kit/react/components/image-bubble.mdx index edc864c52..9014d9fb5 100644 --- a/ui-kit/react/components/image-bubble.mdx +++ b/ui-kit/react/components/image-bubble.mdx @@ -30,6 +30,7 @@ Key capabilities: - **Fullscreen gallery viewer** — click any image to open a paginated fullscreen gallery - **Batch grouping** — rendered as one connected group when several media messages are sent together (handled by the [message list](/ui-kit/react/components/message-list#multi-attachment-batch-grouping)) - **Placeholder loading** — shows a configurable placeholder while images load +- **Offline support** — with [offline support](/ui-kit/react/offline-support) on, media downloaded while online is shown from the device; a file that isn't saved shows "Available when online" while offline, and tapping it asks the SDK to download it **Live Preview** — interact with the image bubble. diff --git a/ui-kit/react/components/message-composer.mdx b/ui-kit/react/components/message-composer.mdx index 892cb3317..18e80a028 100644 --- a/ui-kit/react/components/message-composer.mdx +++ b/ui-kit/react/components/message-composer.mdx @@ -162,6 +162,7 @@ The component handles: - Edit and reply mode with preview banners - Typing indicator events - Live reactions +- Offline support (when turned on) — a text message or sticker sent without a connection is queued and goes out on reconnect. See [Offline Support](/ui-kit/react/offline-support) --- diff --git a/ui-kit/react/components/message-header.mdx b/ui-kit/react/components/message-header.mdx index 97b85d112..dc657c1e4 100644 --- a/ui-kit/react/components/message-header.mdx +++ b/ui-kit/react/components/message-header.mdx @@ -183,6 +183,7 @@ The component handles: - Online/offline presence status (for 1-on-1 conversations) - Group member count (for group conversations) - Real-time typing indicators +- Offline support (when turned on) — while the SDK is disconnected, the one-to-one header shows no "Online" subtitle and no header shows typing; a group header keeps its member count. See [Offline Support](/ui-kit/react/offline-support) - Voice and video call buttons with call state management - Back navigation for mobile layouts - AI conversation summary trigger diff --git a/ui-kit/react/components/message-list.mdx b/ui-kit/react/components/message-list.mdx index 1ceafd426..f1f05ee0b 100644 --- a/ui-kit/react/components/message-list.mdx +++ b/ui-kit/react/components/message-list.mdx @@ -82,7 +82,8 @@ description: "Scrollable message feed with plugin-based bubble rendering, reacti "showConversationStarters": { "type": "boolean", "default": false }, "showMarkAsUnreadOption": { "type": "boolean", "default": false }, "disableTruncation": { "type": "boolean", "default": false }, - "isAgentChat": { "type": "boolean", "default": false } + "isAgentChat": { "type": "boolean", "default": false }, + "hideOfflineNotices": { "type": "boolean", "default": false, "since": "7.3.0", "note": "Offline support only." } }, "optionToggles": { "hideReplyOption": { "type": "boolean", "default": false }, @@ -250,6 +251,7 @@ The component handles: - Date separators and sticky floating date header - Jump-to-message for search results and deep links - Mark-as-unread support +- Offline support (when turned on) — cached messages first, unsent messages marked with Retry and Delete, and "Connect to load …" where the cache runs out. See [Offline Support](/ui-kit/react/offline-support) > **Note:** `user` and `group` are mutually exclusive. Pass one or the other to specify the conversation context. @@ -1015,6 +1017,17 @@ Whether this is an AI agent chat. Suppresses moderation UI and enables agent-spe --- +### hideOfflineNotices + +Hide the notices about unsent messages that [offline support](/ui-kit/react/offline-support#hide-the-offline-notices) shows in the list (removed, not sent, lost in a cache reset, outbox full, send refused, send under way). Has no effect with offline support off. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + ### Option Toggles --- diff --git a/ui-kit/react/components/notification-feed.mdx b/ui-kit/react/components/notification-feed.mdx index fe47845ef..7cbdb9e55 100644 --- a/ui-kit/react/components/notification-feed.mdx +++ b/ui-kit/react/components/notification-feed.mdx @@ -207,6 +207,7 @@ The component handles these automatically — no manual setup needed: | Timestamp grouping | Groups items as "Today", "Yesterday", day name, or date | | Category filtering | Filter chips row with per-category unread badges | | Mark all read | Header button to mark all notifications as read | +| Offline support | With [offline support](/ui-kit/react/offline-support) on, saved items show first; with nothing saved offline, the feed shows "Connect to load notifications" and loads again on reconnect | --- diff --git a/ui-kit/react/components/pinned-messages.mdx b/ui-kit/react/components/pinned-messages.mdx index 75dbb3fb4..739aec846 100644 --- a/ui-kit/react/components/pinned-messages.mdx +++ b/ui-kit/react/components/pinned-messages.mdx @@ -122,6 +122,7 @@ The component handles: - Real-time updates when a message is pinned or unpinned - An overflow menu of per-message options (unpin, save, copy, info, and more) - Empty, loading, and error states +- Offline support (when turned on) — saved pinned messages first, and "Connect to load messages" when nothing is saved. See [Offline Support](/ui-kit/react/offline-support) Pinning must be enabled for your app through the `features.ux.messages.pinned.enabled` app setting for pins to load. See [Core Features](/ui-kit/react/core-features#pin-and-save-messages). diff --git a/ui-kit/react/components/reaction-list.mdx b/ui-kit/react/components/reaction-list.mdx index 60b543f59..c86e7a97a 100644 --- a/ui-kit/react/components/reaction-list.mdx +++ b/ui-kit/react/components/reaction-list.mdx @@ -161,6 +161,7 @@ Called when an error occurs during reaction fetching. - "All" tab shows every reactor across all emojis. - Per-emoji tabs show only reactors for that emoji. - Tab counts update optimistically when the current user removes a reaction. +- With [offline support](/ui-kit/react/offline-support) on and no reactors saved, the list shows "Connect to load reactions", and the tabs show the message's own reaction counts until the list can load. - Keyboard navigation: `ArrowLeft` / `ArrowRight` to move between tabs, `Enter` / `Space` to select. ### Reactor Items diff --git a/ui-kit/react/components/saved-messages.mdx b/ui-kit/react/components/saved-messages.mdx index da3115991..6f42d0b25 100644 --- a/ui-kit/react/components/saved-messages.mdx +++ b/ui-kit/react/components/saved-messages.mdx @@ -99,6 +99,7 @@ The component handles: - Real-time updates when a message is saved or unsaved - An unsave action per row - Empty, loading, and error states +- Offline support (when turned on) — saved messages from the cache first, and "Connect to load messages" when nothing is saved. See [Offline Support](/ui-kit/react/offline-support) Saving must be enabled for your app through the `features.ux.messages.saved.enabled` app setting for saves to load. See [Core Features](/ui-kit/react/core-features#pin-and-save-messages). diff --git a/ui-kit/react/components/search.mdx b/ui-kit/react/components/search.mdx index 2d1a2f27e..f2ce943d2 100644 --- a/ui-kit/react/components/search.mdx +++ b/ui-kit/react/components/search.mdx @@ -49,6 +49,7 @@ The component handles: - Scoped search via `uid` or `guid` - Custom request builders for both conversations and messages - Customizable result item views +- Offline support (when turned on) — a keyword search offline with nothing saved shows "Connect to search"; a search by filter alone is answered from the device. See [Offline Support](/ui-kit/react/offline-support) --- diff --git a/ui-kit/react/components/users.mdx b/ui-kit/react/components/users.mdx index 83d5dae6d..10b1a24c3 100644 --- a/ui-kit/react/components/users.mdx +++ b/ui-kit/react/components/users.mdx @@ -45,6 +45,7 @@ The component handles: - Search filtering - Alphabetical section headers - Selection mode (single/multiple) with optional preview chips +- Offline support (when turned on) — saved users first, and "Connect to load users" or "Connect to search" when nothing is saved. See [Offline Support](/ui-kit/react/offline-support) --- diff --git a/ui-kit/react/components/video-bubble.mdx b/ui-kit/react/components/video-bubble.mdx index 90bf286dd..97e69c165 100644 --- a/ui-kit/react/components/video-bubble.mdx +++ b/ui-kit/react/components/video-bubble.mdx @@ -32,6 +32,7 @@ Key capabilities: - **Play icon overlay** — visual indicator on each video tile - **Fullscreen viewer** — click any video to open in fullscreen player - **Batch grouping** — rendered as one connected group when several media messages are sent together (handled by the [message list](/ui-kit/react/components/message-list#multi-attachment-batch-grouping)) +- **Offline support** — with [offline support](/ui-kit/react/offline-support) on, media downloaded while online is shown from the device; a file that isn't saved shows "Available when online" while offline, and tapping it asks the SDK to download it Auto poster thumbnails are produced by the **Thumbnail Generation** extension — enable it in the Dashboard ([Thumbnail Generation](/fundamentals/thumbnail-generation)). Without it, the bubble falls back to the first video frame. diff --git a/ui-kit/react/components/voice-note-bubble.mdx b/ui-kit/react/components/voice-note-bubble.mdx index 29843de14..215befe6c 100644 --- a/ui-kit/react/components/voice-note-bubble.mdx +++ b/ui-kit/react/components/voice-note-bubble.mdx @@ -44,6 +44,7 @@ Key characteristics: - **Always standalone** — voice notes are never grouped or batched with other messages - **Metadata-driven** — only used when the message has `audioType: "voice_note"` in metadata - **Waveform player** — renders with the `CometChatAudioBubble` player and its CSS selectors +- **Offline support** — with [offline support](/ui-kit/react/offline-support) on, a voice note downloaded while online plays from the device; one that isn't saved shows "Available when online" while offline, and tapping it asks the SDK to download it **Live Preview** — interact with the voice note bubble. diff --git a/ui-kit/react/core-features.mdx b/ui-kit/react/core-features.mdx index 3dc088979..bd53cd13d 100644 --- a/ui-kit/react/core-features.mdx +++ b/ui-kit/react/core-features.mdx @@ -9,7 +9,7 @@ description: "Overview of CometChat React UI Kit core features, including messag | --- | --- | | Package | `@cometchat/chat-uikit-react` | | Required setup | Wrap app in `CometChatProvider` with valid credentials — must complete before rendering any component | -| Core features | Instant Messaging, Media Sharing, Read Receipts, Mark as Unread, Typing Indicator, User Presence, Reactions, Mentions, Quoted Reply, Pin & Save Messages, Search, Threaded Conversations, Moderation, Report Message, Group Chat | +| Core features | Instant Messaging, Media Sharing, Read Receipts, Mark as Unread, Typing Indicator, User Presence, Reactions, Mentions, Quoted Reply, Pin & Save Messages, Search, Threaded Conversations, Moderation, Report Message, Group Chat, Offline Support | | Key components | `CometChatConversations` → [Conversations](/ui-kit/react/components/conversations), `CometChatMessageList` → [Message List](/ui-kit/react/components/message-list), `CometChatMessageComposer` → [Message Composer](/ui-kit/react/components/message-composer), `CometChatMessageHeader` → [Message Header](/ui-kit/react/components/message-header), `CometChatUsers` → [Users](/ui-kit/react/components/users), `CometChatGroups` → [Groups](/ui-kit/react/components/groups), `CometChatGroupMembers` → [Group Members](/ui-kit/react/components/group-members) | | CSS class prefix | `.cometchat-` | | Theming | Override CSS variables on `.cometchat` class. See [Theming](/ui-kit/react/theming) | @@ -308,6 +308,19 @@ Search requires wiring the result callbacks to navigation: handle `onConversatio See the [Groups](/ui-kit/react/components/groups) component page for details. +## Offline Support + +With offline support turned on, chats and messages the user has already opened appear at once from a cache on the device, messages sent while offline are queued and sent automatically on reconnect, and each list tells the user when something needs a connection ("Connect to load chats", "Connect to search", "Connect to load more"). Offline support is off by default; turn it on with `setOfflineConfig()` on the `UIKitSettingsBuilder`. It needs React UI Kit 7.3.0 and JavaScript Chat SDK 4.3.0 or later. + +| Components | Functionality | +| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| [Conversations](/ui-kit/react/components/conversations) | Shows saved conversations first, then merges in the server's list. Shows a notice if unsent messages were lost in a cache reset. | +| [Message List](/ui-kit/react/components/message-list) | Opens chats from the cache, marks queued and failed messages, and offers Retry and Delete on unsent messages. | +| [Message Composer](/ui-kit/react/components/message-composer) | Queues text messages and stickers sent while offline. | +| [Users](/ui-kit/react/components/users), [Groups](/ui-kit/react/components/groups), [Group Members](/ui-kit/react/components/group-members) | Show saved rows first, and "Connect to load …" or "Connect to search" when nothing is saved. | + +See [Offline Support](/ui-kit/react/offline-support) for setup, the offline states and texts, events and customization. + --- ## Next Steps diff --git a/ui-kit/react/event-system.mdx b/ui-kit/react/event-system.mdx index 398782105..13e1e8755 100644 --- a/ui-kit/react/event-system.mdx +++ b/ui-kit/react/event-system.mdx @@ -226,7 +226,7 @@ These events are published by UI Kit components for local cross-component commun | Event Type | Payload | Published by | | --- | --- | --- | -| `ui:message/sent` | `{ message, status }` | MessageComposer | +| `ui:message/sent` | `{ message, status }` | MessageComposer; `CometChatUIKit.sendTextMessage()` / `sendMediaMessage()` / `sendCustomMessage()` | | `ui:message/deleted` | `{ message }` | MessageList (after delete) | | `ui:message/read` | `{ message }` | MessageList (mark as read) | @@ -259,6 +259,15 @@ v6's `ccMessageSent` fired at the same three stages, so the staging itself is no Change either to `status === "success"`, or import `CometChatMessageStatus` and compare with `CometChatMessageStatus.success`. +### Offline Support + +Published only with [offline support](/ui-kit/react/offline-support#events) turned on. + +| Event Type | Payload | Published by | +| --- | --- | --- | +| `ui:message/send-state-changed` | `{ message, state, reason? }` | UI Kit, when an own message's send state changes (`"sending"`, `"sent"`, `"failed"`, `"discarded"`) | +| `ui:offline/cache-reset` | `{ reason, pendingMessagesLost }` | UI Kit, when the SDK wiped and rebuilt its offline cache | + ### Pin and Save (optimistic) Published by the message options the moment a pin/save succeeds locally, before the network echo. Pinned/Saved panels and the message list listen to these so every surface flips together. diff --git a/ui-kit/react/integration-astro.mdx b/ui-kit/react/integration-astro.mdx index 6163d3a48..621c13f4b 100644 --- a/ui-kit/react/integration-astro.mdx +++ b/ui-kit/react/integration-astro.mdx @@ -17,6 +17,7 @@ description: "Add CometChat to an Astro app in 5 steps: create project, install, | Auth Key | Dev/testing only. Use Auth Token in production | | SSR | Use `client:only="react"` directive — CometChat components cannot be server-rendered | | Calling | Optional. Install `@cometchat/calls-sdk-javascript` and call `.setCallingEnabled(true)` on `UIKitSettingsBuilder` | +| Offline support | Optional, off by default. Call `.setOfflineConfig({ enabled: true })` on `UIKitSettingsBuilder`. Needs UI Kit 7.3.0 and `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support) | | Other frameworks | [React.js](/ui-kit/react/integration-react) · [Next.js](/ui-kit/react/integration-nextjs) · [React Router](/ui-kit/react/integration-react-router) | @@ -162,6 +163,10 @@ export default function CometChatApp() { For production, use `CometChatUIKit.loginWithAuthToken(token)` instead of `login(uid)`. Generate auth tokens server-side via the CometChat REST API. Never ship auth keys in client code. + +To show saved chats without a network and queue messages sent while offline, add `.setOfflineConfig({ enabled: true })` to the `UIKitSettingsBuilder` before `build()`. It is off by default and needs `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support). + + --- ## Step 4 — Render the Island in an Astro Page diff --git a/ui-kit/react/integration-nextjs.mdx b/ui-kit/react/integration-nextjs.mdx index 3f4866176..7fc81d072 100644 --- a/ui-kit/react/integration-nextjs.mdx +++ b/ui-kit/react/integration-nextjs.mdx @@ -17,6 +17,7 @@ description: "Add CometChat to a Next.js (App Router) app in 5 steps: create pro | Auth Key | Dev/testing only. Use `loginWithAuthToken` in production | | SSR | CometChat components must be loaded with `dynamic(() => import(...), { ssr: false })` | | Calling | Optional. Install `@cometchat/calls-sdk-javascript` and call `.setCallingEnabled(true)` on `UIKitSettingsBuilder` | +| Offline support | Optional, off by default. Call `.setOfflineConfig({ enabled: true })` on `UIKitSettingsBuilder`. Needs UI Kit 7.3.0 and `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support) | | Other frameworks | [React.js](/ui-kit/react/integration-react) · [React Router](/ui-kit/react/integration-react-router) · [Astro](/ui-kit/react/integration-astro) | @@ -162,6 +163,10 @@ export default function CometChatClient() { For production, use `CometChatUIKit.loginWithAuthToken(token)` instead of `login(uid)`. Generate auth tokens server-side via the CometChat REST API. Never ship auth keys in client code. + +To show saved chats without a network and queue messages sent while offline, add `.setOfflineConfig({ enabled: true })` to the `UIKitSettingsBuilder` before `build()`. It is off by default and needs `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support). + + --- ## Step 4 — Import with SSR Disabled diff --git a/ui-kit/react/integration-react-router.mdx b/ui-kit/react/integration-react-router.mdx index 0dfa7d272..e957d2ec5 100644 --- a/ui-kit/react/integration-react-router.mdx +++ b/ui-kit/react/integration-react-router.mdx @@ -17,6 +17,7 @@ description: "Add CometChat to a React Router app in 5 steps: create project, in | Auth Key | Dev/testing only. Use Auth Token in production | | SSR | N/A — client-side SPA by default | | Calling | Optional. Install `@cometchat/calls-sdk-javascript` and call `.setCallingEnabled(true)` on `UIKitSettingsBuilder` | +| Offline support | Optional, off by default. Call `.setOfflineConfig({ enabled: true })` on `UIKitSettingsBuilder`. Needs UI Kit 7.3.0 and `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support) | | Other frameworks | [React.js](/ui-kit/react/integration-react) · [Next.js](/ui-kit/react/integration-nextjs) · [Astro](/ui-kit/react/integration-astro) | @@ -180,6 +181,10 @@ Init and login complete before the app renders. `CometChatProvider` then supplie For production, use `CometChatUIKit.loginWithAuthToken(token)` instead of `login(uid)`. Generate auth tokens server-side via the CometChat REST API. Never ship auth keys in client code. + +To show saved chats without a network and queue messages sent while offline, add `.setOfflineConfig({ enabled: true })` to the `UIKitSettingsBuilder` before `build()`. It is off by default and needs `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support). + + --- ## Step 4 — Run diff --git a/ui-kit/react/integration-react.mdx b/ui-kit/react/integration-react.mdx index 6fcdb00f2..b35489136 100644 --- a/ui-kit/react/integration-react.mdx +++ b/ui-kit/react/integration-react.mdx @@ -16,6 +16,7 @@ description: "Add CometChat to a React.js app in 4 steps: create project, instal | Order | `init()` → `login()` → render ``. Breaking this order = blank screen | | Auth Key | Dev/testing only. Use Auth Token in production | | Calling | Optional. Install `@cometchat/calls-sdk-javascript` and call `.setCallingEnabled(true)` on `UIKitSettingsBuilder` | +| Offline support | Optional, off by default. Call `.setOfflineConfig({ enabled: true })` on `UIKitSettingsBuilder`. Needs UI Kit 7.3.0 and `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support) | | Other frameworks | [Next.js](/ui-kit/react/integration-nextjs) · [React Router](/ui-kit/react/integration-react-router) · [Astro](/ui-kit/react/integration-astro) | @@ -174,6 +175,10 @@ export default App; For production, use `CometChatUIKit.loginWithAuthToken(token)` instead of `login(uid)`. Generate auth tokens server-side via the [REST API](/rest-api/chat-apis). Never ship auth keys in client code. + +To show saved chats without a network and queue messages sent while offline, add `.setOfflineConfig({ enabled: true })` to the `UIKitSettingsBuilder` before `build()`. It is off by default and needs `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support). + + By default, session data is stored in `localStorage`. To use `sessionStorage` instead, see [Setting Session Storage Mode](/ui-kit/react/methods#setting-session-storage-mode). diff --git a/ui-kit/react/llms-react-v7.mdx b/ui-kit/react/llms-react-v7.mdx index d5ac71012..98c48b5ff 100644 --- a/ui-kit/react/llms-react-v7.mdx +++ b/ui-kit/react/llms-react-v7.mdx @@ -48,6 +48,7 @@ components, theming tokens, or feature enablement. ## Core & configuration - [CometChatProvider](/ui-kit/react/cometchat-provider) - [Core Features](/ui-kit/react/core-features) +- [Offline Support (cache, queued sends, offline states)](/ui-kit/react/offline-support) - [Methods](/ui-kit/react/methods) - [Event System](/ui-kit/react/event-system) - [Sound Manager](/ui-kit/react/sound-manager) diff --git a/ui-kit/react/localization.mdx b/ui-kit/react/localization.mdx index e7b179d0c..a63a45395 100644 --- a/ui-kit/react/localization.mdx +++ b/ui-kit/react/localization.mdx @@ -84,12 +84,49 @@ Override or add translation keys for a language: import { CometChatLocalize } from "@cometchat/chat-uikit-react"; const localize = CometChatLocalize.getSharedInstance(); -localize?.addTranslation("en-us", { - "custom_greeting": "Welcome to our chat!", - "message_deleted": "Message removed", // Override built-in key +localize?.addTranslation({ + "en-us": { + "custom_greeting": "Welcome to our chat!", + "message_deleted": "Message removed", // Override built-in key + }, }); ``` +`addTranslation()` takes one object keyed by language code, so you can add several languages in one call. + +### Offline Support Texts + +With [offline support](/ui-kit/react/offline-support) turned on, the UI Kit shows these texts. Every built-in language has them, and you override them like any other key. For where each one appears, see [Offline States and Texts](/ui-kit/react/offline-support#offline-states-and-texts). + +| Key | en-us | +| --- | --- | +| `conversations_connect_to_load` | Connect to load chats | +| `users_connect_to_load` | Connect to load users | +| `groups_connect_to_load` | Connect to load groups | +| `group_members_connect_to_load` | Connect to load members | +| `message_list_connect_to_load` | Connect to load messages | +| `reaction_list_connect_to_load` | Connect to load reactions | +| `notifications_connect_to_load` | Connect to load notifications | +| `search_connect_to_search` | Connect to search | +| `search_connect_to_search_messages` | Connect to search | +| `search_connect_to_search_subtitle` | Search needs an internet connection. | +| `message_list_connect_to_load_more` | Connect to load more | +| `message_list_connect_to_load_newer` | Connect to load more | +| `message_list_jump_to_latest` | Jump to latest | +| `message_list_not_sent_yet` | Not sent yet | +| `message_list_not_sent_tap_to_retry` | Not sent. Tap to retry | +| `message_bubble_media_available_when_online` | Available when online | +| `message_list_queue_full` | Too many messages waiting to send | +| `message_list_file_too_large_offline` | File too large to send offline | +| `message_list_send_in_flight` | Sending… try again in a moment | +| `message_list_option_delete_failed` | Couldn't remove the message | +| `message_list_unsent_message_removed` | 1 unsent message was removed | +| `message_list_messages_not_sent_one` / `_other` | `{{count}}` message wasn't sent / `{{count}}` messages weren't sent | +| `message_list_unsent_messages_lost_one` / `_other` | `{{count}}` unsent message couldn't be recovered / `{{count}}` unsent messages couldn't be recovered | +| `message_list_unsent_messages_maybe_lost` | Some unsent messages may not have been sent | + +The count texts are plural keys: the UI Kit picks `_one`, `_other`, and `_few` or `_many` where a language has them, for the current language, and replaces `{{count}}` with the number. Override every plural form your language uses. + --- ## Fallback Language diff --git a/ui-kit/react/methods.mdx b/ui-kit/react/methods.mdx index 4a930787c..e64843015 100644 --- a/ui-kit/react/methods.mdx +++ b/ui-kit/react/methods.mdx @@ -91,6 +91,26 @@ When using `sessionStorage`, configure it in your `UIKitSettingsBuilder` before Session storage is cleared when the browser tab is closed. Use this mode if you want users to re-authenticate on every new tab/session. +### Enabling Offline Support + +Offline support is off by default. To show saved chats and messages without a network and queue messages sent while offline, call `setOfflineConfig()` on the `UIKitSettingsBuilder` with `enabled: true`. It needs `@cometchat/chat-uikit-react` 7.3.0 and `@cometchat/chat-sdk-javascript` 4.3.0 or later; on an older SDK the setting has no effect. + +```tsx +import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; + +const settings = new UIKitSettingsBuilder() + .setAppId("APP_ID") + .setRegion("REGION") + .setAuthKey("AUTH_KEY") + .subscribePresenceForAllUsers() + .setOfflineConfig({ enabled: true }) + .build(); + +await CometChatUIKit.init(settings); +``` + +The config is passed to the SDK's `AppSettingsBuilder.setOfflineConfig()` unchanged; its type is `CometChatOfflineConfig`. `CometChatUIKit.getSettings()?.getOfflineConfig()` returns what you passed, not whether offline support is running; call `CometChat.isOfflineEnabled()` for that. See [Offline Support](/ui-kit/react/offline-support) for the options, the offline states and how each component behaves. + --- ## Authentication @@ -133,6 +153,30 @@ await CometChatUIKit.logout(); **Returns:** `Promise` +With [offline support](/ui-kit/react/offline-support) on, logging out also deletes the user's cached data and unsent messages from the device. + +#### Logging out without a connection + +When the server can't be reached, `logout()` still ends the session on the device, then rejects. A rejection alone doesn't mean the user is still logged in, so check the SDK before deciding where to go: + +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react"; + +async function signOut(showSignIn: () => void) { + try { + await CometChatUIKit.logout(); + } catch (error) { + const user = await CometChat.getLoggedinUser().catch(() => null); + if (user) { + console.error("Logout failed", error); + return; + } + } + showSignIn(); +} +``` + --- ## User Management @@ -227,19 +271,11 @@ Get conversation update settings fetched from the dashboard. ## Message Sending - -These methods are low-level utilities. They send messages via the SDK but do **not** publish `ui:message/sent` events. This means: -- The message won't appear in `CometChatMessageList` automatically -- The `CometChatConversations` list won't update - -For messages to appear in the UI, use the `CometChatMessageComposer` component, or manually publish the event after sending: + +While a `CometChatProvider` is mounted, these methods publish `ui:message/sent` (in progress, then success or error), so a mounted `CometChatMessageList` and `CometChatConversations` show the message without any extra code. Don't publish `ui:message/sent` again yourself for the same send. + -```tsx -const publish = usePublishEvent(); -const msg = await CometChatUIKit.sendTextMessage(message); -publish({ type: "ui:message/sent", message: msg, status: CometChatMessageStatus.success }); -``` - +With [offline support](/ui-kit/react/offline-support) on, the returned Promise resolves when the message is actually sent. A message the SDK queues while offline does not reject it. A logout, a user switch or a cache reset that lost (or may have lost) unsent messages before it is sent rejects the Promise with the code `ERROR_OFFLINE_MESSAGE_DISCARDED`. See [Send promises](/ui-kit/react/offline-support#send-promises). ### `CometChatUIKit.sendTextMessage(message)` diff --git a/ui-kit/react/offline-support.mdx b/ui-kit/react/offline-support.mdx new file mode 100644 index 000000000..13f5c978c --- /dev/null +++ b/ui-kit/react/offline-support.mdx @@ -0,0 +1,403 @@ +--- +title: "Offline Support" +sidebarTitle: "Offline Support" +description: "Show saved chats and messages without a network, queue sends until the connection returns, and customize the offline states of the CometChat React UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react` 7.3.0 or later, with `@cometchat/chat-sdk-javascript` 4.3.0 or later | +| Default | **Off.** Nothing changes until you call `setOfflineConfig()` with `enabled: true` | +| Enable | `new UIKitSettingsBuilder()...setOfflineConfig({ enabled: true }).build()`, then `CometChatUIKit.init(settings)` | +| Config | Passed to the SDK's `AppSettingsBuilder.setOfflineConfig()` unchanged. Options: [Configuration & API Reference](/sdk/javascript/offline-reference#offlineconfig-options) | +| Runtime check | `CometChat.isOfflineEnabled()` from `@cometchat/chat-sdk-javascript` | +| Props | `hideOfflineNotices` on `CometChatMessageList` and `CometChatConversations` (default `false`) | +| Events | `ui:message/send-state-changed`, `ui:offline/cache-reset` via `useCometChatEvents` | +| Send promise | `CometChatUIKit.sendTextMessage` / `sendMediaMessage` / `sendCustomMessage` resolve when sent; a logout, user switch, or cache reset that lost (or may have lost) unsent messages rejects with code `ERROR_OFFLINE_MESSAGE_DISCARDED` | +| Styling | `--cometchat-message-bubble-offline-*`, `--cometchat-message-list-offline-*`, `--cometchat-conversations-offline-*`, `--cometchat-offline-media-unavailable-*` CSS variables | + + + +With offline support turned on, the React UI Kit keeps working when the network drops. Chats and messages the user has already opened load from a cache on the device at once, messages sent while offline wait in a queue and go out when the connection returns, and every list says plainly when something needs a connection. + +The UI Kit builds on [offline support in the JavaScript SDK](/sdk/javascript/offline-overview). You turn it on once in `UIKitSettings`; the components handle the rest. + +## Overview + +**Works offline** + +- Conversations, users, groups, group members, messages, reactions, notifications, and pinned and saved messages the user has already loaded appear straight away from the cache. +- Text messages, stickers and custom messages the user sends are queued and sent automatically on reconnect. +- Media that was downloaded while online is shown from the device. +- When the connection returns, the SDK catches up on what was missed and the lists update in place. + +**Needs a connection** + +- Anything the user has never opened while online, for example the first load of a chat or a list. +- Keyword search with no saved match, and keyword search in the Search component. +- Edits, deletes, reactions and other actions on messages that are already sent. They are not queued. (Retry and Delete on a message that is not sent yet work offline.) +- Calls, call logs, message information and AI features such as streamed replies. +- Attachments (images, video, audio, files and voice notes) picked while offline are not guaranteed to send, so don't rely on them being queued. Send them when connected. + +## Requirements + +| Requirement | Version | +| --- | --- | +| React UI Kit | `@cometchat/chat-uikit-react` **7.3.0** or later | +| JavaScript Chat SDK | `@cometchat/chat-sdk-javascript` **4.3.0** or later | +| React | 18 or later (the UI Kit's peer range is `>=18.0.0 <21.0.0`) | + +The UI Kit's peer dependency on the Chat SDK stays `^4.2.0`, so upgrading the UI Kit does not force an SDK upgrade. On an SDK older than 4.3.0, `setOfflineConfig()` has no effect and the UI Kit works online as before. Install 4.3.0 or later to use offline support: + +```bash +npm install @cometchat/chat-uikit-react@^7.3.0 @cometchat/chat-sdk-javascript@^4.3.0 +``` + +Offline support is for UI Kit v7 only. UI Kit v6 and earlier have no offline UI, and turning on the SDK's offline support with them is not supported. + +For the browsers and storage the SDK uses for its cache, see [Supported runtimes](/sdk/javascript/offline-enable#supported-runtimes). + +## Enable Offline Support + +Offline support is **off by default**. Call `setOfflineConfig()` on the `UIKitSettingsBuilder` before `CometChatUIKit.init()`, and set `enabled: true`. + +```tsx title="src/main.tsx" +import ReactDOM from "react-dom/client"; +import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react"; +import App from "./App"; + +const settings = new UIKitSettingsBuilder() + .setAppId("APP_ID") + .setRegion("REGION") + .setAuthKey("AUTH_KEY") + .subscribePresenceForAllUsers() + .setOfflineConfig({ + enabled: true, + // Optional. Every other key has a default in the SDK, for example: + // maxPendingMessages: 50, + // mediaCaching: "AUTO", + // encryption: false, + }) + .build(); + +CometChatUIKit.init(settings).then(async () => { + await CometChatUIKit.login("cometchat-uid-1"); + ReactDOM.createRoot(document.getElementById("root")!).render(); +}); +``` + +The UI Kit passes the object to the SDK's `AppSettingsBuilder.setOfflineConfig()` unchanged. Its type, `CometChatOfflineConfig`, is exported from `@cometchat/chat-uikit-react` and lists the same keys as the SDK's `OfflineConfig`, so a misspelled key is a compile error. For what each key does and its default (cache size, outbox size, media caching, encryption and so on), see [OfflineConfig options](/sdk/javascript/offline-reference#offlineconfig-options). + + +Offline turns on only for an explicit `enabled: true`. If you don't call `setOfflineConfig()`, or pass a config without `enabled: true`, the UI Kit behaves exactly as it does today. + + +Whether offline support is actually running can change after init. For example, it is off before anyone logs in, and when the encrypted cache cannot open. To check it in your own code, call `CometChat.isOfflineEnabled()` at the moment you need the answer rather than reading back the config you passed. See [Verify it is active](/sdk/javascript/offline-enable). + +## How the Components Behave Offline + +### 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), [Reaction List](/ui-kit/react/components/reaction-list), [Notification Feed](/ui-kit/react/components/notification-feed), [Pinned Messages](/ui-kit/react/components/pinned-messages) and [Saved Messages](/ui-kit/react/components/saved-messages) all load in two steps: + +1. The saved rows paint first, from the cache. +2. The server's page then replaces them in place when it arrives. + +When a load can't reach the server: + +| Situation | What the list shows | `onError` | +| --- | --- | --- | +| Rows are on screen, offline | The rows stay. No error view. | Not called | +| Nothing on screen, offline | An icon and "Connect to load chats" (or users, groups, members, messages, reactions, notifications), with no Retry button. The list loads again once by itself on reconnect. | Called once | +| Nothing on screen, offline, keyword search | "Connect to search" with a second line, "Search needs an internet connection." The search runs again once on reconnect. | Not called | +| Nothing on screen, online, a real error | The usual error view. It does not reload by itself. | Called | +| The server answered with nothing | The usual empty view | Not called | + +Pinned Messages and Saved Messages have no `onError` prop; the `onError` column applies to the other lists. + +A list opened with only a filter (for example online users only, tags, or a request builder with no keyword) is a plain list, not a search. Offline with nothing saved, it says "Connect to load …", never "Connect to search". + +While the Reaction List shows "Connect to load reactions", its tabs still show the message's own counts ("All" and one tab per emoji). The reactors fill in once the list can load. + +If you pass your own `errorView` (or `emptyView` for a keyword search), your view is shown instead of the offline state. See [Customization](#customization). + +### Search + +The [Search](/ui-kit/react/components/search) component needs a connection for keyword search: + +- Offline, with nothing shown, a keyword search shows "Connect to search" and "Search needs an internet connection." +- A search by filter alone is answered from the device. With nothing saved it shows the plain "No results" state, with no `onError`. +- When both conversation and message results fail and at least one failure is a real error (not a lost connection), the error view shows and `onError` is called. + +### Message list and threads + +- A chat opens with its cached messages, then the server's page merges in. +- A chat opened offline with nothing saved shows "Connect to load messages". It is read again once when the connection returns. +- At an edge the cache can't fill (older history, or newer messages after jumping to a message), the list shows a "Connect to load more" row. The row is a button, and it also loads by itself once when the connection returns. +- Jumping to a message (from a search result, a quoted reply or the first unread message) works offline when that message is saved. If it isn't, a jump inside an open chat leaves the messages on screen as they are; only an error other than a lost connection calls `onError`. A chat that opens at a message that isn't saved opens on its newest saved messages instead. +- After a long outage the catch-up may bring more than a page of new messages. While the user is reading older messages, a **Jump to latest** button appears instead of moving the list. + + +The default message list asks the server for pages in the form the SDK caches, then applies its message types, categories and hide-deleted setting on the device. If you pass your own `messagesRequestBuilder`, it is sent as you built it, and its pages are cached only when `hideReplies` is its only content filter. + + +### Composer and sending + +- A message sent while offline appears in the list at once with a clock icon and the label "Not sent yet". It is sent automatically when the connection returns, and its receipt then updates as usual. +- A message that fails shows an error mark and a **Not sent. Tap to retry** button under the bubble. The failed state survives a page reload. +- The message menu of an unsent or failed message offers only **Retry** and **Delete**. Actions that need a server copy (reply, edit, react and so on) are hidden until it is sent. **Delete** removes the message from this device. It is hidden when `hideDeleteMessageOption` is set. If the device no longer holds the message (for example after the user left the group), Retry and Delete remove it from the list. If it was in fact already sent, Retry leaves the row as it is, and Delete deletes the sent message as usual, which needs a connection. +- Retry or Delete on a message whose send is already under way changes nothing and shows "Sending… try again in a moment". +- If the outbox is full, the send is refused and the list shows "Too many messages waiting to send". Some sends are refused while offline with "File too large to send offline". See [Queue limits](/sdk/javascript/offline-send#queue-limits). +- Stickers and the group call message are queued like any other send. + +### Media + +With media caching on (the SDK default), images, videos, audio and files that were downloaded while online are shown from the device. A media bubble whose file is not saved shows "Available when online" while the device is offline. Tapping it asks the SDK to download the file, and the bubble updates once it is saved. See [Media Caching](/sdk/javascript/offline-media-caching). + +### Edits, deletes and reactions + +These are not queued. They are sent as soon as the user acts, and they fail if there is no connection: + +- **Reactions** show at once, then roll back and call the message list's `onError` if the request fails. +- **Deleting** a sent message calls `onError` if it fails, and the message stays. +- **Editing** a message: the composer clears and leaves edit mode when the user sends the edit. If the edit fails, the message keeps its old text and the message composer's `onError` is called. + +See [Edits, Deletes, and Reactions Need a Connection](/sdk/javascript/offline-send#edits-deletes-and-reactions-need-a-connection). + +### Presence + +While the SDK is disconnected, nobody shows as online: there is no online dot in any list or header, the header of a one-to-one chat shows no "Online" subtitle, and the header of a one-to-one or group chat shows no typing indicator. Screen readers are told the same. Presence comes back after the reconnect. + +### Logout, user switch and cache reset + +The cache is per user. A logout or a switch to another user clears every list on screen, and the SDK deletes that user's cached data and queued messages. + +If the SDK has to wipe and rebuild its cache (for example when the encryption key is lost), every mounted list reloads. If unsent messages were lost, a notice such as "2 unsent messages couldn't be recovered" appears once, in the Conversations list or the open Message List. See [When the cache resets](/sdk/javascript/offline-sync#when-the-cache-resets). + +## Offline States and Texts + +Override any of them with [custom translations](/ui-kit/react/localization#adding-custom-translations). + +| Text (en-US) | Where it appears | Localization key | +| --- | --- | --- | +| Connect to load chats | Conversations, offline with nothing saved | `conversations_connect_to_load` | +| Connect to load users | Users | `users_connect_to_load` | +| Connect to load groups | Groups | `groups_connect_to_load` | +| Connect to load members | Group Members | `group_members_connect_to_load` | +| Connect to load messages | Message List, Pinned Messages, Saved Messages | `message_list_connect_to_load` | +| Connect to load reactions | Reaction List | `reaction_list_connect_to_load` | +| Connect to load notifications | Notification Feed | `notifications_connect_to_load` | +| Connect to search | Conversations, Users, Groups, Group Members: keyword search offline | `search_connect_to_search` | +| Connect to search | Search component | `search_connect_to_search_messages` | +| Search needs an internet connection. | Second line under "Connect to search" | `search_connect_to_search_subtitle` | +| Connect to load more | Message List edge row (older messages) | `message_list_connect_to_load_more` | +| Connect to load more | Message List edge row (newer messages) | `message_list_connect_to_load_newer` | +| Jump to latest | Message List, after a large catch-up | `message_list_jump_to_latest` | +| Not sent yet | Label of a queued message's clock icon | `message_list_not_sent_yet` | +| Not sent. Tap to retry | Button and label on a failed message | `message_list_not_sent_tap_to_retry` | +| Available when online | Media bubble whose file is not saved | `message_bubble_media_available_when_online` | +| Too many messages waiting to send | Message List notice | `message_list_queue_full` | +| File too large to send offline | Message List notice when a send is refused | `message_list_file_too_large_offline` | +| Sending… try again in a moment | Message List notice | `message_list_send_in_flight` | +| Couldn't remove the message | Error toast when **Delete** on an unsent message fails | `message_list_option_delete_failed` | +| 1 unsent message was removed | Message List notice | `message_list_unsent_message_removed` | +| `{{count}}` message(s) weren't sent | Message List notice | `message_list_messages_not_sent_one`, `message_list_messages_not_sent_other` | +| `{{count}}` unsent message(s) couldn't be recovered | Conversations or Message List notice after a cache reset | `message_list_unsent_messages_lost_one`, `message_list_unsent_messages_lost_other` | +| Some unsent messages may not have been sent | Conversations or Message List notice after a cache reset | `message_list_unsent_messages_maybe_lost` | + +Count texts have plural forms: the UI Kit picks `_one`, `_other` (and `_few` / `_many` where a language needs them) for the current language, and replaces `{{count}}` with the number. + +```tsx +import { CometChatLocalize } from "@cometchat/chat-uikit-react"; + +const localize = CometChatLocalize.getSharedInstance(); +localize?.addTranslation({ + "en-us": { + conversations_connect_to_load: "You're offline. Chats will load when you reconnect.", + message_list_not_sent_yet: "Waiting for network", + }, +}); +``` + +## Errors and Callbacks + +### `onError` + +- **Rows on screen:** offline, a failed load is silent (no error view, no `onError`). A real error calls `onError` once when the user or your app started the load (opening the list, refreshing, searching, paging), and stays silent when the UI Kit started it (reconnect, coming back to the foreground, sync). +- **Nothing on screen:** see the [Lists](#lists) table. +- **Actions:** a failed reaction, delete or edit calls `onError`, as above. + +### Send promises + +`CometChatUIKit.sendTextMessage()`, `sendMediaMessage()` and `sendCustomMessage()` answer every send: + +- Queueing a message does not reject the promise. It resolves when the message is sent, and rejects once if the message fails or is removed before it is sent. A later **Retry** does not answer the same promise again. +- A logout or user switch, or a cache reset that lost (or may have lost) unsent messages, rejects the promise with an error whose `code` is `ERROR_OFFLINE_MESSAGE_DISCARDED`. A message removed later for another reason, for example the user's own **Delete**, rejects with its failure reason as the `code` (`DISCARDED`). +- The UI Kit shows nothing for an `ERROR_OFFLINE_MESSAGE_DISCARDED` rejection: no error toast, no `onError`, and the composer does not lock. Only your own `.catch` hears of it. + +```tsx +import { CometChat } from "@cometchat/chat-sdk-javascript"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react"; + +const message = new CometChat.TextMessage("cometchat-uid-2", "Hello!", CometChat.RECEIVER_TYPE.USER); + +CometChatUIKit.sendTextMessage(message) + .then((sent) => console.log("Sent", sent.getId())) + .catch((error) => { + if (error?.code === "ERROR_OFFLINE_MESSAGE_DISCARDED") { + // Logged out, switched user or cache reset before it could send. + return; + } + console.error("Send failed", error); + }); +``` + +With offline off, these methods behave as before. + +### Events + +Two UI events are added to the [event system](/ui-kit/react/event-system). Both fire only with offline support on. + +| Event | Payload | When | +| --- | --- | --- | +| `ui:message/send-state-changed` | `{ message, state, reason? }` | An own message's send state changed. `state` is a `CometChatMessageSendState`: `"sending"` (queued or in flight), `"sent"`, `"failed"` (Retry offered) or `"discarded"` (removed before it was sent). `reason` is the SDK's `MessageFailureReason` for `failed` and `discarded`. Fired once per change per message. | +| `ui:offline/cache-reset` | `{ reason, pendingMessagesLost }` | The SDK wiped and rebuilt its cache. Every mounted list reloads. `pendingMessagesLost` is the number of unsent messages that could not be kept, or `null` when unknown. | + +`ui:message/sent` keeps its meaning and still fires for each send. + +```tsx +import { useCometChatEvents } from "@cometchat/chat-uikit-react"; + +function OfflineSendTracker() { + useCometChatEvents((event) => { + switch (event.type) { + case "ui:message/send-state-changed": + console.log(event.message.getMuid(), event.state, event.reason); + break; + case "ui:offline/cache-reset": + console.log("Cache reset", event.reason, event.pendingMessagesLost); + break; + default: + break; + } + }, []); + + return null; +} +``` + + +These events are new members of the exported `CometChatEvent` union. If your TypeScript code has an exhaustive `switch` on `event.type` with no `default`, add one. + + +## Customization + +### Hide the offline notices + +| Component | Prop | Default | Hides | +| --- | --- | --- | --- | +| [Message List](/ui-kit/react/components/message-list) | `hideOfflineNotices` | `false` | The notices about unsent messages: removed, not sent, lost in a cache reset, outbox full, send refused, send under way | +| [Conversations](/ui-kit/react/components/conversations) | `hideOfflineNotices` | `false` | The notice shown after a cache reset lost, or may have lost, unsent messages | + +```tsx + + +``` + +### Use your own offline view + +The lists show your own `errorView` instead of "Connect to load …", and your own `emptyView` instead of "Connect to search". To tell the offline state apart inside your view, read `connectToLoad` or `connectToSearch` from the component's context hook. They are `true` only while the offline state is shown, and never set with offline off. + +| Context hook | `connectToLoad` | `connectToSearch` | +| --- | --- | --- | +| `useCometChatConversationsContext` | Yes | Yes | +| `useCometChatUsersContext` | Yes | Yes | +| `useCometChatGroupsContext` | Yes | Yes | +| `useCometChatGroupMembersContext` | Yes | Yes | +| `useCometChatReactionListContext` | Yes | No | +| `useCometChatNotificationFeedContext` | Yes | No | +| `useCometChatPinnedMessagesContext` | Yes | No | +| `useCometChatSavedMessagesContext` | Yes | No | +| `useCometChatMessageListContext` (as `state.connectToLoad`) | Yes | No | + +The [Search](/ui-kit/react/components/search) component's context does not expose these flags. + +### Style the offline UI + +Each variable falls back to the UI Kit's current theme value, so set only what you want to change. See [Theming](/ui-kit/react/theming). + +| CSS variable | Styles | Falls back to | +| --- | --- | --- | +| `--cometchat-message-bubble-offline-retry-color` | "Not sent. Tap to retry" text | `--cometchat-error-color` | +| `--cometchat-message-bubble-offline-retry-font` | "Not sent. Tap to retry" font | `--cometchat-font-caption1-regular` | +| `--cometchat-message-bubble-offline-retry-focus-outline-color` | Focus ring of the retry button | `--cometchat-primary-color` | +| `--cometchat-message-bubble-offline-failed-icon-color` | Error mark on a failed message | `--cometchat-error-color` | +| `--cometchat-message-bubble-offline-failed-tint` | Background of a failed message's row | `transparent` | +| `--cometchat-message-list-offline-footer-color` | "Connect to load more" text | `--cometchat-text-color-highlight` | +| `--cometchat-message-list-offline-footer-font` | "Connect to load more" font | `--cometchat-font-caption1-regular` | +| `--cometchat-message-list-offline-notice-background` | Message List notice background | `--cometchat-neutral-color-300` | +| `--cometchat-message-list-offline-notice-color` | Message List notice text | `--cometchat-text-color-secondary` | +| `--cometchat-message-list-offline-notice-font` | Message List notice font | `--cometchat-font-caption1-regular` | +| `--cometchat-conversations-offline-notice-background` | Conversations notice background | `--cometchat-neutral-color-300` | +| `--cometchat-conversations-offline-notice-color` | Conversations notice text | `--cometchat-text-color-secondary` | +| `--cometchat-conversations-offline-notice-font` | Conversations notice font | `--cometchat-font-caption1-regular` | +| `--cometchat-offline-media-unavailable-background` | "Available when online" background | `--cometchat-neutral-color-300` | +| `--cometchat-offline-media-unavailable-color` | "Available when online" text | `--cometchat-text-color-secondary` | +| `--cometchat-offline-media-unavailable-font` | "Available when online" font | `--cometchat-font-caption1-regular` | + +```css +.cometchat { + --cometchat-message-bubble-offline-failed-tint: rgba(244, 70, 73, 0.06); + --cometchat-message-list-offline-footer-color: #6852d6; +} +``` + +## With Offline Support Turned Off + +Apps that don't call `setOfflineConfig()` get no offline UI, no offline events and no change to how sends work. A few fixes in the same release do change what every app sees: + +- A message list that is empty when the connection returns now loads again and shows its empty state, instead of staying blank. +- A reconnect while the newest message is still unsent now fetches the messages missed during the outage. +- Paging past a conversation that just received a message no longer shows it twice. +- A `messagesRequestBuilder` you pass to `CometChatMessageList` or `CometChatSavedMessages` is no longer modified. +- Saved Messages rows are no longer announced to screen readers as selectable options. +- Message rows, conversation rows, notices, the composer input and the empty and error views carry new `data-cc` attributes for test automation. Existing `data-testid` and `data-message-id` attributes are kept, but DOM snapshot tests may change. + +## Limitations and Known Issues + +- **Only what was loaded online is saved.** A user who has never opened a chat or list while online has nothing to show offline. +- **Thread replies opened online are not saved for offline.** Replies sent or received on this device are saved. +- **A lost send acknowledgement can create one duplicate** of that message on the server. +- **Missed messages can take up to about 10 seconds** to appear after a quick reconnect. +- **After a page reload, a failed message's reason may be unknown.** It is still offered Retry. +- **A chat can stall while online** if a send got no answer while connected. It resumes at the next reconnect. +- **Multiple tabs:** a cache rebuild in one tab can discard another tab's unsent messages. That tab's rows update to match. +- **Need a connection:** keyword search, message information, call logs and AI streamed replies. Call logs have no saved copy and keep their own error view. +- **Encryption in the browser** covers the cached content but not its lookup metadata, and downloaded media is stored unencrypted. See [Encrypt the Cache](/sdk/javascript/offline-encryption). + +--- + +## Next Steps + + + + How the cache, outbox and catch-up sync work + + + Every `OfflineConfig` option, listener and error code + + + Queued sends, retry, discard and queue limits + + + Subscribe to UI Kit events with `useCometChatEvents` + + + Override the offline texts + + + See how the components power each chat feature + + diff --git a/ui-kit/react/overview.mdx b/ui-kit/react/overview.mdx index 0e05a1456..7b23d71f5 100644 --- a/ui-kit/react/overview.mdx +++ b/ui-kit/react/overview.mdx @@ -67,6 +67,7 @@ Pick your framework and follow the step-by-step integration guide: - **Theming** — CSS custom properties (`--cometchat-*`) with built-in light and dark themes - **Localization** — 19 supported languages with customizable translation keys - **Calling** — optional voice and video calling via `@cometchat/calls-sdk-javascript` +- **Offline support** — optional, off by default: saved chats and messages without a network, and queued sends. Needs UI Kit 7.3.0 and `@cometchat/chat-sdk-javascript` 4.3.0 or later. See [Offline Support](/ui-kit/react/offline-support) - **SSR-safe** — no browser-only APIs at module scope; Next.js App Router compatible - **Tree-shakeable** — ESM-first build with dual ESM + CJS output