From 072c6e94306c612d365402e9e9f357d340539c98 Mon Sep 17 00:00:00 2001 From: Aditya Date: Tue, 10 Feb 2026 17:55:54 +0530 Subject: [PATCH 001/106] improve call-logs, call-features, ai-features, ai-assistant-chat-history --- ui-kit/ios/ai-assistant-chat-history.mdx | 940 +++++++++++++++-------- ui-kit/ios/ai-features.mdx | 488 +++++++++++- ui-kit/ios/call-features.mdx | 641 ++++++++++++++-- 3 files changed, 1663 insertions(+), 406 deletions(-) diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index cc24e42a4..5e2b7243d 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -1,424 +1,728 @@ --- title: "AI Assistant Chat History" +sidebarTitle: "AI Assistant Chat History" +description: "Complete guide to displaying AI assistant conversation history in iOS apps - production-ready code included" --- ## Overview -The `AI Assistant Chat History` component is a pre-built user interface component designed to display the conversation history between users and an AI assistant within a chat application. It provides a structured and visually appealing way to present past interactions, making it easy for users to review previous messages and context. +`CometChatAIAssistanceChatHistory` displays past conversations between users and AI assistants. Users can review previous AI interactions and start new conversations. -## Usage - -### Integration - -##### Using Navigation Controller to Present `CometChatAIAssistantChatHistory` +--- -The `CometChatAIAssistanceChatHistory` component can be launched using a navigation controller. -This approach is ideal when you want to present the chat history as a standalone screen within your app’s navigation flow +## Prerequisites - - -```swift -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. -self.navigationController?.pushViewController(chatHistory, animated: true) + + +Add to your Podfile: +```ruby +pod 'CometChatUIKitSwift', '5.1.7' ``` - - - - - -Simply adding the CometChatAIAssistanceChatHistory component to your view hierarchy without providing a User or Group object will only display a loading indicator. -To fetch and display actual messages, you must assign either a User or a Group object to the component. +Run `pod install` + - - -*** - - -### Actions - -[Actions](/ui-kit/ios/components-overview#actions) define how a component behaves and responds to user interactions. + +Go to [CometChat Dashboard](https://app.cometchat.com) → AI → Enable AI features + -##### onNewChatButtonClicked - -`onNewChatButtonClicked` The `onNewChatButtonClicked` action is triggered when the user taps on the “New Chat” button. -You can override it to define custom functionality, such as navigating to a new chat creation screen or initiating a new AI chat session. - - - + ```swift -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. - -chatHistory.onNewChatButtonClicked = { - // TODO: Implement custom behavior here +import CometChatUIKitSwift + +let uikitSettings = UIKitSettings() + .set(appID: "YOUR_APP_ID") + .set(authKey: "YOUR_AUTH_KEY") + .set(region: "YOUR_REGION") + .build() + +CometChatUIKit.init(uiKitSettings: uikitSettings) { result in + switch result { + case .success: + CometChatUIKit.login(uid: "USER_ID") { _ in } + case .failure(let error): + print(error.localizedDescription) + } } ``` + + - - - - -*** - -##### onMessageClicked +--- -You can customize this behavior by using the provided code snippet to override the onMessageClicked callback. -This allows you to define custom actions when a user taps on a message inside the AI Assistant Chat History component. +## Basic Implementation - + ```swift -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. -chatHistory.onMessageClicked = { message in -// TODO: Implement custom behavior when a message is clicked +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ViewController: UIViewController { + + var user: CometChat.User! + + func showAIChatHistory() { + let chatHistory = CometChatAIAssistanceChatHistory() + chatHistory.user = user // Required! + + navigationController?.pushViewController(chatHistory, animated: true) + } } ``` - - -*** - -##### onError - -You can customize this behavior by overriding the `onError` callback to improve error handling within the component. -This is useful for displaying custom error messages or performing recovery actions when data fetching fails. - - - -```swift -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. - -chatHistory.set(onError: { error in - // Override on error -}) -``` - - + +You **must** set either `user` or `group`. Without this, only a loading indicator will display. + - +--- -##### onLoad +## Production-Ready Implementation -The `onLoad` callback is invoked when the message list is successfully fetched and loaded. -This can be used to track component readiness or perform actions once messages are displayed. +Complete implementation with all features: - + ```swift -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. - -chatHistory.set(onLoad: { history in - // Handle loaded ai chat history -}) +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class AIAssistantViewController: UIViewController { + + // MARK: - Properties + private var user: CometChat.User! + private var chatHistoryComponent: CometChatAIAssistanceChatHistory! + + // MARK: - Initialization + convenience init(user: CometChat.User) { + self.init() + self.user = user + } + + // MARK: - Lifecycle + override func viewDidLoad() { + super.viewDidLoad() + setupChatHistory() + } + + // MARK: - Setup + private func setupChatHistory() { + chatHistoryComponent = CometChatAIAssistanceChatHistory() + chatHistoryComponent.user = user + + // Configure callbacks + setupCallbacks() + + // Configure styling + setupStyling() + + // Configure date formatting + setupDateFormatting() + + // Configure empty/error states + setupStateViews() + + // Present + navigationController?.pushViewController(chatHistoryComponent, animated: true) + } + + // MARK: - Callbacks + private func setupCallbacks() { + // New chat button tapped + chatHistoryComponent.onNewChatButtonClicked = { [weak self] in + self?.startNewAIChat() + } + + // Message tapped + chatHistoryComponent.onMessageClicked = { [weak self] message in + self?.handleMessageTap(message) + } + + // Data loaded successfully + chatHistoryComponent.set(onLoad: { messages in + print("✅ Loaded \(messages.count) AI messages") + }) + + // No data available + chatHistoryComponent.set(onEmpty: { [weak self] in + print("📭 No AI chat history") + }) + + // Error occurred + chatHistoryComponent.set(onError: { [weak self] error in + self?.showError(error.localizedDescription) + }) + } + + // MARK: - Styling + private func setupStyling() { + let style = AiAssistantChatHistoryStyle() + + // Background + style.backgroundColor = .systemBackground + + // Item text + style.itemTextFont = UIFont.systemFont(ofSize: 16, weight: .medium) + style.itemTextColor = .label + + // New chat button + style.newChatTitleFont = UIFont.systemFont(ofSize: 18, weight: .bold) + style.newChatTitleColor = .systemBlue + + chatHistoryComponent.style = style + } + + // MARK: - Date Formatting + private func setupDateFormatting() { + // Today's messages + chatHistoryComponent.dateTimeFormatter.today = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.timeStyle = .short + return "Today at \(formatter.string(from: date))" + } + + // Yesterday's messages + chatHistoryComponent.dateTimeFormatter.yesterday = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.timeStyle = .short + return "Yesterday at \(formatter.string(from: date))" + } + + // Older messages + chatHistoryComponent.dateTimeFormatter.otherDay = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "MMM d, yyyy 'at' h:mm a" + return formatter.string(from: date) + } + } + + // MARK: - State Views + private func setupStateViews() { + // Empty state text + chatHistoryComponent.emptyStateText = "No AI conversations yet" + chatHistoryComponent.emptyStateSubtitleText = "Tap 'New Chat' to start talking with AI" + + // Error state text + chatHistoryComponent.errorStateText = "Couldn't load history" + chatHistoryComponent.errorStateSubtitleText = "Please check your connection and try again" + } + + // MARK: - Actions + private func startNewAIChat() { + // Option 1: Open messages view for new AI chat + let messagesVC = CometChatMessages() + messagesVC.user = user + navigationController?.pushViewController(messagesVC, animated: true) + + // Option 2: Show action sheet with options + // showNewChatOptions() + } + + private func handleMessageTap(_ message: BaseMessage) { + print("Tapped message ID: \(message.id)") + print("Message text: \(message.text ?? "No text")") + + // Show message details or continue conversation + let alert = UIAlertController( + title: "Message", + message: message.text, + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "Continue Chat", style: .default) { [weak self] _ in + self?.continueChat(from: message) + }) + alert.addAction(UIAlertAction(title: "Close", style: .cancel)) + present(alert, animated: true) + } + + private func continueChat(from message: BaseMessage) { + let messagesVC = CometChatMessages() + messagesVC.user = user + navigationController?.pushViewController(messagesVC, animated: true) + } + + private func showError(_ message: String) { + let alert = UIAlertController( + title: "Error", + message: message, + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "Retry", style: .default) { [weak self] _ in + self?.setupChatHistory() + }) + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + present(alert, animated: true) + } +} ``` - - -*** +--- -##### onEmpty +## Custom Views -The `onEmpty` callback is triggered when no messages are available. -You can use this to show placeholder content, such as an empty state message or an illustration. +### Custom Loading View - + ```swift let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. +chatHistory.user = user -chatHistory.set(onEmpty: { - // Handle empty state -}) -``` +// Custom loading indicator +let loadingView = UIActivityIndicatorView(style: .large) +loadingView.color = .systemBlue +loadingView.startAnimating() +chatHistory.set(loadingView: loadingView) +``` - -*** - -### Filters - -You can customize the message list displayed in the `CometChatAIAssistanceChatHistory` component by modifying the `MessagesRequestBuilder`. -This allows you to filter messages according to your app’s needs — for example, fetching messages that match a search term or belong to a specific user or group. - -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed +### Custom Empty State View - + ```swift -swift let builder = MessagesRequest.MessageRequestBuilder() - .set(uid: user.uid) // Example: filter messages by user UID +import UIKit +import CometChatUIKitSwift + +class CustomEmptyView: UIView { + + private let imageView: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(systemName: "sparkles") + iv.tintColor = .systemBlue + iv.contentMode = .scaleAspectFit + iv.translatesAutoresizingMaskIntoConstraints = false + return iv + }() + + private let titleLabel: UILabel = { + let label = UILabel() + label.text = "No AI Conversations" + label.font = .systemFont(ofSize: 20, weight: .bold) + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + private let subtitleLabel: UILabel = { + let label = UILabel() + label.text = "Start a conversation with AI to see it here" + label.font = .systemFont(ofSize: 16) + label.textColor = .secondaryLabel + label.textAlignment = .center + label.numberOfLines = 0 + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + let startChatButton: UIButton = { + let button = UIButton(type: .system) + button.setTitle("Start New Chat", for: .normal) + button.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold) + button.backgroundColor = .systemBlue + button.setTitleColor(.white, for: .normal) + button.layer.cornerRadius = 12 + button.translatesAutoresizingMaskIntoConstraints = false + return button + }() + + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setupUI() { + addSubview(imageView) + addSubview(titleLabel) + addSubview(subtitleLabel) + addSubview(startChatButton) + + NSLayoutConstraint.activate([ + imageView.centerXAnchor.constraint(equalTo: centerXAnchor), + imageView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -80), + imageView.widthAnchor.constraint(equalToConstant: 80), + imageView.heightAnchor.constraint(equalToConstant: 80), + + titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 24), + titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 32), + titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -32), + + subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8), + subtitleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 32), + subtitleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -32), + + startChatButton.topAnchor.constraint(equalTo: subtitleLabel.bottomAnchor, constant: 24), + startChatButton.centerXAnchor.constraint(equalTo: centerXAnchor), + startChatButton.widthAnchor.constraint(equalToConstant: 180), + startChatButton.heightAnchor.constraint(equalToConstant: 48) + ]) + } +} +// Usage let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. -chatHistory.set(messagesRequestBuilder: builder) -``` - - - - - - - -The following parameters in `messagesRequestBuilder` will always be modified internally by the component: - -1. `uid` -2. `guid` -3. `types` -4. `categories` - - - -*** - -### Events - -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Component`. - -By using events, you can extend existing functionality. Since events are global in nature, they can be added or removed from multiple locations within the app. -The CometChatAIAssistanceChatHistory component does not emit any events of its own. - -*** +chatHistory.user = user -## Customization +let emptyView = CustomEmptyView() +emptyView.startChatButton.addTarget(self, action: #selector(startNewChat), for: .touchUpInside) -To meet your app’s design and UX requirements, you can customize the appearance and functionality of the `CometChatAIAssistanceChatHistory` component. -We provide multiple exposed properties and methods that allow you to modify both the visual style and interactive behavior according to your needs. - -### Style - -The style property allows you to customize the look and feel of the component in your app. -These parameters control key design aspects such as colors, fonts, text styles, and background appearance for various subviews like headers, date separators, and message items - -##### 1. AiAssistantChatHistoryStyle - -You can assign a custom `AiAssistantChatHistoryStyle` to the component to override the default visual theme. - -**Global level styling** - - - -```swift -CometChatAIAssistanceChatHistory.style.backgroundColor = -CometChatAIAssistanceChatHistory.style.itemTextFont = -CometChatAIAssistanceChatHistory.style.newChatTitleFont = +chatHistory.set(emptyView: emptyView) ``` - - -**Instance level styling** +### Custom Error State View ```swift -let aiAssistantChatHistoryStyle = AiAssistantChatHistoryStyle() -aiAssistantChatHistoryStyle.backgroundColor = -aiAssistantChatHistoryStyle.itemTextFont = -aiAssistantChatHistoryStyle.newChatTitleFont = - -let aIAssistanceChatHistory = CometChatAIAssistanceChatHistory() -aIAssistanceChatHistory.style = aiAssistantChatHistoryStyle -``` - - - - - - - - - -*** +import UIKit +import CometChatUIKitSwift + +class CustomErrorView: UIView { + + private let iconView: UIImageView = { + let iv = UIImageView() + iv.image = UIImage(systemName: "exclamationmark.triangle") + iv.tintColor = .systemRed + iv.contentMode = .scaleAspectFit + iv.translatesAutoresizingMaskIntoConstraints = false + return iv + }() + + private let titleLabel: UILabel = { + let label = UILabel() + label.text = "Something went wrong" + label.font = .systemFont(ofSize: 18, weight: .semibold) + label.textAlignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + private let messageLabel: UILabel = { + let label = UILabel() + label.text = "We couldn't load your AI chat history.\nPlease check your connection." + label.font = .systemFont(ofSize: 14) + label.textColor = .secondaryLabel + label.textAlignment = .center + label.numberOfLines = 0 + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + let retryButton: UIButton = { + let button = UIButton(type: .system) + button.setTitle("Try Again", for: .normal) + button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) + button.backgroundColor = .systemBlue + button.setTitleColor(.white, for: .normal) + button.layer.cornerRadius = 10 + button.translatesAutoresizingMaskIntoConstraints = false + return button + }() + + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + private func setupUI() { + addSubview(iconView) + addSubview(titleLabel) + addSubview(messageLabel) + addSubview(retryButton) + + NSLayoutConstraint.activate([ + iconView.centerXAnchor.constraint(equalTo: centerXAnchor), + iconView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -60), + iconView.widthAnchor.constraint(equalToConstant: 60), + iconView.heightAnchor.constraint(equalToConstant: 60), + + titleLabel.topAnchor.constraint(equalTo: iconView.bottomAnchor, constant: 16), + titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 24), + titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -24), + + messageLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 8), + messageLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 24), + messageLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -24), + + retryButton.topAnchor.constraint(equalTo: messageLabel.bottomAnchor, constant: 20), + retryButton.centerXAnchor.constraint(equalTo: centerXAnchor), + retryButton.widthAnchor.constraint(equalToConstant: 140), + retryButton.heightAnchor.constraint(equalToConstant: 44) + ]) + } +} -### Functionality +// Usage +let chatHistory = CometChatAIAssistanceChatHistory() +chatHistory.user = user -These functional customizations allow you to fine-tune the overall behavior and user experience of the component. -With these options, you can modify text, customize icons, and toggle visibility for specific UI elements within the `CometChatAIAssistanceChatHistory` component. +let errorView = CustomErrorView() +errorView.retryButton.addTarget(self, action: #selector(retryLoading), for: .touchUpInside) - - -```swift -swift let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. - -// Example: Adding a custom back button -let backButton = UIButton(type: .system) -backButton.setImage(UIImage(systemName: "snowflake"), for: .normal) -backButton.tintColor = .systemRed -backButton.addTarget(self, action: #selector(didTapBackButton), for: .touchUpInside) -chatHistory.backButton = backButton +chatHistory.set(errorView: errorView) ``` - - -## CometChatMessageList Properties - -Below is a list of customizations along with corresponding code snippets: - -| **Property** | **Description** | **Code** | -| -------------------------------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| **User** | Used to set the user for displaying their AI chat history. | `CometChatAIAssistantChatHistory.set(user: user)` | -| **Group** | Used to set the group for displaying its AI chat history. | `CometChatAIAssistantChatHistory.set(group: group)` | -| **Messages Request Builder** | Used to pass a custom message request builder to fetch AI chat history. | `CometChatAIAssistantChatHistory.set(messagesRequestBuilder: customBuilder)` | -| **Loading State View** | Used to set a custom loading view when fetching AI chat history. | `CometChatAIAssistantChatHistory.set(loadingStateView: customLoadingView)` | -| **Empty State View** | Used to set a custom view when no messages are available. | `CometChatAIAssistantChatHistory.set(emptyStateView: customEmptyView)` | -| **Error State View** | Used to set a custom error view when message fetching fails. | `CometChatAIAssistantChatHistory.set(errorStateView: customErrorView)` | -| **On Message Clicked** | Used to handle actions when a message is clicked. | `CometChatAIAssistantChatHistory.set(onMessageClicked: { message in })` | -| **On Error** | Used to handle actions when an error occurs while fetching data. | `CometChatAIAssistantChatHistory.set(onError: { })` | -| **On Load** | Used to handle actions when chat history is successfully loaded. | `CometChatAIAssistantChatHistory.set(onLoad: { })` | -| **On Empty** | Used to handle actions when chat history is empty. | `CometChatAIAssistantChatHistory.set(onEmpty: { })` | -| **On New Chat Button Clicked** | Used to handle actions when the “New Chat” button is clicked. | `CometChatAIAssistantChatHistory.set(onNewChatButtonClicked: { user in })` | -| **On Close** | Used to handle actions when the back button is pressed. | `CometChatAIAssistantChatHistory.set(onClose: { })` | -| **Empty State Text** | Used to set the text when the chat history list is empty. | `CometChatAIAssistantChatHistory.emptyStateText = "No conversations yet"` | -| **Empty State Subtitle Text** | Used to set a subtitle when the chat history list is empty. | `CometChatAIAssistantChatHistory.emptyStateSubtitleText = "Start a new chat to begin"` | -| **Error State Text** | Used to set the text when an error occurs. | `CometChatAIAssistantChatHistory.errorStateText = "Failed to load history"` | -| **Error State Subtitle Text** | Used to set a subtitle when an error occurs. | `CometChatAIAssistantChatHistory.errorStateSubtitleText = "Please try again later"` | -| **Hide Date Separator** | Used to hide or show the date separator in the chat history list. | `CometChatAIAssistantChatHistory.hideDateSeparator = true` | -*** - -### Advance - -For advanced-level customization, you can inject custom views or functions into the component. -This allows you to tailor the `CometChatAIAssistanceChatHistory` experience to align perfectly with your app’s interface and logic. - -#### dateSeparatorPattern - -You can modify the format of the date separator displayed between messages using the `dateSeparatorPattern` property. -This closure accepts a `Date` object and returns a formatted `String`. +--- -**Example** +## Filter Messages -Here is the complete example for reference: +Customize which messages are displayed: - + ```swift -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.user = user // A User or Group object is required to launch this component. -chatHistory.dateTimeFormatter.time = { timestamp in - return "at " + DateFormatter.localizedString(from: Date(timeIntervalSince1970: TimeInterval(timestamp)), dateStyle: .none, timeStyle: .short) -} -chatHistory.dateTimeFormatter.today = { timestamp in - return "Today • \(formattedTime(from: timestamp))" -} +import CometChatSDK +import CometChatUIKitSwift -// for global level -CometChatAIAssistanceChatHistory.dateTimeFormatter.otherDay = { timestamp in // This will display older dates as "24 Apr 2025" instead of the default relative format. - let formatter = DateFormatter() - formatter.dateFormat = "dd MMM yyyy" - return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) -} -``` +let chatHistory = CometChatAIAssistanceChatHistory() +chatHistory.user = user - +// Create custom message request builder +let builder = MessagesRequest.MessageRequestBuilder() + .set(uid: user.uid ?? "") + .set(limit: 50) +chatHistory.set(messagesRequestBuilder: builder) +``` + -*** - -#### loadingStateView + +These parameters are **always overridden** by the component: +- `uid` / `guid` +- `types` +- `categories` + -Customize the loading view displayed when messages are being fetched. -Use this property to show a spinner, skeleton loader, or a custom loading message for better UX. +--- -Use Cases: +## Embed in Your App -* Show a spinner or skeleton loader for smooth UX. -* Display a "Fetching history..." text. +### As a Tab - + ```swift -let loadingView = UIActivityIndicatorView(style: .large) -loadingView.startAnimating() - -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.set(loadingView: loadingView) +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class MainTabBarController: UITabBarController { + + var currentUser: CometChat.User! + + override func viewDidLoad() { + super.viewDidLoad() + fetchUserAndSetupTabs() + } + + private func fetchUserAndSetupTabs() { + // Get current logged in user + guard let user = CometChat.getLoggedInUser() else { return } + currentUser = user + setupTabs() + } + + private func setupTabs() { + // Chats Tab + let chatsVC = CometChatConversationsWithMessages() + let chatsNav = UINavigationController(rootViewController: chatsVC) + chatsNav.tabBarItem = UITabBarItem( + title: "Chats", + image: UIImage(systemName: "message"), + selectedImage: UIImage(systemName: "message.fill") + ) + + // AI Assistant Tab + let aiVC = CometChatAIAssistanceChatHistory() + aiVC.user = currentUser + aiVC.onNewChatButtonClicked = { [weak self] in + self?.startNewAIChat() + } + let aiNav = UINavigationController(rootViewController: aiVC) + aiNav.tabBarItem = UITabBarItem( + title: "AI Assistant", + image: UIImage(systemName: "sparkles"), + selectedImage: UIImage(systemName: "sparkles") + ) + + // Users Tab + let usersVC = CometChatUsersWithMessages() + let usersNav = UINavigationController(rootViewController: usersVC) + usersNav.tabBarItem = UITabBarItem( + title: "Users", + image: UIImage(systemName: "person.2"), + selectedImage: UIImage(systemName: "person.2.fill") + ) + + viewControllers = [chatsNav, aiNav, usersNav] + } + + private func startNewAIChat() { + let messagesVC = CometChatMessages() + messagesVC.user = currentUser + + if let nav = selectedViewController as? UINavigationController { + nav.pushViewController(messagesVC, animated: true) + } + } +} ``` - - -*** - -#### emptyStateView - -Customize the view displayed when there are no messages in the chat history. -This is typically used to show a friendly placeholder or an illustration.. - -Use Cases: - -* Display “No chat history yet” text. -* Add a button prompting users to start a new chat. +### As a Button Action - + ```swift -let emptyView = UILabel() -emptyView.text = "No chat history yet." -emptyView.textAlignment = .center -emptyView.textColor = .gray - -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.set(emptyView: emptyView) +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ProfileViewController: UIViewController { + + var user: CometChat.User! + + private let aiHistoryButton: UIButton = { + let button = UIButton(type: .system) + button.setTitle("View AI Chat History", for: .normal) + button.setImage(UIImage(systemName: "sparkles"), for: .normal) + button.backgroundColor = .systemBlue + button.tintColor = .white + button.layer.cornerRadius = 12 + button.translatesAutoresizingMaskIntoConstraints = false + return button + }() + + override func viewDidLoad() { + super.viewDidLoad() + setupUI() + } + + private func setupUI() { + view.backgroundColor = .systemBackground + view.addSubview(aiHistoryButton) + + NSLayoutConstraint.activate([ + aiHistoryButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), + aiHistoryButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), + aiHistoryButton.widthAnchor.constraint(equalToConstant: 250), + aiHistoryButton.heightAnchor.constraint(equalToConstant: 50) + ]) + + aiHistoryButton.addTarget(self, action: #selector(showAIHistory), for: .touchUpInside) + } + + @objc private func showAIHistory() { + let chatHistory = CometChatAIAssistanceChatHistory() + chatHistory.user = user + + chatHistory.onNewChatButtonClicked = { [weak self] in + let messagesVC = CometChatMessages() + messagesVC.user = self?.user + self?.navigationController?.pushViewController(messagesVC, animated: true) + } + + navigationController?.pushViewController(chatHistory, animated: true) + } +} ``` - - -*** - -#### errorStateView - -You can define a custom view to display when an error occurs during message loading. -This could include a retry button or a helpful error message for better recovery.. +--- -Use Cases: +## API Reference + +### Properties + +| Property | Type | Required | Description | +|----------|------|----------|-------------| +| `user` | `CometChat.User` | Yes* | User for AI chat history | +| `group` | `CometChat.Group` | Yes* | Group for AI chat history | +| `style` | `AiAssistantChatHistoryStyle` | No | Custom styling | +| `emptyStateText` | `String` | No | Empty state title | +| `emptyStateSubtitleText` | `String` | No | Empty state subtitle | +| `errorStateText` | `String` | No | Error state title | +| `errorStateSubtitleText` | `String` | No | Error state subtitle | +| `hideDateSeparator` | `Bool` | No | Hide date separators | +| `backButton` | `UIButton` | No | Custom back button | + +*Either `user` or `group` is required + +### Callbacks + +| Method | Parameters | Description | +|--------|------------|-------------| +| `onNewChatButtonClicked` | `() -> Void` | New chat button tapped | +| `onMessageClicked` | `(BaseMessage) -> Void` | Message tapped | +| `set(onLoad:)` | `([BaseMessage]) -> Void` | Data loaded | +| `set(onEmpty:)` | `() -> Void` | No data | +| `set(onError:)` | `(Error) -> Void` | Error occurred | + +### Custom Views + +| Method | Parameters | Description | +|--------|------------|-------------| +| `set(loadingView:)` | `UIView` | Custom loading view | +| `set(emptyView:)` | `UIView` | Custom empty state | +| `set(errorView:)` | `UIView` | Custom error state | +| `set(messagesRequestBuilder:)` | `MessagesRequestBuilder` | Filter messages | + +### Style Properties (AiAssistantChatHistoryStyle) + +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `UIColor` | Background color | +| `itemTextFont` | `UIFont` | Message text font | +| `itemTextColor` | `UIColor` | Message text color | +| `newChatTitleFont` | `UIFont` | New chat button font | +| `newChatTitleColor` | `UIColor` | New chat button color | -* Show a retry option on network failure. -* Display “Unable to load messages. Check your connection.". +--- - - -```swift -let errorView = UIView() -let errorLabel = UILabel() -errorLabel.text = "Couldn't load history. Check your connection." -errorLabel.textAlignment = .center -errorLabel.textColor = .systemRed -errorView.addSubview(errorLabel) -errorLabel.translatesAutoresizingMaskIntoConstraints = false -NSLayoutConstraint.activate([ -errorLabel.centerXAnchor.constraint(equalTo: errorView.centerXAnchor), -errorLabel.centerYAnchor.constraint(equalTo: errorView.centerYAnchor) -]) +## Troubleshooting -let chatHistory = CometChatAIAssistanceChatHistory() -chatHistory.set(errorView: errorView) -``` +| Problem | Solution | +|---------|----------| +| Only loading indicator shows | Set `user` or `group` property | +| No messages displayed | Enable AI features in CometChat Dashboard | +| Styling not applied | Apply style before presenting view | +| Callbacks not firing | Set callbacks before pushing to navigation | +| Empty state not showing | Check `set(onEmpty:)` callback | - +--- - +## Related -*** \ No newline at end of file +- [AI Features Overview](/ui-kit/ios/ai-features) - All AI features +- [Message List](/ui-kit/ios/message-list) - Chat message display +- [Message Composer](/ui-kit/ios/message-composer) - Message input +- [Components Overview](/ui-kit/ios/components-overview) - All components diff --git a/ui-kit/ios/ai-features.mdx b/ui-kit/ios/ai-features.mdx index 90f86183c..38031c90e 100644 --- a/ui-kit/ios/ai-features.mdx +++ b/ui-kit/ios/ai-features.mdx @@ -1,47 +1,507 @@ --- -title: "AI" +title: "AI Features" +sidebarTitle: "AI" +description: "Complete guide to AI-powered chat features in iOS apps - conversation starters, smart replies, and summaries" --- ## Overview -CometChat's AI capabilities greatly enhance user interaction and engagement in your application. Let's understand how the iOS UI Kit achieves these features. +CometChat AI features enhance your chat experience with intelligent suggestions and summaries. Once enabled in your dashboard, they integrate automatically into the UI Kit components. -## Conversation Starters +| Feature | What It Does | Where It Appears | +|---------|--------------|------------------| +| Conversation Starters | Suggests opening messages for new chats | `CometChatMessageList` | +| Smart Replies | Suggests responses based on context | `CometChatMessageComposer` | +| Conversation Summary | Summarizes long conversations | `CometChatMessageComposer` | +| AI Assistant | Chat with AI bot | `CometChatAIAssistanceChatHistory` | + +--- + +## Enable AI Features + + + +Go to [app.cometchat.com](https://app.cometchat.com) and select your app. + + + +Click **AI** in the sidebar, then enable the features you want: +- ✅ Conversation Starter +- ✅ Smart Replies +- ✅ Conversation Summary + + + +Customize AI behavior, response style, and triggers in the dashboard settings. + + + +**That's it!** AI features now work automatically in your app. -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 starters. +--- -For a comprehensive understanding and guide on implementing and using the Conversation Starters, refer to our specific guide on the [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter). +## Conversation Starters -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/ios/message-list) Component of UI Kits. +When a user opens a new chat with no message history, AI suggests conversation openers. -## Smart Replies +### How It Works + +1. User opens chat with someone they haven't messaged before +2. AI analyzes user profiles and context +3. Suggested messages appear in the message list +4. User taps a suggestion to send it -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. +### Implementation -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). +Conversation starters appear automatically in `CometChatMessages`: -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/ios/message-composer) Component of UI Kits. + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ChatViewController: UIViewController { + + func openChatWithUser(uid: String) { + CometChat.getUser(UID: uid) { [weak self] user in + DispatchQueue.main.async { + let messagesVC = CometChatMessages() + messagesVC.user = user + + // Conversation starters appear automatically + // if enabled in dashboard and no previous messages exist + + self?.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` + + + +--- + +## Smart Replies + +AI suggests contextual responses based on the conversation. -## Conversation Summary +### How It Works + +1. User receives a message +2. AI analyzes the message and conversation context +3. Smart reply suggestions appear in the composer action sheet +4. User taps a suggestion to insert it -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. +### Implementation -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). +Smart replies appear automatically in `CometChatMessageComposer`: -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/ios/message-composer) Component of UI Kits. + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ChatViewController: UIViewController { + + func openChat(with user: CometChat.User) { + let messagesVC = CometChatMessages() + messagesVC.user = user + + // Smart replies appear automatically in the composer + // when enabled in dashboard + + navigationController?.pushViewController(messagesVC, animated: true) + } +} +``` + + + +--- + +## Conversation Summary + +AI generates summaries of long conversations so users can catch up quickly. + +### How It Works + +1. User opens a conversation with many messages +2. User taps the summary option in composer action sheet +3. AI processes the conversation +4. Summary of key points is displayed + +### Implementation + +Conversation summary is available automatically: + + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ChatViewController: UIViewController { + + func openChat(with user: CometChat.User) { + let messagesVC = CometChatMessages() + messagesVC.user = user + + // Conversation summary option appears in composer action sheet + // when enabled in dashboard and sufficient messages exist + + navigationController?.pushViewController(messagesVC, animated: true) + } +} +``` + + + +--- + +## AI Assistant Chat History + +View and continue conversations with AI assistants. + +### Basic Implementation + + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class AIAssistantViewController: UIViewController { + + var user: CometChat.User! + + func showAIChatHistory() { + let chatHistory = CometChatAIAssistanceChatHistory() + chatHistory.user = user // Required + + navigationController?.pushViewController(chatHistory, animated: true) + } +} +``` + + + +### Full Implementation with Callbacks + + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class AIAssistantViewController: UIViewController { + + var user: CometChat.User! + + func showAIChatHistory() { + let chatHistory = CometChatAIAssistanceChatHistory() + chatHistory.user = user + + // Handle new chat button + chatHistory.onNewChatButtonClicked = { [weak self] in + self?.startNewAIChat() + } + + // Handle message tap + chatHistory.onMessageClicked = { message in + print("Tapped message: \(message.text ?? "")") + } + + // Handle load success + chatHistory.set(onLoad: { messages in + print("Loaded \(messages.count) AI messages") + }) + + // Handle empty state + chatHistory.set(onEmpty: { + print("No AI chat history") + }) + + // Handle errors + chatHistory.set(onError: { [weak self] error in + self?.showError(error.localizedDescription) + }) + + navigationController?.pushViewController(chatHistory, animated: true) + } + + private func startNewAIChat() { + // Navigate to new AI chat + print("Starting new AI conversation") + } + + private func showError(_ message: String) { + let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } +} +``` + + + +### Customize AI Chat History Styling + + + +```swift +import UIKit +import CometChatUIKitSwift + +class AIAssistantViewController: UIViewController { + + var user: CometChat.User! + + func showStyledAIChatHistory() { + let chatHistory = CometChatAIAssistanceChatHistory() + chatHistory.user = user + + // Custom styling + let style = AiAssistantChatHistoryStyle() + style.backgroundColor = .systemBackground + style.itemTextFont = UIFont.systemFont(ofSize: 16, weight: .medium) + style.itemTextColor = .label + style.newChatTitleFont = UIFont.systemFont(ofSize: 18, weight: .bold) + style.newChatTitleColor = .systemBlue + chatHistory.style = style + + // Custom empty state + chatHistory.emptyStateText = "No AI conversations yet" + chatHistory.emptyStateSubtitleText = "Tap 'New Chat' to start" + + // Custom date formatting + chatHistory.dateTimeFormatter.today = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.timeStyle = .short + return "Today at \(formatter.string(from: date))" + } + + navigationController?.pushViewController(chatHistory, animated: true) + } +} +``` + + + +--- + +## Complete App with AI Features + +Full implementation showing all AI features: + + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +// MARK: - Scene Delegate +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + + var window: UIWindow? + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + guard let windowScene = (scene as? UIWindowScene) else { return } + + let uikitSettings = UIKitSettings() + .set(appID: "YOUR_APP_ID") + .set(authKey: "YOUR_AUTH_KEY") + .set(region: "YOUR_REGION") + .subscribePresenceForAllUsers() + .build() + + CometChatUIKit.init(uiKitSettings: uikitSettings) { [weak self] result in + switch result { + case .success: + CometChatUIKit.login(uid: "cometchat-uid-1") { loginResult in + switch loginResult { + case .success: + DispatchQueue.main.async { + self?.setupUI(windowScene: windowScene) + } + case .onError(let error): + print("Login failed: \(error.description)") + @unknown default: + break + } + } + case .failure(let error): + print("Init failed: \(error.localizedDescription)") + } + } + } + + private func setupUI(windowScene: UIWindowScene) { + let tabBar = AIEnabledTabBarController() + window = UIWindow(windowScene: windowScene) + window?.rootViewController = tabBar + window?.makeKeyAndVisible() + } +} + +// MARK: - Tab Bar Controller +class AIEnabledTabBarController: UITabBarController { + + override func viewDidLoad() { + super.viewDidLoad() + setupTabs() + } + + private func setupTabs() { + // Chats - AI features (starters, smart replies, summary) work automatically + let chatsVC = CometChatConversationsWithMessages() + let chatsNav = UINavigationController(rootViewController: chatsVC) + chatsNav.tabBarItem = UITabBarItem( + title: "Chats", + image: UIImage(systemName: "message"), + selectedImage: UIImage(systemName: "message.fill") + ) + + // AI Assistant + let aiVC = AIAssistantListViewController() + let aiNav = UINavigationController(rootViewController: aiVC) + aiNav.tabBarItem = UITabBarItem( + title: "AI Assistant", + image: UIImage(systemName: "sparkles"), + selectedImage: UIImage(systemName: "sparkles") + ) + + // Users + let usersVC = CometChatUsersWithMessages() + let usersNav = UINavigationController(rootViewController: usersVC) + usersNav.tabBarItem = UITabBarItem( + title: "Users", + image: UIImage(systemName: "person.2"), + selectedImage: UIImage(systemName: "person.2.fill") + ) + + viewControllers = [chatsNav, aiNav, usersNav] + } +} + +// MARK: - AI Assistant List +class AIAssistantListViewController: UIViewController { + + private let tableView = UITableView() + private var users: [CometChat.User] = [] + + override func viewDidLoad() { + super.viewDidLoad() + title = "AI Assistant" + setupTableView() + fetchUsers() + } + + private func setupTableView() { + view.addSubview(tableView) + tableView.frame = view.bounds + tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + tableView.delegate = self + tableView.dataSource = self + tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") + } + + private func fetchUsers() { + let request = UsersRequest.UsersRequestBuilder() + .set(limit: 30) + .build() + + request.fetchNext { [weak self] users in + self?.users = users + DispatchQueue.main.async { + self?.tableView.reloadData() + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} + +extension AIAssistantListViewController: UITableViewDelegate, UITableViewDataSource { + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return users.count + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) + let user = users[indexPath.row] + cell.textLabel?.text = user.name + cell.accessoryType = .disclosureIndicator + return cell + } + + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + tableView.deselectRow(at: indexPath, animated: true) + + let user = users[indexPath.row] + let chatHistory = CometChatAIAssistanceChatHistory() + chatHistory.user = user + + chatHistory.onNewChatButtonClicked = { [weak self] in + // Start new AI chat + let messagesVC = CometChatMessages() + messagesVC.user = user + self?.navigationController?.pushViewController(messagesVC, animated: true) + } + + navigationController?.pushViewController(chatHistory, animated: true) + } +} +``` + + + +--- + +## Troubleshooting + +| Problem | Solution | +|---------|----------| +| AI features not appearing | Enable them in CometChat Dashboard → AI | +| Conversation starters not showing | Only appear for new conversations with no messages | +| Smart replies not appearing | Ensure feature is enabled and messages exist | +| Summary not generating | Need sufficient messages in conversation | +| AI Assistant empty | Verify user has AI chat history | + +--- + +## Related + +- [AI Assistant Chat History](/ui-kit/ios/ai-assistant-chat-history) - Full component documentation +- [Message List](/ui-kit/ios/message-list) - Where conversation starters appear +- [Message Composer](/ui-kit/ios/message-composer) - Where smart replies appear +- [Conversation Starter Guide](/fundamentals/ai-user-copilot/conversation-starter) - Platform configuration +- [Smart Replies Guide](/fundamentals/ai-user-copilot/smart-replies) - Platform configuration diff --git a/ui-kit/ios/call-features.mdx b/ui-kit/ios/call-features.mdx index c22dfa285..cbfca1a11 100644 --- a/ui-kit/ios/call-features.mdx +++ b/ui-kit/ios/call-features.mdx @@ -1,39 +1,26 @@ --- -title: "Call" +title: "Calling Features" +sidebarTitle: "Call" +description: "Complete guide to adding voice and video calling to iOS apps with CometChat UI Kit - production-ready code included" --- ## Overview -CometChat's Calls feature is an advanced functionality that 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 iOS UI Kit. +Add one-on-one and group audio/video calling to your iOS app. Once integrated, call buttons automatically appear in chat headers, and incoming/outgoing call screens are handled for you. -## 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/ios/getting-started) guide. This guide will walk you through a step-by-step process of integrating our UI Kit into your iOS project. - -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. Here's how you do it: - -**1. CocoaPods** - -We recommend using CocoaPods, as they are the most advanced way of managing iOS project dependencies. Open a terminal window, move to your project directory, and then create a Podfile by running the following command. - - - -1. You can install CometChatCallsSDK for iOS through Swift Package Manager or Cocoapods - -2. CometChatCallsSDK supports iOS 13 and aboveSwift 5.0+ - -3. CometChatCallsSDK supports Swift 5.0+ - - + + + -```ruby Swift -$ pod init -``` +--- -Add the following lines to the Podfile. +## Quick Setup -```ruby Swift -platform :ios, '11.0' + + +Add to your `Podfile`: +```ruby +platform :ios, '13.0' use_frameworks! target 'YourApp' do @@ -42,86 +29,592 @@ target 'YourApp' do end ``` -And then install the CometChatCallsSDK framework through CocoaPods. +Run: +```bash +pod install +``` + + + +Add to `Info.plist`: +```xml +NSCameraUsageDescription +Camera access required for video calls -```ruby Swift -$ pod install +NSMicrophoneUsageDescription +Microphone access required for voice and video calls +``` + + + +In `SceneDelegate.swift`: +```swift +import CometChatUIKitSwift + +func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + guard let windowScene = (scene as? UIWindowScene) else { return } + + let uikitSettings = UIKitSettings() + .set(appID: "YOUR_APP_ID") + .set(authKey: "YOUR_AUTH_KEY") + .set(region: "YOUR_REGION") // "us", "eu", or "in" + .build() + + CometChatUIKit.init(uiKitSettings: uikitSettings) { result in + switch result { + case .success: + CometChatUIKit.login(uid: "cometchat-uid-1") { loginResult in + switch loginResult { + case .success: + // Calling is now enabled automatically + print("✅ Ready for calls") + case .onError(let error): + print("❌ Login failed: \(error.description)") + @unknown default: + break + } + } + case .failure(let error): + print("❌ Init failed: \(error.localizedDescription)") + } + } +} ``` + + + +**That's it!** Call buttons now appear in `CometChatMessages` header automatically. -If you're facing any issues while installing pods then use the below command. +--- -```ruby Swift -$ pod install --repo-update +## Production-Ready Implementation + +Complete app with calling, chat, and call history: + + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + + var window: UIWindow? + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + guard let windowScene = (scene as? UIWindowScene) else { return } + + // Initialize CometChat + let uikitSettings = UIKitSettings() + .set(appID: "YOUR_APP_ID") + .set(authKey: "YOUR_AUTH_KEY") + .set(region: "YOUR_REGION") + .subscribePresenceForAllUsers() + .build() + + CometChatUIKit.init(uiKitSettings: uikitSettings) { [weak self] result in + switch result { + case .success: + print("✅ CometChat initialized") + self?.loginAndSetupUI(windowScene: windowScene) + + case .failure(let error): + print("❌ Init failed: \(error.localizedDescription)") + } + } + } + + private func loginAndSetupUI(windowScene: UIWindowScene) { + CometChatUIKit.login(uid: "cometchat-uid-1") { [weak self] result in + switch result { + case .success: + print("✅ Logged in") + DispatchQueue.main.async { + self?.setupMainInterface(windowScene: windowScene) + } + + case .onError(let error): + print("❌ Login failed: \(error.description)") + + @unknown default: + break + } + } + } + + private func setupMainInterface(windowScene: UIWindowScene) { + let tabBar = MainTabBarController() + + window = UIWindow(windowScene: windowScene) + window?.rootViewController = tabBar + window?.makeKeyAndVisible() + } +} +``` + + + +```swift +import UIKit +import CometChatUIKitSwift + +class MainTabBarController: UITabBarController { + + override func viewDidLoad() { + super.viewDidLoad() + setupTabs() + setupAppearance() + } + + private func setupTabs() { + // Chats Tab - with calling enabled + let chatsVC = CometChatConversationsWithMessages() + let chatsNav = UINavigationController(rootViewController: chatsVC) + chatsNav.tabBarItem = UITabBarItem( + title: "Chats", + image: UIImage(systemName: "message"), + selectedImage: UIImage(systemName: "message.fill") + ) + + // Calls Tab - call history + let callsVC = CometChatCallLogs() + callsVC.set(onItemClick: { [weak self] callLog, _ in + self?.handleCallLogTap(callLog) + }) + let callsNav = UINavigationController(rootViewController: callsVC) + callsNav.tabBarItem = UITabBarItem( + title: "Calls", + image: UIImage(systemName: "phone"), + selectedImage: UIImage(systemName: "phone.fill") + ) + + // Users Tab + let usersVC = CometChatUsersWithMessages() + let usersNav = UINavigationController(rootViewController: usersVC) + usersNav.tabBarItem = UITabBarItem( + title: "Users", + image: UIImage(systemName: "person.2"), + selectedImage: UIImage(systemName: "person.2.fill") + ) + + // Groups Tab + let groupsVC = CometChatGroupsWithMessages() + let groupsNav = UINavigationController(rootViewController: groupsVC) + groupsNav.tabBarItem = UITabBarItem( + title: "Groups", + image: UIImage(systemName: "person.3"), + selectedImage: UIImage(systemName: "person.3.fill") + ) + + viewControllers = [chatsNav, callsNav, usersNav, groupsNav] + } + + private func setupAppearance() { + tabBar.tintColor = .systemBlue + tabBar.backgroundColor = .systemBackground + } + + private func handleCallLogTap(_ callLog: CallLog) { + // Get the other user from call log + let loggedInUser = CometChat.getLoggedInUser() + var otherUserUID: String? + + if let initiator = callLog.initiator as? CallUser, + initiator.uid != loggedInUser?.uid { + otherUserUID = initiator.uid + } else if let receiver = callLog.receiver as? CallUser { + otherUserUID = receiver.uid + } + + guard let uid = otherUserUID else { return } + + // Fetch user and open chat + CometChat.getUser(UID: uid) { [weak self] user in + DispatchQueue.main.async { + let messagesVC = CometChatMessages() + messagesVC.user = user + + if let nav = self?.selectedViewController as? UINavigationController { + nav.pushViewController(messagesVC, animated: true) + } + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} ``` + + -Always get the latest version of CometChatCallsSDK by command. +--- -```ruby Swift -$ pod update CometChatCallsSDK +## Initiate Calls Programmatically + +### Voice Call to User + + + +```swift +import CometChatSDK + +func startVoiceCall(to userUID: String) { + let call = CometChat.Call( + receiverId: userUID, + callType: .audio, + receiverType: .user + ) + + CometChat.initiateCall(call: call) { call in + print("✅ Voice call started: \(call?.sessionId ?? "")") + } onError: { error in + print("❌ Call failed: \(error?.errorDescription ?? "")") + } +} + +// Usage +startVoiceCall(to: "cometchat-uid-2") ``` + + + +### Video Call to User + + + +```swift +import CometChatSDK + +func startVideoCall(to userUID: String) { + let call = CometChat.Call( + receiverId: userUID, + callType: .video, + receiverType: .user + ) + + CometChat.initiateCall(call: call) { call in + print("✅ Video call started: \(call?.sessionId ?? "")") + } onError: { error in + print("❌ Call failed: \(error?.errorDescription ?? "")") + } +} + +// Usage +startVideoCall(to: "cometchat-uid-2") +``` + + + +### Group Call + + + +```swift +import CometChatSDK + +func startGroupCall(to groupGUID: String, type: CometChat.CallType) { + let call = CometChat.Call( + receiverId: groupGUID, + callType: type, + receiverType: .group + ) + + CometChat.initiateCall(call: call) { call in + print("✅ Group call started: \(call?.sessionId ?? "")") + } onError: { error in + print("❌ Call failed: \(error?.errorDescription ?? "")") + } +} + +// Usage +startGroupCall(to: "group-guid", type: .video) +``` + + - +--- -Always ensure to open the XCFramework file after adding the dependencies. +## Custom Call Buttons + +Add call buttons anywhere in your app: + + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class UserProfileViewController: UIViewController { + + var user: CometChat.User! + + private let voiceCallButton: UIButton = { + let button = UIButton(type: .system) + button.setImage(UIImage(systemName: "phone.fill"), for: .normal) + button.setTitle(" Voice Call", for: .normal) + button.backgroundColor = .systemGreen + button.tintColor = .white + button.layer.cornerRadius = 12 + button.translatesAutoresizingMaskIntoConstraints = false + return button + }() + + private let videoCallButton: UIButton = { + let button = UIButton(type: .system) + button.setImage(UIImage(systemName: "video.fill"), for: .normal) + button.setTitle(" Video Call", for: .normal) + button.backgroundColor = .systemBlue + button.tintColor = .white + button.layer.cornerRadius = 12 + button.translatesAutoresizingMaskIntoConstraints = false + return button + }() + + override func viewDidLoad() { + super.viewDidLoad() + setupUI() + } + + private func setupUI() { + view.backgroundColor = .systemBackground + + let stackView = UIStackView(arrangedSubviews: [voiceCallButton, videoCallButton]) + stackView.axis = .horizontal + stackView.spacing = 16 + stackView.distribution = .fillEqually + stackView.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(stackView) + + NSLayoutConstraint.activate([ + stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor), + stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor), + stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 32), + stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -32), + + voiceCallButton.heightAnchor.constraint(equalToConstant: 50), + videoCallButton.heightAnchor.constraint(equalToConstant: 50) + ]) + + voiceCallButton.addTarget(self, action: #selector(voiceCallTapped), for: .touchUpInside) + videoCallButton.addTarget(self, action: #selector(videoCallTapped), for: .touchUpInside) + } + + @objc private func voiceCallTapped() { + initiateCall(type: .audio) + } + + @objc private func videoCallTapped() { + initiateCall(type: .video) + } + + private func initiateCall(type: CometChat.CallType) { + guard let uid = user.uid else { return } + + let call = CometChat.Call( + receiverId: uid, + callType: type, + receiverType: .user + ) + + CometChat.initiateCall(call: call) { [weak self] call in + print("✅ Call initiated") + } onError: { [weak self] error in + self?.showError(error?.errorDescription ?? "Call failed") + } + } + + private func showError(_ message: String) { + let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } +} +``` + + - +--- -*** +## Using CometChatCallButtons Component + +The built-in call buttons component: + + + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ChatHeaderViewController: UIViewController { + + var user: CometChat.User! + + override func viewDidLoad() { + super.viewDidLoad() + setupCallButtons() + } + + private func setupCallButtons() { + let callButtons = CometChatCallButtons() + callButtons.user = user + + // Customize actions + callButtons.set(onVoiceCallClick: { user, group in + print("Voice call to: \(user?.name ?? group?.name ?? "")") + }) + + callButtons.set(onVideoCallClick: { user, group in + print("Video call to: \(user?.name ?? group?.name ?? "")") + }) + + callButtons.set(onError: { error in + print("Error: \(error.errorDescription)") + }) + + // Add to navigation bar + let hostingController = UIHostingController(rootView: callButtons) + addChild(hostingController) + + navigationItem.rightBarButtonItem = UIBarButtonItem(customView: hostingController.view) + } +} +``` + + -**2. Swift Package Manager.** +--- -Add the Call SDK dependency : +## Handle Incoming Calls + +Incoming calls are handled automatically. For custom handling: + + + +```swift +import CometChatSDK + +class CallHandler: NSObject, CometChatCallDelegate { + + static let shared = CallHandler() + + func registerForCalls() { + CometChat.calldelegate = self + } + + // Called when receiving an incoming call + func onIncomingCallReceived(incomingCall: CometChat.Call?, error: CometChat.CometChatException?) { + guard let call = incomingCall else { return } + + print("📞 Incoming call from: \(call.sender?.name ?? "")") + print("Call type: \(call.callType == .audio ? "Audio" : "Video")") + + // The UI Kit automatically shows the incoming call screen + // Add custom logic here if needed + } + + // Called when an outgoing call is accepted + func onOutgoingCallAccepted(acceptedCall: CometChat.Call?, error: CometChat.CometChatException?) { + guard let call = acceptedCall else { return } + print("✅ Call accepted: \(call.sessionId ?? "")") + } + + // Called when an outgoing call is rejected + func onOutgoingCallRejected(rejectedCall: CometChat.Call?, error: CometChat.CometChatException?) { + guard let call = rejectedCall else { return } + print("❌ Call rejected: \(call.sessionId ?? "")") + } + + // Called when an incoming call is cancelled + func onIncomingCallCancelled(canceledCall: CometChat.Call?, error: CometChat.CometChatException?) { + guard let call = canceledCall else { return } + print("📵 Call cancelled: \(call.sessionId ?? "")") + } + + // Called when a call ends + func onCallEnded(endedCall: CometChat.Call?, error: CometChat.CometChatException?) { + guard let call = endedCall else { return } + print("📴 Call ended: \(call.sessionId ?? "")") + } +} + +// Register in AppDelegate or SceneDelegate +// CallHandler.shared.registerForCalls() +``` + + -You can install **Calling SDK for iOS** through **Swift Package Manager.** +--- -1. Go to your Swift Package Manager's File tab and select Add Packages +## Calling Components Reference -2. Add `CometChatCallsSDK` into your `Package Repository` as below: +### CometChatCallButtons -```sh Bash -https://github.com/cometchat/calls-sdk-ios.git -``` +Renders voice and video call buttons. -3. To add the package, select Version Rules, enter Up to Exact Version, **4.0.5** and click Next. +```swift +let callButtons = CometChatCallButtons() +callButtons.user = user // or callButtons.group = group - +// Callbacks +callButtons.set(onVoiceCallClick: { user, group in }) +callButtons.set(onVideoCallClick: { user, group in }) +callButtons.set(onError: { error in }) +``` -Before Adding the Call SDK dependency to your project's dependencies please make sure that you have completed the Chat UI Kit Integration. +### CometChatIncomingCall - +Displays incoming call screen with accept/reject options. -After adding this dependency, the iOS UI Kit will automatically detect it and activate the calling features. Now, your application supports both audio and video calling. You will see [CallButtons](/ui-kit/ios/call-buttons) component rendered in [MessageHeader](/ui-kit/ios/message-header) Component. +```swift +let incomingCall = CometChatIncomingCall() +incomingCall.set(call: call) - - - +incomingCall.set(onAcceptClick: { call in }) +incomingCall.set(onDeclineClick: { call in }) +``` -## Features +### CometChatOutgoingCall -### Incoming Call +Displays outgoing call screen while waiting for answer. -The [Incoming Call](/ui-kit/ios/incoming-call) component of the CometChat UI Kit provides the functionality that lets users receive real-time audio and video calls in the app. +```swift +let outgoingCall = CometChatOutgoingCall() +outgoingCall.set(call: call) -When a call is made to a user, the Incoming Call component triggers and displays a call screen. This call screen typically displays the caller information and provides the user with options to either accept or reject the incoming call. +outgoingCall.set(onCancelClick: { call in }) +``` - - - +### CometChatCallLogs -### Outgoing Call +Displays call history. See [Call Logs](/ui-kit/ios/call-logs) for full documentation. -The [Outgoing Call](/ui-kit/ios/incoming-call) component of the CometChat UI Kit is designed to manage the outgoing call process within your application. When a user initiates an audio or video call to another user or group, this component displays an outgoing call screen, showcasing information about the recipient and the call status. +```swift +let callLogs = CometChatCallLogs() +callLogs.set(onItemClick: { callLog, indexPath in }) +``` -Importantly, the Outgoing Call component is smartly designed to transition automatically into the ongoing call screen once the receiver accepts the call. This ensures a smooth flow from initiating the call to engaging in a conversation, without any additional steps required from the user. +--- - - - +## Troubleshooting -### Call Logs +| Problem | Solution | +|---------|----------| +| Call buttons not showing | Verify `CometChatCallsSDK` is in Podfile and run `pod install` | +| "Permission denied" error | Add camera/microphone permissions to Info.plist | +| Calls not connecting | Check network connection and CometChat credentials | +| No incoming call UI | Ensure `CometChatCallsSDK` is initialized before login | +| Audio not working | Check device is not on silent mode | -[Call Logs](/ui-kit/ios/call-logs) component provides you with the records call events such as who called who, the time of the call, and the duration of the call. This information can be fetched from the CometChat server and displayed in a structured format for users to view their past call activities. +--- - - - +## Related + +- [Call Logs](/ui-kit/ios/call-logs) - Display call history +- [Call Buttons](/ui-kit/ios/call-buttons) - Call button component +- [Incoming Call](/ui-kit/ios/incoming-call) - Incoming call screen +- [Outgoing Call](/ui-kit/ios/outgoing-call) - Outgoing call screen +- [Ongoing Call](/ui-kit/ios/ongoing-call) - Active call screen From 9e98cb6e6a2b73e425071b1b4fa3d0b85d3158c9 Mon Sep 17 00:00:00 2001 From: Aditya Date: Tue, 10 Feb 2026 18:14:49 +0530 Subject: [PATCH 002/106] changed in color-resources, component-styling, components-overview --- ui-kit/ios/color-resources.mdx | 314 +++++++++++++-- ui-kit/ios/component-styling.mdx | 626 +++++++++++++++++++---------- ui-kit/ios/components-overview.mdx | 355 +++++++++++++++- 3 files changed, 1030 insertions(+), 265 deletions(-) diff --git a/ui-kit/ios/color-resources.mdx b/ui-kit/ios/color-resources.mdx index 097b70398..deb771630 100644 --- a/ui-kit/ios/color-resources.mdx +++ b/ui-kit/ios/color-resources.mdx @@ -1,60 +1,320 @@ --- title: "Color Resources" +sidebarTitle: "Color Resources" +description: "Complete guide to customizing colors in CometChat iOS UI Kit - themes, dark mode, and branding" --- ## Overview -Color resources in CometChatTheme for iOS enable you to maintain a consistent visual identity across your application. These predefined colors are used for various UI elements, including text, buttons, backgrounds, alerts, and more. +CometChat UI Kit uses `CometChatTheme` to manage colors across all components. Colors automatically adapt to Light and Dark mode, ensuring a consistent experience. -CometChatTheme adapts seamlessly to **Light mode** and **Dark mode**, ensuring an optimal user experience across different system appearances. - -The color resources are divided into the following categories: + + + + + + + + + + + + -* **Primary Colors**: Define the main theme of the application. -* **Neutral Colors**: Used for backgrounds, strokes, and secondary UI elements. -* **Alert Colors**: Highlight states like success, warning, error, or information. -* **Text Colors**: Used for typography. -* **Icon Colors**: Define icon appearances. -* **Button Colors**: Customize button backgrounds, icons, and text. +--- -CometChatTheme provides separate color definitions for light and dark modes, allowing seamless adaptation to the system's theme. +## Color Categories -## Usage +| Category | Purpose | Examples | +|----------|---------|----------| +| **Primary** | Main brand color, buttons, links | `primaryColor` | +| **Background** | Screen and component backgrounds | `backgroundColor01`, `backgroundColor02` | +| **Text** | Typography colors | `textColorPrimary`, `textColorSecondary` | +| **Border** | Dividers and outlines | `borderColorLight`, `borderColorDark` | +| **Alert** | Status indicators | `successColor`, `errorColor`, `warningColor` | +| **Icon** | Icon tints | `iconColorPrimary`, `iconColorSecondary` | -Default Colors CometChatTheme includes predefined color sets for Light and Dark modes. These color sets ensure proper visual contrast, accessibility, and consistent branding. With CometChatTheme, the predefined colors are automatically applied based on the system’s appearance. +--- -You can access and use these default colors directly through the CometChatTheme class. +## Quick Start -Example: Light Mode Color Usage +### Access Default Colors ```swift -CometChatTheme.primaryColor // Example: UIColor(hex: "#6852D6") -CometChatTheme.backgroundColor01 // Light: UIColor(hex: "#FFFFFF") +import CometChatUIKitSwift + +// Primary brand color +let primary = CometChatTheme.primaryColor // #6852D6 + +// Background colors +let background = CometChatTheme.backgroundColor01 // White (light) / #141414 (dark) +let secondaryBg = CometChatTheme.backgroundColor02 + +// Text colors +let primaryText = CometChatTheme.textColorPrimary +let secondaryText = CometChatTheme.textColorSecondary + +// Alert colors +let success = CometChatTheme.successColor // Green +let error = CometChatTheme.errorColor // Red +let warning = CometChatTheme.warningColor // Orange + +// Icon colors +let iconPrimary = CometChatTheme.iconColorPrimary +let iconSecondary = CometChatTheme.iconColorSecondary ``` + + +--- + +## Customize Theme Colors + +### Change Primary Color (Brand Color) + + + +```swift +import CometChatUIKitSwift + +// Set your brand color globally +CometChatTheme.primaryColor = UIColor(hex: "#FF5722") // Orange brand + +// All components will now use this color for: +// - Buttons +// - Links +// - Selected states +// - Accent elements +``` + +### Complete Theme Customization + + + +```swift +import CometChatUIKitSwift + +class ThemeManager { + + static func applyCustomTheme() { + // Brand colors + CometChatTheme.primaryColor = UIColor(hex: "#6200EE") // Purple + + // Background colors + CometChatTheme.backgroundColor01 = UIColor(hex: "#FFFFFF") + CometChatTheme.backgroundColor02 = UIColor(hex: "#F5F5F5") + CometChatTheme.backgroundColor03 = UIColor(hex: "#EEEEEE") + + // Text colors + CometChatTheme.textColorPrimary = UIColor(hex: "#212121") + CometChatTheme.textColorSecondary = UIColor(hex: "#757575") + CometChatTheme.textColorTertiary = UIColor(hex: "#9E9E9E") + + // Border colors + CometChatTheme.borderColorLight = UIColor(hex: "#E0E0E0") + CometChatTheme.borderColorDark = UIColor(hex: "#BDBDBD") + + // Alert colors + CometChatTheme.successColor = UIColor(hex: "#4CAF50") + CometChatTheme.errorColor = UIColor(hex: "#F44336") + CometChatTheme.warningColor = UIColor(hex: "#FF9800") + CometChatTheme.infoColor = UIColor(hex: "#2196F3") + + // Icon colors + CometChatTheme.iconColorPrimary = UIColor(hex: "#212121") + CometChatTheme.iconColorSecondary = UIColor(hex: "#757575") + } +} + +// Apply in AppDelegate or SceneDelegate +ThemeManager.applyCustomTheme() +``` + - - - +--- + +## Dark Mode Support -Example: Dark Mode Color Usage +CometChat automatically adapts to system appearance. You can also customize dark mode colors: ```swift -CometChatTheme.primaryColor // Example: UIColor(hex: "#6852D6") -CometChatTheme.backgroundColor01 // Light: UIColor(hex: "#141414") -``` +import CometChatUIKitSwift +import UIKit +class ThemeManager { + + static func applyTheme() { + // Create dynamic colors that adapt to light/dark mode + CometChatTheme.primaryColor = UIColor { traitCollection in + return traitCollection.userInterfaceStyle == .dark + ? UIColor(hex: "#BB86FC") // Light purple for dark mode + : UIColor(hex: "#6200EE") // Purple for light mode + } + + CometChatTheme.backgroundColor01 = UIColor { traitCollection in + return traitCollection.userInterfaceStyle == .dark + ? UIColor(hex: "#121212") // Dark background + : UIColor(hex: "#FFFFFF") // White background + } + + CometChatTheme.textColorPrimary = UIColor { traitCollection in + return traitCollection.userInterfaceStyle == .dark + ? UIColor(hex: "#FFFFFF") // White text + : UIColor(hex: "#212121") // Dark text + } + } +} +``` + + +--- + +## Color Reference + +### Primary Colors + +| Property | Light Mode | Dark Mode | Usage | +|----------|------------|-----------|-------| +| `primaryColor` | `#6852D6` | `#6852D6` | Buttons, links, accents | + +### Background Colors + +| Property | Light Mode | Dark Mode | Usage | +|----------|------------|-----------|-------| +| `backgroundColor01` | `#FFFFFF` | `#141414` | Main background | +| `backgroundColor02` | `#F5F5F5` | `#1E1E1E` | Secondary background | +| `backgroundColor03` | `#EEEEEE` | `#2C2C2C` | Tertiary background | + +### Text Colors + +| Property | Light Mode | Dark Mode | Usage | +|----------|------------|-----------|-------| +| `textColorPrimary` | `#141414` | `#FFFFFF` | Main text | +| `textColorSecondary` | `#727272` | `#A0A0A0` | Secondary text | +| `textColorTertiary` | `#A0A0A0` | `#727272` | Hints, placeholders | + +### Alert Colors + +| Property | Color | Usage | +|----------|-------|-------| +| `successColor` | `#09C26F` | Success states | +| `errorColor` | `#F44649` | Errors, missed calls | +| `warningColor` | `#FFAB00` | Warnings | +| `infoColor` | `#2196F3` | Information | + +### Border Colors + +| Property | Light Mode | Dark Mode | Usage | +|----------|------------|-----------|-------| +| `borderColorLight` | `#E8E8E8` | `#2C2C2C` | Subtle borders | +| `borderColorDark` | `#CCCCCC` | `#404040` | Prominent borders | + +--- + +## Production Example + +Complete app with custom branding: + + + +```swift +import UIKit +import CometChatUIKitSwift + +@main +class AppDelegate: UIResponder, UIApplicationDelegate { + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + + // Apply custom theme before initializing CometChat + applyBrandTheme() + + return true + } + + private func applyBrandTheme() { + // Your brand colors + let brandPrimary = UIColor(hex: "#1E88E5") // Blue + let brandSecondary = UIColor(hex: "#FFC107") // Amber + + // Apply to CometChat theme + CometChatTheme.primaryColor = brandPrimary + + // Customize backgrounds + CometChatTheme.backgroundColor01 = UIColor { trait in + trait.userInterfaceStyle == .dark + ? UIColor(hex: "#0D1117") + : UIColor(hex: "#FFFFFF") + } + + CometChatTheme.backgroundColor02 = UIColor { trait in + trait.userInterfaceStyle == .dark + ? UIColor(hex: "#161B22") + : UIColor(hex: "#F6F8FA") + } + + // Customize text + CometChatTheme.textColorPrimary = UIColor { trait in + trait.userInterfaceStyle == .dark + ? UIColor(hex: "#C9D1D9") + : UIColor(hex: "#24292F") + } + + CometChatTheme.textColorSecondary = UIColor { trait in + trait.userInterfaceStyle == .dark + ? UIColor(hex: "#8B949E") + : UIColor(hex: "#57606A") + } + + // Alert colors + CometChatTheme.successColor = UIColor(hex: "#238636") + CometChatTheme.errorColor = UIColor(hex: "#DA3633") + CometChatTheme.warningColor = brandSecondary + } +} +// UIColor extension for hex support +extension UIColor { + convenience init(hex: String) { + var hexSanitized = hex.trimmingCharacters(in: .whitespacesAndNewlines) + hexSanitized = hexSanitized.replacingOccurrences(of: "#", with: "") + + var rgb: UInt64 = 0 + Scanner(string: hexSanitized).scanHexInt64(&rgb) + + let r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0 + let g = CGFloat((rgb & 0x00FF00) >> 8) / 255.0 + let b = CGFloat(rgb & 0x0000FF) / 255.0 + + self.init(red: r, green: g, blue: b, alpha: 1.0) + } +} +``` + - - - +--- + +## Troubleshooting + +| Problem | Solution | +|---------|----------| +| Colors not applying | Apply theme before `CometChatUIKit.init()` | +| Dark mode not working | Use `UIColor { traitCollection in }` for dynamic colors | +| Inconsistent colors | Set all related colors (text, background, border) together | + +--- + +## Related + +- [Component Styling](/ui-kit/ios/component-styling) - Style individual components +- [Theme Introduction](/ui-kit/ios/theme-introduction) - Complete theming guide +- [Getting Started](/ui-kit/ios/getting-started) - Initial setup diff --git a/ui-kit/ios/component-styling.mdx b/ui-kit/ios/component-styling.mdx index 369923b4e..f3308ea0a 100644 --- a/ui-kit/ios/component-styling.mdx +++ b/ui-kit/ios/component-styling.mdx @@ -1,240 +1,320 @@ --- title: "Component Styling" +sidebarTitle: "Component Styling" +description: "Complete guide to styling CometChat iOS UI Kit components - colors, fonts, and custom appearances" --- ## Overview -CometChat UIKit for iOS enables developers to integrate customizable components into their applications effortlessly. Each component is designed to ensure a consistent user experience, offering flexibility to align with your app’s design system. You can modify attributes such as colors, fonts, sizes, and more using CometChatTheme or directly applying styles to components. +Every CometChat component can be styled to match your app's design. You can apply styles globally (affects all instances) or per-instance (affects one component). -Below is a detailed guide for styling individual components within the UIKit. - -## Components +--- -### Conversations +## Styling Methods -The `CometChatConversations` component provides a list of recent chats, displaying participants, message previews, and timestamps. It supports default themes while offering extensive customization for text appearance, icons, and layout. This component allows you to create an intuitive and visually appealing chat list that matches your app's branding. +### Global Styling -You can check out the list of styling properties offered by [CometChatConversations](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Conversations/ConversationsStyle.swift) +Apply once, affects all instances of a component: ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = 8 +import CometChatUIKitSwift -let customReceiptStyle = ReceiptStyle() -customReceiptStyle.backgroundColor = UIColor(hex: "#F76808") - -let customBadgeStyle = BadgeStyle() -customBadgeStyle.backgroundColor = UIColor(hex: "#F76808") - -let customConversation = CometChatConversation() -customConversation.avatarStyle = customAvatarStyle -customConversation.receiptStyle = customReceiptStyle -customConversation.badgeStyle = customBadgeStyle +// Set before using any components (e.g., in AppDelegate) +CometChatConversations.style.titleColor = UIColor(hex: "#6200EE") +CometChatConversations.style.titleFont = UIFont.systemFont(ofSize: 28, weight: .bold) +CometChatConversations.style.backgroundColor = .systemBackground ``` - - - - - - -### Users +### Instance Styling -The CometChatUsers component displays a scrollable list of users, ideal for showcasing available contacts for messaging, calls, or group creation. Customization includes user avatars, status indicators, and list backgrounds, enabling alignment with your app's design system. - -You can check out the list of styling properties offered by [CometChatUsers](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Users/UsersStyle.swift) +Apply to a specific component instance: ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = 8 - -let customReceiptStyle = ReceiptStyle() -customReceiptStyle.backgroundColor = UIColor(hex: "#F76808") +import CometChatUIKitSwift -let customBadgeStyle = BadgeStyle() -customBadgeStyle.backgroundColor = UIColor(hex: "#F76808") +let style = ConversationsStyle() +style.titleColor = UIColor(hex: "#6200EE") +style.titleFont = UIFont.systemFont(ofSize: 28, weight: .bold) +style.backgroundColor = .systemBackground -CometChatUsers.style.titleColor = UIColor(hexString: "#F76808") -CometChatUsers.style.titleFont = UIFont(name: "Times-New-Roman", size: 34) -CometChatUsers.avatarStyle = customAvatarStyle -CometChatUsers.receiptStyle = customReceiptStyle -CometChatUsers.badgeStyle = customBadgeStyle +let conversations = CometChatConversations() +conversations.style = style ``` - - - - - +--- -### Groups +## Component Styles -The CometChatGroups component enables displaying and interacting with chat groups. Each group item highlights key details like group name, participant count, and last active time. Developers can customize avatar styles, fonts, borders, and background colors. +### Conversations -You can check out the list of styling properties offered by [CometChatGroups](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Groups/GroupsStyle.swift) + + + ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = 8 +import CometChatUIKitSwift + +// Create custom styles +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) + +let badgeStyle = BadgeStyle() +badgeStyle.backgroundColor = UIColor(hex: "#F76808") +badgeStyle.textColor = .white +badgeStyle.textFont = UIFont.systemFont(ofSize: 12, weight: .bold) + +let receiptStyle = ReceiptStyle() +receiptStyle.readIconTint = UIColor(hex: "#6200EE") +receiptStyle.deliveredIconTint = UIColor(hex: "#9E9E9E") + +// Apply to conversations +let conversations = CometChatConversations() +conversations.avatarStyle = avatarStyle +conversations.badgeStyle = badgeStyle +conversations.receiptStyle = receiptStyle + +// Style the list +conversations.style.titleColor = UIColor(hex: "#212121") +conversations.style.titleFont = UIFont.systemFont(ofSize: 17, weight: .semibold) +conversations.style.subtitleColor = UIColor(hex: "#757575") +conversations.style.subtitleFont = UIFont.systemFont(ofSize: 14) +conversations.style.backgroundColor = .systemBackground +conversations.style.listItemBackground = .systemBackground +``` + + -let customReceiptStyle = ReceiptStyle() -customReceiptStyle.backgroundColor = UIColor(hex: "#F76808") +[View all ConversationsStyle properties →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Conversations/ConversationsStyle.swift) -let customBadgeStyle = BadgeStyle() -customBadgeStyle.backgroundColor = UIColor(hex: "#F76808") +--- -CometChatGroups.style.titleColor = UIColor(hexString: "#F76808") -CometChatGroups.style.titleFont = UIFont(name: "Times-New-Roman", size: 34) -CometChatGroups.avatarStyle = customAvatarStyle -CometChatGroups.receiptStyle = customReceiptStyle -CometChatGroups.badgeStyle = customBadgeStyle -``` +### Users - + + + + + +```swift +import CometChatUIKitSwift + +// Avatar style +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) + +// Status indicator style +let statusStyle = StatusIndicatorStyle() +statusStyle.backgroundColor = .systemGreen +statusStyle.borderColor = .white +statusStyle.borderWidth = 2 + +// Apply styles +let users = CometChatUsers() +users.avatarStyle = avatarStyle +users.statusIndicatorStyle = statusStyle + +// List styling +users.style.titleColor = UIColor(hex: "#F76808") +users.style.titleFont = UIFont(name: "Helvetica-Bold", size: 28) +users.style.listItemTitleColor = UIColor(hex: "#212121") +users.style.listItemTitleFont = UIFont.systemFont(ofSize: 16, weight: .medium) +users.style.backgroundColor = .systemBackground +``` + - - - +[View all UsersStyle properties →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Users/UsersStyle.swift) -### Message Header +--- -The CometChatMessageHeader component displays essential information about the active chat, such as the recipient's name, avatar, and status (online/offline). It also includes navigation, search, or menu buttons. Customization options include header background, text appearance, and icon styles. +### Groups -You can check out the list of styling properties offered by [CometChatMessageHeader](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20Header/MessageHeaderStyle.swift) + + + ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") - -CometChatMessageHeader.style.titleTextColor = UIColor(hexString: "#F76808") -CometChatMessageHeader.style.titleTextFont = UIFont(name: "Times-New-Roman", size: 16) -CometChatMessageHeader.style.avatarStyle = customAvatarStyle +import CometChatUIKitSwift + +// Avatar style for group icons +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) + +// Apply styles +let groups = CometChatGroups() +groups.avatarStyle = avatarStyle + +// List styling +groups.style.titleColor = UIColor(hex: "#F76808") +groups.style.titleFont = UIFont(name: "Helvetica-Bold", size: 28) +groups.style.listItemTitleColor = UIColor(hex: "#212121") +groups.style.listItemSubtitleColor = UIColor(hex: "#757575") +groups.style.backgroundColor = .systemBackground ``` - - - - - +[View all GroupsStyle properties →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Groups/GroupsStyle.swift) -### Message List +--- -The CometChatMessageList component displays a conversation's sequence of messages, supporting text, media, reactions, and more. Developers can customize bubble colors, text appearance, timestamps, and alignment to enhance the chat experience. +### Message Header -You can check out the list of styling properties offered by [CometChatMessageList](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/MessageListStyle.swift) + + + ```swift -CometChatMessageList.style.backgroundColor = UIColor(hexString: "#FBAA75") -CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor(hexString: "#F76808") +import CometChatUIKitSwift + +// Avatar style +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) + +// Apply to message header +CometChatMessageHeader.style.titleTextColor = UIColor(hex: "#F76808") +CometChatMessageHeader.style.titleTextFont = UIFont(name: "Helvetica-Bold", size: 18) +CometChatMessageHeader.style.subtitleTextColor = UIColor(hex: "#757575") +CometChatMessageHeader.style.backgroundColor = .systemBackground +CometChatMessageHeader.avatarStyle = avatarStyle ``` - - - - - +[View all MessageHeaderStyle properties →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20Header/MessageHeaderStyle.swift) -### Message Composer +--- -The CometChatMessageComposer component provides users with an interface to compose and send messages, including text, attachments, and stickers. Developers can style input boxes, buttons, and icons to match their app’s design. +### Message List -You can check out the list of styling properties offered by [CometChatMessageList](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20Composer/MessageComposerStyle.swift) + + + ```swift -CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = UIColor(hexString: "#F76808") -CometChatMessageComposer.style.attachmentImageTint = UIColor(hexString: "#F76808") -CometChatMessageComposer.style.voiceRecordingImageTint = UIColor(hexString: "#F76808") -CometChatMessageComposer.style.stickerTint = UIColor(hexString: "#F76808") -CometChatMessageComposer.style.aiImageTint = UIColor(hexString: "#F76808") -``` +import CometChatUIKitSwift - +// Background color +CometChatMessageList.style.backgroundColor = UIColor(hex: "#FBAA75") +// Outgoing message bubbles (your messages) +CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor(hex: "#F76808") +CometChatMessageList.messageBubbleStyle.outgoing.textColor = .white +CometChatMessageList.messageBubbleStyle.outgoing.textFont = UIFont.systemFont(ofSize: 15) + +// Incoming message bubbles (other's messages) +CometChatMessageList.messageBubbleStyle.incoming.backgroundColor = UIColor(hex: "#E8E8E8") +CometChatMessageList.messageBubbleStyle.incoming.textColor = UIColor(hex: "#212121") +CometChatMessageList.messageBubbleStyle.incoming.textFont = UIFont.systemFont(ofSize: 15) + +// Timestamp style +CometChatMessageList.style.timestampTextColor = UIColor(hex: "#9E9E9E") +CometChatMessageList.style.timestampTextFont = UIFont.systemFont(ofSize: 11) +``` + - - - +[View all MessageListStyle properties →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/MessageListStyle.swift) -### Call Logs +--- -The CometChatCallLogs Component provides a comprehensive list of recent voice and video calls. Each call log displays details such as the caller’s name, avatar, call type (audio/video), call status (missed, incoming, outgoing), and timestamps. This component ensures smooth integration and allows developers to customize styles, icons, and colors to align with the app’s branding. +### Message Composer -You can check out the list of styling properties offered by [CometChatCallLogs](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Calls/Call%20Log/Call%20Logs/CallLogStyle.swift) + + + ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = 8 - -CometChatCallLogs.style.titleColor = UIColor(hexString: "#F76808") -CometChatCallLogs.style.titleFont = UIFont(name: "Roboto", size: 24) -CometChatCallLogs.avatarStyle = customAvatarStyle +import CometChatUIKitSwift + +// Send button +CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = UIColor(hex: "#F76808") +CometChatMessageComposer.style.sendButtonImageTint = .white + +// Action icons +CometChatMessageComposer.style.attachmentImageTint = UIColor(hex: "#F76808") +CometChatMessageComposer.style.voiceRecordingImageTint = UIColor(hex: "#F76808") +CometChatMessageComposer.style.stickerTint = UIColor(hex: "#F76808") +CometChatMessageComposer.style.aiImageTint = UIColor(hex: "#F76808") + +// Input field +CometChatMessageComposer.style.inputBackgroundColor = UIColor(hex: "#F5F5F5") +CometChatMessageComposer.style.inputTextColor = UIColor(hex: "#212121") +CometChatMessageComposer.style.inputTextFont = UIFont.systemFont(ofSize: 16) +CometChatMessageComposer.style.placeholderTextColor = UIColor(hex: "#9E9E9E") + +// Background +CometChatMessageComposer.style.backgroundColor = .systemBackground +CometChatMessageComposer.style.borderColor = UIColor(hex: "#E8E8E8") ``` - - +[View all MessageComposerStyle properties →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20Composer/MessageComposerStyle.swift) + +--- + +### Call Logs + -### AI Assistant Chat History - -The CometChatAIAssistantChatHistory component provides a pre-built interface to display the conversation history between a user and an AI assistant. Each message shows the sender, timestamp, and message content. This component ensures smooth integration and allows developers to customize styles, icons, and colors to align with the app’s branding. - ```swift -let customDateStyle = CometChatDateStyle( -textColor: UIColor(hexString: "#8E8E93"), -textStyle: UIFont.systemFont(ofSize: 12) -) -CometChatAIAssistantChatHistory.style.backgroundColor = UIColor(hexString: "#FFF9F2") -CometChatAIAssistantChatHistory.style.headerBackgroundColor = UIColor(hexString: "#FFF9F2") -CometChatAIAssistantChatHistory.style.headerTitleTextColor = UIColor(hexString: "#141414") -CometChatAIAssistantChatHistory.style.headerTitleTextFont = UIFont.boldSystemFont(ofSize: 18) -CometChatAIAssistantChatHistory.style.newChatIconColor = UIColor(hexString: "#F76808") -CometChatAIAssistantChatHistory.style.itemTextColor = UIColor(hexString: "#141414") -CometChatAIAssistantChatHistory.style.itemTextFont = UIFont.systemFont(ofSize: 14) -CometChatAIAssistantChatHistory.style.dateSeparatorStyle = customDateStyle +import CometChatUIKitSwift + +// Avatar style +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) + +// Apply styles +CometChatCallLogs.style.titleColor = UIColor(hex: "#F76808") +CometChatCallLogs.style.titleFont = UIFont(name: "Helvetica-Bold", size: 24) +CometChatCallLogs.style.listItemTitleTextColor = UIColor(hex: "#212121") +CometChatCallLogs.style.listItemSubTitleTextColor = UIColor(hex: "#757575") +CometChatCallLogs.style.backgroundColor = .systemBackground + +// Call type icons +CometChatCallLogs.style.incomingCallIconTint = .systemRed +CometChatCallLogs.style.outgoingCallIconTint = .systemGreen +CometChatCallLogs.style.missedCallTitleColor = .systemRed + +CometChatCallLogs.avatarStyle = avatarStyle ``` - - -### Search +[View all CallLogStyle properties →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Calls/Call%20Log/Call%20Logs/CallLogStyle.swift) + +--- -The `CometChatSearch` component allows users to search through conversations and messages. It provides a user-friendly interface for finding specific content quickly, with customizable styles for various elements such as background colors, text appearances, and section headers. +### Search @@ -242,129 +322,231 @@ The `CometChatSearch` component allows users to search through conversations and - ```swift +import CometChatUIKitSwift -// component level styling +// Instance styling let style = SearchStyle() style.backgroundColor = UIColor(hex: "#EDEAFA") style.listItemBackground = UIColor(hex: "#EDEAFA") -style.listItemTitleFont = UIFont(name: "TimesNewRomanPS-Regular", size: 16) -style.titleFont = UIFont(name: "TimesNewRomanPS-Bold", size: 12) -style.searchBarPlaceholderTextFont = UIFont(name: "TimesNewRomanPS-Regular", size: 12) - +style.listItemTitleFont = UIFont(name: "Helvetica", size: 16) +style.titleFont = UIFont(name: "Helvetica-Bold", size: 12) +style.searchBarPlaceholderTextFont = UIFont(name: "Helvetica", size: 12) +style.searchBarBackgroundColor = .white +style.searchBarTextColor = UIColor(hex: "#212121") + let searchVC = CometChatSearch() searchVC.style = style -self?.navigationController?.pushViewController(searchVC, animated: true) - - -// global level styling + +// Or global styling CometChatSearch.style.backgroundColor = UIColor(hex: "#EDEAFA") CometChatSearch.style.listItemBackground = UIColor(hex: "#EDEAFA") -CometChatSearch.style.listItemTitleFont = UIFont(name: "TimesNewRomanPS-Regular", size: 16) -CometChatSearch.style.titleFont = UIFont(name: "TimesNewRomanPS-Bold", size: 12) -CometChatSearch.style.searchBarPlaceholderTextFont = UIFont(name: "TimesNewRomanPS-Regular", size: 12) ``` - -*** - -## Base Component - -### Avatar - -The `CometChatAvatar` Component is used across the UIKit to represent users, groups, or placeholders visually. This highly reusable component supports various shapes (circle or square), sizes, borders, and fallback icons, allowing complete design consistency for profile or group images. - -You can check out the list of styling properties offered by [CometChatAvatar](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Avatar/AvatarStyle.swift) - -### Status indicator - -The `CometChatStatusIndicator` visually represents user presence (online, offline, or custom states). It can be styled for different shapes, sizes, and colors to reflect your app’s visual preferences while maintaining clarity in conveying status information. - -You can check out the list of styling properties offered by [CometChatStatusIndicator](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Status%20Indicator/StatusIndicatorStyle.swift) - -### Badge - -The `CometChatBadge` Component displays notifications or counts, such as unread messages. It can be styled for background colors, border radius, text size, and colors, allowing you to create visually distinct indicators for different notifications. - -You can check out the list of styling properties offered by [CometChatBadge](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Badge/BadgeCountStyle.swift) - -### Date - -The `CometChatDate` Component formats and displays timestamps in conversation lists and message threads. It ensures time-related information is clear and consistent. Developers can customize its text appearance, alignment, and colors to fit various contexts. - -You can check out the list of styling properties offered by [CometChatDate](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Date/DateStyle.swift) - -### Receipts - -The `CometChatReceipts` Component indicates message delivery and read statuses using intuitive icons. These can be styled for icon size, tint, and alignment, ensuring they remain clear and consistent with your app’s UI. - -You can check out the list of styling properties offered by [CometChatReceipts](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Receipt/ReceiptStyle.swift) - -### Media Recorder - -The `CometChatMediaRecorder` Component facilitates the recording of audio and video messages. It supports full customization of its recording controls, including button sizes, shapes, and colors, making it an integral part of your media-rich chat experience. - -You can check out the list of styling properties offered by [CometChatMediaRecorder](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/MediaRecorder/MediaRecorderStyle.swift) - -### Sticker Keyboard - -The `CometChatStickerKeyboard` simplifies the integration of sticker-based messaging. Customize the background, grid layout, and sticker display styles to align with your chat experience. This component provides a visually rich and interactive way to enhance conversations. +--- -You can check out the list of styling properties offered by [CometChatStickerKeyboard](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Extensions/Sticker/StickerKeyboardStyle.swift) +### AI Assistant Chat History -### Reaction list + + +```swift +import CometChatUIKitSwift -The `CometChatReactionList` Component provides a visual representation of emoji reactions on messages. It supports customization for reaction sizes, spacing, and colors, enabling you to build an engaging and personalized messaging environment. +// Date separator style +let dateStyle = CometChatDateStyle() +dateStyle.textColor = UIColor(hex: "#8E8E93") +dateStyle.textFont = UIFont.systemFont(ofSize: 12) -You can check out the list of styling properties offered by [CometChatReactionList](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/ReactionsHelper/ReactionList/ReactionListStyle.swift) +// Apply styles +CometChatAIAssistantChatHistory.style.backgroundColor = UIColor(hex: "#FFF9F2") +CometChatAIAssistantChatHistory.style.headerBackgroundColor = UIColor(hex: "#FFF9F2") +CometChatAIAssistantChatHistory.style.headerTitleTextColor = UIColor(hex: "#141414") +CometChatAIAssistantChatHistory.style.headerTitleTextFont = UIFont.boldSystemFont(ofSize: 18) +CometChatAIAssistantChatHistory.style.newChatIconColor = UIColor(hex: "#F76808") +CometChatAIAssistantChatHistory.style.itemTextColor = UIColor(hex: "#141414") +CometChatAIAssistantChatHistory.style.itemTextFont = UIFont.systemFont(ofSize: 14) +CometChatAIAssistantChatHistory.style.dateSeparatorStyle = dateStyle +``` + + -### Conversation Starter +--- -The `CometChatConversationStarter` Component offers AI-based suggestions or reply options to initiate a chat. Developers can customize the background, text styles, and button appearances to ensure seamless integration with the app’s visual language. +## Base Component Styles -You can check out the list of styling properties offered by [CometChatConversationStarter](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/AI/AI%20Conversation%20Starter/AIConversationStarterStyle.swift) +### Avatar -### Conversation Summary + + +```swift +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#6200EE") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 24) // Circle +avatarStyle.borderWidth = 2 +avatarStyle.borderColor = .white +avatarStyle.textFont = UIFont.systemFont(ofSize: 16, weight: .bold) +avatarStyle.textColor = .white +``` + + -The `CometChatConversationSummary` Component highlights the essence of a conversation, including participant details, last message, and timestamp. Customize text sizes, colors, and spacing to create visually distinct summaries that improve readability and engagement. +[View AvatarStyle →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Avatar/AvatarStyle.swift) -You can check out the list of styling properties offered by [CometChatConversationSummary](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/AI/AI%20Summarizer/AIConversationSummaryStyle.swift) +### Badge -### Smart Replies + + +```swift +let badgeStyle = BadgeStyle() +badgeStyle.backgroundColor = UIColor(hex: "#F44336") +badgeStyle.textColor = .white +badgeStyle.textFont = UIFont.systemFont(ofSize: 12, weight: .bold) +badgeStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 10) +badgeStyle.borderWidth = 0 +``` + + -The `CometChatSmartReplies` Component provides AI-driven suggestions for quick message replies. Fully customizable for button styles, padding, and colors, this component enables a streamlined and modern chat experience for users. +[View BadgeStyle →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Badge/BadgeCountStyle.swift) -You can check out the list of styling properties offered by [CometChatSmartReplies](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/AI/AI%20Smart%20Replies/AISmartRepliesStyle.swift) +### Status Indicator -### Message Information + + +```swift +let statusStyle = StatusIndicatorStyle() +statusStyle.backgroundColor = .systemGreen // Online color +statusStyle.borderColor = .white +statusStyle.borderWidth = 2 +statusStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 6) // Circle +``` + + -The `CometChatMessageInformation` Component displays metadata for messages, such as delivery timestamps, sender details, and read receipts. Customization options include text styles, colors, and alignment, making it adaptable to various app layouts. +[View StatusIndicatorStyle →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Status%20Indicator/StatusIndicatorStyle.swift) -You can check out the list of styling properties offered by [CometChatMessageInformation](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20Information/MessageInformationStyle.swift) +### Receipt -### Message option sheet + + +```swift +let receiptStyle = ReceiptStyle() +receiptStyle.sentIconTint = UIColor(hex: "#9E9E9E") +receiptStyle.deliveredIconTint = UIColor(hex: "#9E9E9E") +receiptStyle.readIconTint = UIColor(hex: "#6200EE") +receiptStyle.errorIconTint = UIColor(hex: "#F44336") +``` + + -The `CometChatMessageOptionSheet` Component is a context menu for performing actions on messages, such as replying, forwarding, or deleting. Developers can style its background, icons, and text to match the app’s menu system. +[View ReceiptStyle →](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Receipt/ReceiptStyle.swift) -You can check out the list of styling properties offered by [CometChatMessageOptionSheet](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Models/CometChatMessageOption.swift) +--- -### Attachment option sheet +## Complete Styling Example -The `CometChatAttachmentOptionSheet` Component provides a sleek interface for users to attach media, documents, or other files. It supports icon and text customizations to create a cohesive attachment experience. +Apply consistent branding across all components: -You can check out the list of styling properties offered by [CometChatAttachmentOptionSheet](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Views/Message%20Action%20Sheet/ActionSheetStyle.swift) + + +```swift +import CometChatUIKitSwift +import UIKit + +class StyleManager { + + // Brand colors + static let primaryColor = UIColor(hex: "#6200EE") + static let secondaryColor = UIColor(hex: "#03DAC6") + static let backgroundColor = UIColor.systemBackground + static let surfaceColor = UIColor(hex: "#F5F5F5") + static let textPrimary = UIColor(hex: "#212121") + static let textSecondary = UIColor(hex: "#757575") + + static func applyGlobalStyles() { + // Theme colors + CometChatTheme.primaryColor = primaryColor + + // Avatar style (used everywhere) + let avatarStyle = AvatarStyle() + avatarStyle.backgroundColor = secondaryColor + avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) + + // Badge style + let badgeStyle = BadgeStyle() + badgeStyle.backgroundColor = primaryColor + badgeStyle.textColor = .white + + // Apply to Conversations + CometChatConversations.avatarStyle = avatarStyle + CometChatConversations.badgeStyle = badgeStyle + CometChatConversations.style.titleColor = textPrimary + CometChatConversations.style.titleFont = UIFont.systemFont(ofSize: 28, weight: .bold) + CometChatConversations.style.backgroundColor = backgroundColor + + // Apply to Users + CometChatUsers.avatarStyle = avatarStyle + CometChatUsers.style.titleColor = textPrimary + CometChatUsers.style.backgroundColor = backgroundColor + + // Apply to Groups + CometChatGroups.avatarStyle = avatarStyle + CometChatGroups.style.titleColor = textPrimary + CometChatGroups.style.backgroundColor = backgroundColor + + // Apply to Message Header + CometChatMessageHeader.avatarStyle = avatarStyle + CometChatMessageHeader.style.titleTextColor = textPrimary + CometChatMessageHeader.style.backgroundColor = backgroundColor + + // Apply to Message List + CometChatMessageList.style.backgroundColor = surfaceColor + CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = primaryColor + CometChatMessageList.messageBubbleStyle.outgoing.textColor = .white + CometChatMessageList.messageBubbleStyle.incoming.backgroundColor = .white + CometChatMessageList.messageBubbleStyle.incoming.textColor = textPrimary + + // Apply to Message Composer + CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = primaryColor + CometChatMessageComposer.style.attachmentImageTint = primaryColor + CometChatMessageComposer.style.backgroundColor = backgroundColor + + // Apply to Call Logs + CometChatCallLogs.avatarStyle = avatarStyle + CometChatCallLogs.style.titleColor = textPrimary + CometChatCallLogs.style.backgroundColor = backgroundColor + } +} + +// Apply in AppDelegate +@main +class AppDelegate: UIResponder, UIApplicationDelegate { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + StyleManager.applyGlobalStyles() + return true + } +} +``` + + -### AIOption Sheet +--- -The `CometChatAIOptionSheet` Component offers AI-powered action options, like generating replies or initiating voice-to-text commands. It allows developers to style icons, colors, and interaction elements for a polished and user-friendly interface. +## Troubleshooting -You can check out the list of styling properties offered by [CometChatAIOptionSheet](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/AI/AI%20Shared%20Views/AIOptionsStyle.swift) +| Problem | Solution | +|---------|----------| +| Styles not applying | Apply global styles before `CometChatUIKit.init()` | +| Instance style overridden | Instance styles take precedence over global | +| Colors look wrong in dark mode | Use dynamic colors with `UIColor { traitCollection in }` | +| Font not loading | Verify font name is correct and font is added to project | -### Mentions +--- -The `CometChatMentions` Component highlights referenced users or groups within messages. With customizable styles for text color and background, you can ensure mentions stand out clearly in chats while maintaining a cohesive visual theme. +## Related -You can check out the list of styling properties offered by [CometChatMentions](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20Composer/TextFormatter/MentionTextStyle.swift) +- [Color Resources](/ui-kit/ios/color-resources) - Theme colors +- [Theme Introduction](/ui-kit/ios/theme-introduction) - Complete theming +- [Components Overview](/ui-kit/ios/components-overview) - All components diff --git a/ui-kit/ios/components-overview.mdx b/ui-kit/ios/components-overview.mdx index 3888e4b00..0eebab191 100644 --- a/ui-kit/ios/components-overview.mdx +++ b/ui-kit/ios/components-overview.mdx @@ -1,47 +1,370 @@ --- -title: "Overview" +title: "Components Overview" +sidebarTitle: "Overview" +description: "Understanding CometChat iOS UI Kit components - types, actions, events, and customization" --- -CometChat's **UI Kit** is a set of pre-built UI components that allows you to easily craft an in-app chat with all the essential messaging features. +## Overview -## Type of Components +CometChat UI Kit provides pre-built components that you can use to quickly build a chat experience. Components are organized into three types based on complexity. -UI components based on the behaviour and functionality can be categorized into three types: Base Components, Components, and Composite Components. +--- + +## Component Types ### Base Components -Base Components form the building blocks of your app's user interface (UI). They focus solely on presenting visual elements based on input data, without handling any business logic. These components provide the foundational appearance and behavior for your UI. +Simple UI elements with no business logic. They display data you pass to them. + +| Component | Purpose | +|-----------|---------| +| `CometChatAvatar` | User/group profile images | +| `CometChatBadge` | Notification counts | +| `CometChatStatusIndicator` | Online/offline status | +| `CometChatDate` | Formatted timestamps | +| `CometChatReceipt` | Message delivery status | + + + +```swift +import CometChatUIKitSwift + +// Avatar - displays user image +let avatar = CometChatAvatar() +avatar.setAvatar(avatarUrl: user.avatar, with: user.name) + +// Badge - shows unread count +let badge = CometChatBadge() +badge.set(count: 5) + +// Status indicator - shows online status +let status = CometChatStatusIndicator() +status.set(status: .online) +``` + + + +--- ### Components -Components build upon Base Components by incorporating business logic. They not only render UI elements but also manage data loading, execute specific actions, and respond to events. This combination of visual presentation and functional capabilities makes Components essential for creating dynamic and interactive UIs. +UI elements with built-in business logic. They fetch data, handle actions, and emit events. + +| Component | Purpose | +|-----------|---------| +| `CometChatUsers` | List of users | +| `CometChatGroups` | List of groups | +| `CometChatConversations` | Recent chats list | +| `CometChatMessageList` | Chat messages | +| `CometChatMessageComposer` | Message input | +| `CometChatMessageHeader` | Chat header | +| `CometChatCallLogs` | Call history | + + + +```swift +import CometChatUIKitSwift + +// Users list - fetches and displays users automatically +let users = CometChatUsers() +users.set(onItemClick: { user, indexPath in + print("Selected: \(user.name ?? "")") +}) + +// Conversations - shows recent chats +let conversations = CometChatConversations() +conversations.set(onItemClick: { conversation, indexPath in + // Open chat +}) + +// Message list - displays messages for a user/group +let messageList = CometChatMessageList() +messageList.set(user: user) +``` + + + +--- ### Composite Components -Composite Components are advanced UI elements that combine multiple Components or other Composite Components to achieve complex functionality. By layering components together, Composite Components offer a sophisticated and flexible approach to designing UIs. They enable diverse functionalities and interactions, making them versatile tools for creating rich user experiences. +Combine multiple components into complete features. + +| Component | Contains | +|-----------|----------| +| `CometChatMessages` | MessageHeader + MessageList + MessageComposer | +| `CometChatUsersWithMessages` | Users + Messages | +| `CometChatGroupsWithMessages` | Groups + Messages | +| `CometChatConversationsWithMessages` | Conversations + Messages | + + + +```swift +import CometChatUIKitSwift + +// Complete chat experience in one component +let conversationsWithMessages = CometChatConversationsWithMessages() +navigationController?.pushViewController(conversationsWithMessages, animated: true) + +// Or just the messages view +let messages = CometChatMessages() +messages.user = user // or messages.group = group +navigationController?.pushViewController(messages, animated: true) +``` + + + +--- ## Actions -Actions direct the operational behavior of a component. They are split into two categories: Predefined Actions and User-Defined Actions. +Actions define how components respond to user interactions. ### Predefined Actions -These are actions that are inherently programmed into a UI component. They are ingrained in the component itself by default, and they execute automatically in response to user interaction,without needing any additional user input. +Built-in behaviors that work automatically: + + + +```swift +// CometChatConversations has predefined actions: +// - Tap conversation → Opens messages +// - Long press → Shows options +// - Swipe → Delete conversation -### User-Defined Actions +let conversations = CometChatConversations() +// These work automatically! +``` + + -These are actions that must be explicitly specified by the user. They are not innately part of the component like predefined actions. Instead, they must be developed based on the unique needs of the user or the application. User-defined actions provide adaptability and allow for the creation of custom behaviors that align with the individual needs of the application. +### Custom Actions -To customize the behavior of a component, actions must be overridden by the user. This provides the user with control over how the component responds to specific events or interactions. +Override default behavior with your own logic: -Both Components and Composite Components expose actions to the user, which means that users can interact with these types of components through predefined or user-defined actions. On the other hand, Base Components do not expose actions to the user as they are the foundational building blocks mainly responsible for rendering the user interface and do not carry any business logic or actions. + + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +// Override tap action +conversations.set(onItemClick: { conversation, indexPath in + // Your custom logic + print("Tapped: \(conversation.conversationWith?.name ?? "")") + + // Navigate to custom screen instead of default + let customChatVC = MyChatViewController() + customChatVC.conversation = conversation + self.navigationController?.pushViewController(customChatVC, animated: true) +}) + +// Override long press +conversations.set(onItemLongClick: { conversation, indexPath in + // Show custom options + self.showCustomOptions(for: conversation) +}) + +// Handle errors +conversations.set(onError: { error in + print("Error: \(error.localizedDescription)") +}) + +// Handle empty state +conversations.set(onEmpty: { + print("No conversations") +}) +``` + + + +--- ## Events -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. +Events allow components to communicate without direct references. Subscribe to events from anywhere in your app. -Both Components and Composite Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. +### Available Events + +| Event | Triggered When | +|-------|----------------| +| `ccMessageSent` | Message is sent | +| `ccMessageEdited` | Message is edited | +| `ccMessageDeleted` | Message is deleted | +| `ccMessageRead` | Message is read | +| `ccUserBlocked` | User is blocked | +| `ccUserUnblocked` | User is unblocked | +| `ccGroupCreated` | Group is created | +| `ccGroupDeleted` | Group is deleted | +| `ccGroupMemberAdded` | Member added to group | +| `ccGroupMemberRemoved` | Member removed from group | + +### Subscribe to Events + + + +```swift +import CometChatUIKitSwift +import Combine + +class ChatManager { + + private var cancellables = Set() + + func subscribeToEvents() { + // Message sent event + CometChatMessageEvents.ccMessageSent + .sink { message in + print("Message sent: \(message.text ?? "")") + // Update UI, analytics, etc. + } + .store(in: &cancellables) + + // Message deleted event + CometChatMessageEvents.ccMessageDeleted + .sink { message in + print("Message deleted: \(message.id)") + } + .store(in: &cancellables) + + // User blocked event + CometChatUserEvents.ccUserBlocked + .sink { user in + print("Blocked: \(user.name ?? "")") + } + .store(in: &cancellables) + + // Group member added + CometChatGroupEvents.ccGroupMemberAdded + .sink { (action, addedBy, addedUser, group) in + print("\(addedUser.name ?? "") added to \(group.name ?? "")") + } + .store(in: &cancellables) + } + + func unsubscribe() { + cancellables.removeAll() + } +} +``` + + + +--- ## Configurations -Configurations offer the ability to customize the properties of each individual component within a Composite Component. If a Composite Component includes multiple components, each of these components will have its own set of properties that can be configured. This means multiple sets of configurations are available, one for each constituent component. This allows for fine-tuned customization of the Composite Component, enabling you to tailor its behavior and appearance to match specific requirements in a granular manner. +Customize nested components within composite components: + + + +```swift +import CometChatUIKitSwift + +// CometChatMessages contains: MessageHeader, MessageList, MessageComposer +// You can configure each one: + +let messages = CometChatMessages() +messages.user = user + +// Configure MessageHeader +let headerConfig = MessageHeaderConfiguration() +headerConfig.hideBackButton = false +headerConfig.set(subtitleView: { user, group in + let label = UILabel() + label.text = user?.status == .online ? "Online" : "Offline" + label.textColor = user?.status == .online ? .systemGreen : .gray + return label +}) +messages.set(messageHeaderConfiguration: headerConfig) + +// Configure MessageList +let listConfig = MessageListConfiguration() +listConfig.set(emptyStateText: "No messages yet") +listConfig.set(errorStateText: "Failed to load messages") +messages.set(messageListConfiguration: listConfig) + +// Configure MessageComposer +let composerConfig = MessageComposerConfiguration() +composerConfig.set(placeholderText: "Type a message...") +composerConfig.hideLiveReaction = true +messages.set(messageComposerConfiguration: composerConfig) +``` + + + +--- + +## Component Hierarchy + +``` +CometChatConversationsWithMessages +├── CometChatConversations +│ ├── CometChatListItem +│ │ ├── CometChatAvatar +│ │ ├── CometChatBadge +│ │ ├── CometChatStatusIndicator +│ │ └── CometChatDate +│ └── CometChatListBase +└── CometChatMessages + ├── CometChatMessageHeader + │ ├── CometChatAvatar + │ └── CometChatStatusIndicator + ├── CometChatMessageList + │ ├── CometChatMessageBubble + │ ├── CometChatReceipt + │ └── CometChatDate + └── CometChatMessageComposer + ├── CometChatMediaRecorder + └── CometChatStickerKeyboard +``` + +--- + +## Quick Reference + +### When to Use Each Type + +| Need | Use | +|------|-----| +| Display user avatar | `CometChatAvatar` (Base) | +| Show list of users | `CometChatUsers` (Component) | +| Complete chat with user selection | `CometChatUsersWithMessages` (Composite) | +| Custom chat UI | Individual Components | +| Quick integration | Composite Components | + +### Common Patterns + + + +```swift +// Pattern 1: Quick integration with composite +let chat = CometChatConversationsWithMessages() +navigationController?.pushViewController(chat, animated: true) + +// Pattern 2: Custom flow with components +let users = CometChatUsers() +users.set(onItemClick: { user, _ in + let messages = CometChatMessages() + messages.user = user + self.navigationController?.pushViewController(messages, animated: true) +}) + +// Pattern 3: Fully custom with base components +let customCell = UITableViewCell() +let avatar = CometChatAvatar() +avatar.setAvatar(avatarUrl: user.avatar, with: user.name) +customCell.contentView.addSubview(avatar) +``` + + + +--- + +## Related + +- [Component Styling](/ui-kit/ios/component-styling) - Customize appearance +- [Color Resources](/ui-kit/ios/color-resources) - Theme colors +- [Getting Started](/ui-kit/ios/getting-started) - Initial setup From 6d19fe0028a57baa4d36f7450f7b06f5dc529dac Mon Sep 17 00:00:00 2001 From: Aditya Date: Tue, 10 Feb 2026 19:09:50 +0530 Subject: [PATCH 003/106] transformed conversations, core-features , events --- ui-kit/ios/conversations.mdx | 1411 +++++++------------------ ui-kit/ios/core-features.mdx | 851 ++++++++++++++-- ui-kit/ios/events.mdx | 1868 ++++++++++------------------------ 3 files changed, 1666 insertions(+), 2464 deletions(-) diff --git a/ui-kit/ios/conversations.mdx b/ui-kit/ios/conversations.mdx index b8b804408..c62e53e11 100644 --- a/ui-kit/ios/conversations.mdx +++ b/ui-kit/ios/conversations.mdx @@ -1,1186 +1,491 @@ --- title: "Conversations" +description: "Display and manage all chat conversations for the logged-in user" --- -## Overview - -The Conversations is a [Component](/ui-kit/ios/components-overview#components), That shows all conversations related to the currently logged-in user, +The `CometChatConversations` component displays a list of all conversations (one-on-one and group chats) for the currently logged-in user. It shows the last message, unread count, typing indicators, and user presence in real-time. -## Usage - -### Integration - -As CometChatConversations is a custom view controller, it can be initiated either by tapping a button or through the trigger of any event. It offers multiple parameters and methods for tailoring its user interface. - -```ruby swift -let cometChatConversations = CometChatConversations() -self.navigationController.pushViewController(cometChatConversations, animated: true) -``` - -* Integration (With Custom Request Builder) - -During the initialization of **CometChatConversations,** users can provide this custom request builder. - -```ruby swift -// You can create ConversationRequestBuilder as per your requirement -let conversationRequestBuilder = ConversationRequest.ConversationRequestBuilder(limit: 20).set(conversationType: .both) - -let cometChatConversations = CometChatConversations(conversationRequestBuilder: conversationRequestBuilder) -self.navigationController.pushViewController(cometChatConversations, animated: true) -``` - - - -If a navigation controller is already in use, opt for the `pushViewController` method instead of presenting the view controller. - - - -### Actions - -[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -1. ##### set(onItemClick:) - -`set(OnItemClick:)` is triggered when you click on a ListItem of the Conversations component. This `set(OnItemClick:)` method proves beneficial when a user intends to customize the on-click behavior in CometChatConversations. - - - -```swift -// syntax for set(onItemClick: @escaping ((_ conversation: Conversation, _ indexPath: IndexPath) -> Void)) -cometChatConversations.set(onItemClick: { conversation, indexPath in - // Override on item click -}) -``` - - - - - -*** - -2. ##### set(OnItemLongClick:) - -`set(OnItemLongClick:)` is triggered when you long press on a ListItem of the Conversations component. This `set(OnItemLongClick:)` method proves beneficial when a user intends to additional functionality on long press on list item in CometChatConversations. - - - -```swift -// syntax for set(onItemLongClick: @escaping ((_ conversation: Conversation, _ indexPath: IndexPath) -> Void)) -cometChatConversations.set(onItemLongClick: { conversation, indexPath in - // Override on item click -}) -``` - - - - - -*** - -##### 3. set(onBack:) - -This `set(onBack:)` method becomes valuable when a user needs to override the action triggered upon pressing the back button in CometChatConversations. - - - -```swift -// syntax for set(onBack: @escaping () -> Void) -cometChatConversations.set(onBack: { - // Override on back -}) -``` - - - - - -*** - -##### 4. set(onSelection:) - -The `set(onSelection:)` only gets trigger when selection mode is set to multiple of single. And this gets trigger on every selection, and returns the list of selected conversations. - - - -```swift - -conversations.set(onSelection: { conversations in - //Handle action -}) -``` - - - - - -*** - -##### 5. set(onError:) - -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatConversations. - - - -```swift -// syntax for set(onError: @escaping ((_ error: CometChatException) -> Void)) -cometChatConversations.set(onError: { error in - // Override on error -}) -``` - - - - +## Prerequisites -*** +Before using this component, ensure you have: -##### 6. set(onEmpty:) +1. [Initialized the CometChat UI Kit](/ui-kit/ios/getting-started) +2. [Logged in a user](/ui-kit/ios/getting-started#login) -This `set(onEmpty:)` method is triggered when the conversations list is empty in CometChatConversations. +## Basic Usage - - ```swift -// syntax for set(onEmpty: @escaping () -> Void) -cometChatConversations.set(onEmpty: { - // Handle empty state -}) -``` - - - - - -*** - -##### 7. setOnLoad - -This set(onLoad:) gets triggered when a conversation list is fully fetched and going to displayed on the screen, this return the list of conversations to get displayed on the screen. - - - -```swift -// syntax for set(onLoad: @escaping ((_ conversations: [Conversation]) -> Void)) -cometChatConversations.set(onLoad: { conversations in - // Handle loaded conversations -}) -``` - - - - - -*** - -### Filters - -You can set `ConversationsRequestBuilder` in the Conversations Component to filter the conversation list. You can modify the builder as per your specific requirements with multiple options available to know more refer to [ConversationRequestBuilder](/sdk/ios/retrieve-conversations). - -You can set filters using the following parameters. - -1. **Conversation Type:** Filters on type of Conversation, `User` or `Groups` -2. **Limit:** Number of conversations fetched in a single request. -3. **WithTags:** Filter on fetching conversations containing tags -4. **Tags:** Filters on specific `Tag` -5. **UserTags:** Filters on specific User `Tag` -6. **GroupTags:** Filters on specific Group `Tag` - - - -```swift -// You can create ConversationRequestBuilder as per your requirement -let conversationRequestBuilder = ConversationRequest.ConversationRequestBuilder(limit: 20).set(conversationType: .both) - -let cometChatConversations = CometChatConversations(conversationRequestBuilder: conversationRequestBuilder) -self.navigationController.pushViewController(cometChatConversations, animated: true) -``` - - - - - - - -If a navigation controller is already in use, opt for the `pushViewController` method instead of presenting the view controller. - - - -*** - -### Events - -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -##### 1. ConversationDeleted - -This event will be emitted when the user deletes a conversation - - - -```swift Add Listener -// View controller from your project where you want to listen events. -public class ViewController: UIViewController { +import CometChatUIKitSwift - public override func viewDidLoad() { +class ConversationsViewController: UIViewController { + + override func viewDidLoad() { super.viewDidLoad() - - // Subscribing for the listener to listen events from conversation module - CometChatConversationEvents.addListener("UNIQUE_ID", self as CometChatConversationEventListener) - } - -} - - // Listener events from conversation module -extension ViewController: CometChatConversationEventListener { - - func ccConversationDelete(conversation: Conversation) { - // Do Stuff + + let conversations = CometChatConversations() + + // Push to navigation stack + navigationController?.pushViewController(conversations, animated: true) } - } ``` -```ruby Remove Listener -public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from conversation module - CometChatConversationEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") -} -``` - - - - +## Production-Ready Implementation -## Customization +This example shows a complete conversations screen with navigation to messages, custom filtering, and error handling: -To align with your app's design specifications, you have the flexibility to customize the appearance of the conversation component. We offer accessible methods that empower you to tailor the experience and functionality to meet your unique requirements. - -### Style - -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. - -##### 1. Conversation Style - -The CometChatConversation component allows developers to customize its appearance through the ConversationStyle class. This enables global-level or instance-specific styling. - -**Global level styling** - - - ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = 8 - -let customReceiptStyle = ReceiptStyle() -customReceiptStyle.backgroundColor = UIColor(hex: "#F76808") - -var customBadgeStyle = BadgeStyle() -customBadgeStyle.backgroundColor = UIColor(hex: "#F76808") - -CometChatConversation.style.backgroundColor = CometChatTheme.backgroundColor01 -CometChatConversation.style.avatarStyle = customAvatarStyle -CometChatConversation.style.receiptStyle = customReceiptStyle -CometChatConversation.style.badgeStyle = customBadgeStyle -``` - - - - - -**Instance level styling** +import UIKit +import CometChatUIKitSwift +import CometChatSDK - - -```swift -let conversationStyle = ConversationsStyle() -conversationStyle.backgroundColor = CometChatTheme.backgroundColor01 +class ChatListViewController: UIViewController { + + private var conversationsController: CometChatConversations! + + override func viewDidLoad() { + super.viewDidLoad() + setupConversations() + } + + private func setupConversations() { + // Create custom request builder for filtering + let requestBuilder = ConversationRequest.ConversationRequestBuilder(limit: 30) + .set(conversationType: .both) // Show both user and group conversations -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = 8 - -let customReceiptStyle = ReceiptStyle() -customReceiptStyle.backgroundColor = UIColor(hex: "#F76808") - -let customBadgeStyle = BadgeStyle() -customBadgeStyle.backgroundColor = UIColor(hex: "#F76808") - -let customConversation = CometChatConversation() -customConversation.avatarStyle = customAvatarStyle -customConversation.receiptStyle = customReceiptStyle -customConversation.badgeStyle = customBadgeStyle -customConversation.style = conversationStyle -``` - - - - - - - - - -List of properties exposed by ConversationStyle - -| **Property** | **Description** | **Code** | -| ------------------------------- | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | -| **Background Color** | Used to set the background color of the conversation screen. | `CometChatConversation.style.backgroundColor = UIColor.white` | -| **Background Drawable** | Used to set a background image for the conversation screen. | `CometChatConversation.style.backgroundDrawable = UIImage(named: "background")` | -| **Border Width** | Used to set the border width of the conversation UI. | `CometChatConversation.style.borderWidth = 2.0` | -| **Border Color** | Used to set the border color of the conversation UI. | `CometChatConversation.style.borderColor = UIColor.gray` | -| **Corner Radius** | Used to set the corner radius of the conversation UI. | `CometChatConversation.style.cornerRadius = 10.0` | -| **Back Icon Tint** | Used to set the tint color of the back icon in the conversation UI. | `CometChatConversation.style.backIconTint = UIColor.blue` | -| **Back Icon** | Used to set a custom back icon for the conversation UI. | `CometChatConversation.style.backIcon = UIImage(named: "customBackIcon")` | -| **Separator Color** | Used to set the color of separators in the conversation list. | `CometChatConversation.style.separatorColor = UIColor.lightGray` | -| **Separator Width** | Used to set the width of separators in the conversation list. | `CometChatConversation.style.separatorWidth = 1.0` | -| **Error Text Color** | Used to set the color of error messages in the conversation UI. | `CometChatConversation.style.errorTextColor = UIColor.red` | -| **Last Message Text Color** | Used to set the color of the last message text in the conversation list. | `CometChatConversation.style.lastMessageTextColor = UIColor.darkGray` | -| **Typing Indicator Color** | Used to set the color of the typing indicator in the conversation UI. | `CometChatConversation.style.typingIndicatorColor = UIColor.green` | -| **Title Appearance** | Used to customize the appearance of the conversation screen's title. | `CometChatConversation.style.titleAppearance = UIFont.boldSystemFont(ofSize: 18.0)` | -| **Last Message Appearance** | Used to customize the appearance of the last message text in the list. | `CometChatConversation.style.lastMessageAppearance = UIFont.italicSystemFont(ofSize: 14.0)` | -| **Thread Indicator Appearance** | Used to customize the appearance of thread indicators in the list. | `CometChatConversation.style.threadIndicatorTextAppearance = UIFont.systemFont(ofSize: 12.0)` | -| **Avatar Style** | Used to customize the appearance of avatars in the conversation list. | `CometChatConversation.style.avatarStyle = customAvatarStyle` | -| **Status Indicator Style** | Used to customize the style of status indicators for online/offline members. | `CometChatConversation.style.statusIndicatorStyle = customStatusIndicatorStyle` | -| **Date Style** | Used to customize the appearance of date labels in the conversation list. | `CometChatConversation.style.dateStyle = customDateStyle` | -| **Badge Style** | Used to customize the appearance of badges in the conversation list. | `CometChatConversation.style.badgeStyle = customBadgeStyle` | -| **List Item Style** | Used to customize the appearance of the list items in the conversation list. | `CometChatConversation.style.listItemStyle = customListItemStyle` | - -##### 2. Avatar Style - -To apply customized styles to the `Avatar` component in the `Conversations` Component, you can use the following code snippet. For more information, visit [Avatar Styles](/ui-kit/ios/component-styling#avatar). - -**Global level styling** - - - -```swift -CometChatAvatar.style.cornerRadius = CometChatCornerStyle(cornerRadius: 8) -CometChatAvatar.style.backgroundColor = UIColor(hex: "#F76808") + // Initialize conversations component + conversationsController = CometChatConversations(conversationRequestBuilder: requestBuilder) + + // Handle conversation selection - navigate to messages + conversationsController.set(onItemClick: { [weak self] conversation, indexPath in + self?.openMessages(for: conversation) + }) + + // Handle long press for additional options + conversationsController.set(onItemLongClick: { [weak self] conversation, indexPath in + self?.showConversationOptions(for: conversation) + }) + + // Handle errors + conversationsController.set(onError: { error in + print("Conversations error: \(error.errorDescription)") + }) + + // Handle empty state + conversationsController.set(onEmpty: { + print("No conversations found") + }) + + // Handle when conversations are loaded + conversationsController.set(onLoad: { conversations in + print("Loaded \(conversations.count) conversations") + }) + + // Present the conversations + navigationController?.pushViewController(conversationsController, animated: true) + } + + private func openMessages(for conversation: Conversation) { + if let user = conversation.conversationWith as? User { + let messagesVC = CometChatMessages() + messagesVC.set(user: user) + navigationController?.pushViewController(messagesVC, animated: true) + } else if let group = conversation.conversationWith as? Group { + let messagesVC = CometChatMessages() + messagesVC.set(group: group) + navigationController?.pushViewController(messagesVC, animated: true) + } + } + + private func showConversationOptions(for conversation: Conversation) { + let alert = UIAlertController(title: "Options", message: nil, preferredStyle: .actionSheet) + + alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ in + CometChat.deleteConversation( + conversationWith: conversation.conversationWith?.uid ?? "", + conversationType: conversation.conversationType + ) { success in + print("Conversation deleted") + } onError: { error in + print("Delete failed: \(error?.errorDescription ?? "")") + } + }) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + present(alert, animated: true) + } +} ``` - - - +## Filter Conversations -**Instance level styling** +Use `ConversationRequestBuilder` to filter which conversations appear: - - ```swift -var customAvatarStyle = AvatarStyle() -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) -customAvatarStyle.backgroundColor = UIColor(hex: "#F76808") - -let customAvatar = CometChatAvatar() -customAvatar.style = customAvatarStyle -``` - - - - - - - - - -##### 3. StatusIndicator Style - -To apply customized styles to the Status Indicator component in the `Conversations` Component, you can use the following code snippet. For more information, visit [Indicator Styles](/ui-kit/ios/status-indicator). - -**Global level styling** +// Show only one-on-one conversations +let userOnlyBuilder = ConversationRequest.ConversationRequestBuilder(limit: 20) + .set(conversationType: .user) - - -```swift -CometChatStatusIndicator.style.cornerRadius = CometChatCornerStyle(cornerRadius: 8) -CometChatStatusIndicator.style.backgroundColor = UIColor(hex: "#F76808") +let conversations = CometChatConversations(conversationRequestBuilder: userOnlyBuilder) ``` - - - - -**Instance level styling** - - - ```swift -var customStatusIndicatorStyle = StatusIndicatorStyle() -customStatusIndicatorStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) -customStatusIndicatorStyle.backgroundColor = UIColor(hex: "#F76808") +// Show only group conversations +let groupOnlyBuilder = ConversationRequest.ConversationRequestBuilder(limit: 20) + .set(conversationType: .group) -CometChatStatusIndicator.style = customStatusIndicatorStyle +let conversations = CometChatConversations(conversationRequestBuilder: groupOnlyBuilder) ``` - - - - - - - - -##### 4. Badge Style - -To apply customized styles to the `Badge` component in the `Conversations` Component, you can use the following code snippet. For more information, visit [Badge Styles](https://www.cometchat.com/docs/ui-kit/ios/component-styling#badge) - -**Global level styling** - - - ```swift -CometChatBadge.style.backgroundColor = UIColor(hex: "#F44649") -CometChatBadge.style.cornerRadius = CometChatCornerStyle(cornerRadius: 4) -``` - - - - +// Filter by tags +let taggedBuilder = ConversationRequest.ConversationRequestBuilder(limit: 20) + .set(conversationType: .both) + .withTags(true) + .set(tags: ["support", "sales"]) -**Instance level styling** - - - -```swift -let customBadgeStyle = BadgeStyle() -customBadgeStyle.backgroundColor = UIColor(hex: "#F44649") -customBadgeStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 4) - -CometChatBadge.style = customBadgeStyle +let conversations = CometChatConversations(conversationRequestBuilder: taggedBuilder) ``` - - - - - - - - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ---------------------------- | ------------------------------------------ | ------------------------------------- | -| hideErrorView | Hides the error state view. | `hideErrorView = true` | -| hideNavigationBar | Hides or shows the navigation bar. | `hideNavigationBar = true` | -| hideSearch | Hides the search bar. | `hideSearch = true` | -| hideBackButton | Hides the back button. | `hideBackButton = true` | -| hideLoadingState | Hides the loading state indicator. | `hideLoadingState = true` | -| hideReceipts | Hides message read/delivery receipts. | `hideReceipts = true` | -| hideDeleteConversationOption | Hides the option to delete a conversation. | `hideDeleteConversationOption = true` | -| hideUserStatus | Hides the online/offline status of users. | `hideUserStatus = true` | -| hideGroupType | Hides the group type (private/public). | `hideGroupType = true` | - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** +## Actions Reference -#### Date Time Formatter +| Method | Description | Example | +|--------|-------------|---------| +| `set(onItemClick:)` | Triggered when a conversation is tapped | Navigate to messages | +| `set(onItemLongClick:)` | Triggered on long press | Show options menu | +| `set(onBack:)` | Triggered when back button is pressed | Custom navigation | +| `set(onSelection:)` | Triggered in selection mode | Multi-select conversations | +| `set(onError:)` | Triggered when an error occurs | Show error alert | +| `set(onEmpty:)` | Triggered when list is empty | Show empty state | +| `set(onLoad:)` | Triggered when conversations load | Analytics tracking | -The **CometChatConversations** component supports full customization of how date and time are displayed using the [CometChatDateTimeFormatter](/ui-kit/ios/localize#datetimeformatter). +## Styling -This enables developers to localize, format, or personalize the date and time strings shown next to each conversation—such as “Today”, “Yesterday”, “12:45 PM”, etc. +### Quick Styling -1. Component-Level (Global) - - - -```swift -CometChatConversations.dateTimeFormatter.time = { timestamp in - return "at " + DateFormatter.localizedString(from: Date(timeIntervalSince1970: TimeInterval(timestamp)), dateStyle: .none, timeStyle: .short) -} - -CometChatConversations.dateTimeFormatter.today = { timestamp in - return "Today • \(formattedTime(from: timestamp))" -} - -CometChatConversations.dateTimeFormatter.otherDay = { timestamp in // This will display older dates as "24 Apr 2025" instead of the default relative format. - let formatter = DateFormatter() - formatter.dateFormat = "dd MMM yyyy" - return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) -} -``` - - - - - -2. Instance-Level (Local) - - - ```swift let conversations = CometChatConversations() -conversations.dateTimeFormatter.yesterday = { timestamp in - return "Yesterday at " + formattedTime(from: timestamp) -} -``` - +// Apply custom colors +CometChatConversation.style.backgroundColor = .systemBackground +CometChatConversation.style.lastMessageTextColor = .secondaryLabel +CometChatConversation.style.typingIndicatorColor = .systemGreen - +// Custom avatar style +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#6851D6") +avatarStyle.cornerRadius = 8 +CometChatConversation.style.avatarStyle = avatarStyle -##### Available closures - -| Property | Description | Code | -| --------- | ------------------------------------------------------------------- | -------------------------------------------------------------- | -| time | Called to format a timestamp as a standard time (e.g., "12:30 PM"). | `CometChatConversations.dateTimeFormatter.time = { ... }` | -| today | Called when rendering messages sent today. | `CometChatConversations.dateTimeFormatter.today = { ... }` | -| yesterday | Called for yesterday's messages. | `CometChatConversations.dateTimeFormatter.yesterday = { ... }` | -| lastweek | Called for messages within the last week. | `CometChatConversations.dateTimeFormatter.lastweek = { ... }` | -| otherDay | Called for dates older than last week. | `CometChatConversations.dateTimeFormatter.otherDay = { ... }` | -| minute | Called when referring to "a minute ago". | `CometChatConversations.dateTimeFormatter.minute = { ... }` | -| minutes | Called for "x minutes ago". | `CometChatConversations.dateTimeFormatter.minutes = { ... }` | -| hour | Called for "an hour ago". | `CometChatConversations.dateTimeFormatter.hour = { ... }` | -| hours | Called for "x hours ago". | `CometChatConversations.dateTimeFormatter.hours = { ... }` | - -Each closure receives a timestamp (Int, representing UNIX time) and must return a String representing the formatted time. - -*** - -#### SetTextFormatters - -You can modify the text formatters by using .set(textFormatters:). This method accepts an array of CometChatTextFormatter, allowing you to apply multiple text formatters to the conversation text. - - - -cometChatConversations.set(textFormatters: \[CometChatTextFormatter]) - - - - - -*** - -#### SetDatePattern - -You can modify the date pattern to your requirement using .set(datePattern:). This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - - - -```swift -cometChatConversations.set(datePattern: { conversation in - if let time = conversation.lastMessage?.sentAt { - let date = Date(timeIntervalSince1970: TimeInterval(time)) - let dateFormatter = DateFormatter() - dateFormatter.dateFormat = "dd MMM, hh:mm a" - dateFormatter.amSymbol = "AM" - dateFormatter.pmSymbol = "PM" - return dateFormatter.string(from: date) - } - return "" -}) +// Custom badge style for unread count +let badgeStyle = BadgeStyle() +badgeStyle.backgroundColor = UIColor(hex: "#F44649") +badgeStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 10) +CometChatConversation.style.badgeStyle = badgeStyle ``` - +### Style Properties - +| Property | Description | +|----------|-------------| +| `backgroundColor` | Background color of the list | +| `lastMessageTextColor` | Color of the last message preview | +| `typingIndicatorColor` | Color of "typing..." indicator | +| `separatorColor` | Color of row separators | +| `avatarStyle` | Style for user/group avatars | +| `badgeStyle` | Style for unread message count | +| `receiptStyle` | Style for read/delivered receipts | +| `dateStyle` | Style for timestamp labels | -Demonstration +## Hide UI Elements - - - - -*** - -#### SetOptions - -You can define custom options for each conversation using .set(options:). This method allows you to return an array of CometChatConversationOption based on the conversation object. - - - ```swift -cometChatConversations.set(options: { conversation in - return [MuteOption(), DeleteOption()] -}) -``` - - - - - -*** - -#### AddOptions - -You can dynamically add options to conversations using .add(options:). This method lets you return additional CometChatConversationOption elements. - - - -```swift -cometChatConversations.add(options: { conversation in - return [ArchiveOption()] -}) -``` - - - - - -*** - -#### SetCustomSoundForMessages - -You can customize the notification sound for incoming messages using .set(customSoundForMessages:). This method accepts a URL pointing to the audio file. +let conversations = CometChatConversations() - - -```swift -let soundURL = Bundle.main.url(forResource: "notification_sound", withExtension: "mp3") -cometChatConversations.set(customSoundForMessages: soundURL!) +// Hide elements as needed +conversations.hideSearch = true // Hide search bar +conversations.hideReceipts = true // Hide read/delivered receipts +conversations.hideUserStatus = true // Hide online/offline status +conversations.hideGroupType = true // Hide public/private group icons +conversations.hideDeleteConversationOption = true // Hide delete option +conversations.hideNavigationBar = true // Hide navigation bar +conversations.hideBackButton = true // Hide back button ``` - - - +## Custom Views -*** +### Custom List Item -#### SetListItemView +Replace the entire conversation row with your own design: -With this function, you can assign a custom ListItem view to the Conversations Component. - - - ```swift -cometChatConversations.set(listItemView: { conversation in - let customListItem = CustomListItem() - customListItem.set(conversation: conversation) - return customListItem +conversations.set(listItemView: { conversation in + let customView = CustomConversationCell() + customView.configure(with: conversation) + return customView }) ``` - - - - -Demonstration - - - - - -You can create a `CustomListItemView` as a custom `UIView`. Which we will inflate in `setListItemView()` - -```swift swift - -import UIKit -import CometChatUIKitSwift - -class CustomListItem: UIView { - // Initialize UI components - private var profileImageView: CometChatAvatar = { - let imageView = CometChatAvatar(image: UIImage()) - imageView.translatesAutoresizingMaskIntoConstraints = false // Important for manual layout - return imageView - }() - - private var nameLabel: UILabel = { - let label = UILabel() - label.translatesAutoresizingMaskIntoConstraints = false // Important for manual layout - return label - }() - +```swift +// CustomConversationCell.swift +class CustomConversationCell: UIView { + + private let avatarView = CometChatAvatar(image: UIImage()) + private let nameLabel = UILabel() + private let messageLabel = UILabel() + private let timeLabel = UILabel() + private let unreadBadge = UILabel() + override init(frame: CGRect) { super.init(frame: frame) setupUI() } - - required init?(coder aDecoder: NSCoder) { + + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - + private func setupUI() { - addSubview(profileImageView) + avatarView.translatesAutoresizingMaskIntoConstraints = false + nameLabel.translatesAutoresizingMaskIntoConstraints = false + messageLabel.translatesAutoresizingMaskIntoConstraints = false + timeLabel.translatesAutoresizingMaskIntoConstraints = false + unreadBadge.translatesAutoresizingMaskIntoConstraints = false + + nameLabel.font = .systemFont(ofSize: 16, weight: .semibold) + messageLabel.font = .systemFont(ofSize: 14) + messageLabel.textColor = .secondaryLabel + timeLabel.font = .systemFont(ofSize: 12) + timeLabel.textColor = .tertiaryLabel + + unreadBadge.font = .systemFont(ofSize: 12, weight: .bold) + unreadBadge.textColor = .white + unreadBadge.backgroundColor = .systemBlue + unreadBadge.textAlignment = .center + unreadBadge.layer.cornerRadius = 10 + unreadBadge.clipsToBounds = true + + addSubview(avatarView) addSubview(nameLabel) - + addSubview(messageLabel) + addSubview(timeLabel) + addSubview(unreadBadge) + NSLayoutConstraint.activate([ - // Profile image constraints - profileImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), - profileImageView.centerYAnchor.constraint(equalTo: centerYAnchor), - profileImageView.widthAnchor.constraint(equalToConstant: 40), - profileImageView.heightAnchor.constraint(equalToConstant: 40), - - nameLabel.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 8), - nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), - nameLabel.centerYAnchor.constraint(equalTo: centerYAnchor) + avatarView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), + avatarView.centerYAnchor.constraint(equalTo: centerYAnchor), + avatarView.widthAnchor.constraint(equalToConstant: 50), + avatarView.heightAnchor.constraint(equalToConstant: 50), + + nameLabel.leadingAnchor.constraint(equalTo: avatarView.trailingAnchor, constant: 12), + nameLabel.topAnchor.constraint(equalTo: avatarView.topAnchor, constant: 4), + nameLabel.trailingAnchor.constraint(lessThanOrEqualTo: timeLabel.leadingAnchor, constant: -8), + + messageLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor), + messageLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 4), + messageLabel.trailingAnchor.constraint(lessThanOrEqualTo: unreadBadge.leadingAnchor, constant: -8), + + timeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), + timeLabel.topAnchor.constraint(equalTo: nameLabel.topAnchor), + + unreadBadge.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), + unreadBadge.centerYAnchor.constraint(equalTo: messageLabel.centerYAnchor), + unreadBadge.widthAnchor.constraint(greaterThanOrEqualToConstant: 20), + unreadBadge.heightAnchor.constraint(equalToConstant: 20) ]) } - - func set(conversation: Conversation) { + + func configure(with conversation: Conversation) { + var name = "" var avatarURL: String? - if let group = conversation.conversationWith as? Group { - nameLabel.text = group.name - avatarURL = group.icon - } - + if let user = conversation.conversationWith as? User { - nameLabel.text = user.name + name = user.name ?? "" avatarURL = user.avatar + } else if let group = conversation.conversationWith as? Group { + name = group.name ?? "" + avatarURL = group.icon } - - - - - self.profileImageView.setAvatar(avatarUrl: avatarURL, with: nameLabel.text) + + nameLabel.text = name + avatarView.setAvatar(avatarUrl: avatarURL, with: name) + + // Set last message + if let textMessage = conversation.lastMessage as? TextMessage { + messageLabel.text = textMessage.text + } else if conversation.lastMessage is MediaMessage { + messageLabel.text = "📎 Attachment" + } else { + messageLabel.text = "No messages yet" + } + + // Set time + if let sentAt = conversation.lastMessage?.sentAt { + let date = Date(timeIntervalSince1970: TimeInterval(sentAt)) + let formatter = DateFormatter() + formatter.dateFormat = "h:mm a" + timeLabel.text = formatter.string(from: date) + } + + // Set unread count + let unreadCount = conversation.unreadMessageCount + unreadBadge.isHidden = unreadCount == 0 + unreadBadge.text = unreadCount > 99 ? "99+" : "\(unreadCount)" } } ``` -*** - -#### SetLeadingView - -You can modify the leading view of a conversation cell using .set(leadingView:). - - - -```swift -cometChatConversations.set(leadingView: { conversation in - let view = CustomLeadingView() - return view -}) -``` - - +### Custom Subtitle View - +Customize just the subtitle area (below the name): -Demonstration - - - - - -You can create a `CustomLeadingView` as a custom `UIView`. Which we will inflate in `setLeadingView()` - - - ```swift -import UIKit - -class CustomLeadingView: UIView { +conversations.set(subtitleView: { conversation in + let label = UILabel() + label.font = .systemFont(ofSize: 13) + label.textColor = .secondaryLabel - private let chatIcon: UIImageView = { - let imageView = UIImageView() - let config = UIImage.SymbolConfiguration(pointSize: 20, weight: .bold) - imageView.image = UIImage(systemName: "bubble.left.and.bubble.right.fill", withConfiguration: config) - imageView.tintColor = .black - imageView.translatesAutoresizingMaskIntoConstraints = false - return imageView - }() - - init() { - super.init(frame: .zero) - setupUI() - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") + if let textMessage = conversation.lastMessage as? TextMessage { + label.text = textMessage.text + } else if conversation.lastMessage is MediaMessage { + label.text = "📷 Photo" } - private func setupUI() { - backgroundColor = UIColor.purple.withAlphaComponent(0.2) - layer.cornerRadius = 8 - layer.borderWidth = 2 - layer.borderColor = UIColor.orange.cgColor - translatesAutoresizingMaskIntoConstraints = false - - addSubview(chatIcon) - - NSLayoutConstraint.activate([ - chatIcon.centerXAnchor.constraint(equalTo: centerXAnchor), - chatIcon.centerYAnchor.constraint(equalTo: centerYAnchor) - ]) - } -} -``` - - - - - -*** - -#### SetTitleView - -You can customize the title view of a conversation cell using .set(titleView:). - - - -```swift -cometChatConversations.set(titleView: { conversation in - let view = CustomTitleView() - return view -}) + return label +}) ``` - +### Custom Date Format - - -Demonstration - - - - - -You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()` - - - ```swift -import UIKit - -class CustomTitleView: UIView { - - private let avatarImageView: UIView = { - let view = UIView() - view.backgroundColor = UIColor.purple.withAlphaComponent(0.3) - view.layer.cornerRadius = 20 - view.translatesAutoresizingMaskIntoConstraints = false - - let initialsLabel = UILabel() - initialsLabel.text = "GA" - initialsLabel.font = UIFont.boldSystemFont(ofSize: 16) - initialsLabel.textColor = .white - initialsLabel.translatesAutoresizingMaskIntoConstraints = false - - view.addSubview(initialsLabel) - NSLayoutConstraint.activate([ - initialsLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), - initialsLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor) - ]) - - return view - }() - - private let onlineIndicator: UIView = { - let view = UIView() - view.backgroundColor = .green - view.layer.cornerRadius = 5 - view.translatesAutoresizingMaskIntoConstraints = false - return view - }() +conversations.set(datePattern: { conversation in + guard let sentAt = conversation.lastMessage?.sentAt else { return "" } - private let nameLabel: UILabel = { - let label = UILabel() - label.text = "George Alan" - label.font = UIFont.boldSystemFont(ofSize: 14) - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() - - private let statusLabel: UILabel = { - let label = UILabel() - label.text = "📅 In meeting" - label.textColor = .systemBlue - label.font = UIFont.systemFont(ofSize: 14) - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() - - private let timestampLabel: UILabel = { - let label = UILabel() - label.text = "07:35 PM" - label.textColor = .gray - label.font = UIFont.systemFont(ofSize: 12) - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() - - private let messageLabel: UILabel = { - let label = UILabel() - label.text = "I'll take it. Can you ship it?" - label.textColor = .darkGray - label.font = UIFont.systemFont(ofSize: 14) - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() + let date = Date(timeIntervalSince1970: TimeInterval(sentAt)) + let formatter = DateFormatter() - init() { - super.init(frame: .zero) - setupUI() + if Calendar.current.isDateInToday(date) { + formatter.dateFormat = "h:mm a" + } else if Calendar.current.isDateInYesterday(date) { + return "Yesterday" + } else { + formatter.dateFormat = "MMM d" } - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setupUI() { - addSubview(avatarImageView) - addSubview(onlineIndicator) - addSubview(nameLabel) - addSubview(statusLabel) - addSubview(timestampLabel) - addSubview(messageLabel) - - NSLayoutConstraint.activate([ - avatarImageView.leadingAnchor.constraint(equalTo: leadingAnchor), - avatarImageView.topAnchor.constraint(equalTo: topAnchor), - avatarImageView.widthAnchor.constraint(equalToConstant: 40), - avatarImageView.heightAnchor.constraint(equalToConstant: 40), - - onlineIndicator.bottomAnchor.constraint(equalTo: avatarImageView.bottomAnchor, constant: -2), - onlineIndicator.trailingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: -2), - onlineIndicator.widthAnchor.constraint(equalToConstant: 10), - onlineIndicator.heightAnchor.constraint(equalToConstant: 10), - - nameLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 8), - nameLabel.topAnchor.constraint(equalTo: topAnchor), - - statusLabel.leadingAnchor.constraint(equalTo: nameLabel.trailingAnchor, constant: 4), - statusLabel.centerYAnchor.constraint(equalTo: nameLabel.centerYAnchor), - - timestampLabel.trailingAnchor.constraint(equalTo: trailingAnchor), - timestampLabel.topAnchor.constraint(equalTo: topAnchor), - - messageLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor), - messageLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 2), - messageLabel.trailingAnchor.constraint(equalTo: trailingAnchor), - messageLabel.bottomAnchor.constraint(equalTo: bottomAnchor) - ]) - } -} - + return formatter.string(from: date) +}) ``` - - - +## Listen for Events -*** +React to conversation changes in your app: -#### SetTrailView - -You can modify the trailing view of a conversation cell using .set(trailView:). - - - ```swift -cometChatConversations.set(trailView: { conversation in - let view = CustomTrailView() - return view -}) -``` - - - - - -Demonstration - - - - - -You can create a `CustomTrailView` as a custom `UIView`. Which we will inflate in `setTrailView()` - - - -```swift -import UIKit - -class CustomTrailView: UIView { - - private let timeLabel: UILabel = { - let label = UILabel() - label.text = "10" - label.font = UIFont.boldSystemFont(ofSize: 20) - label.textColor = .purple - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() +class MyViewController: UIViewController, CometChatConversationEventListener { - private let subtextLabel: UILabel = { - let label = UILabel() - label.text = "Mins ago" - label.font = UIFont.systemFont(ofSize: 14) - label.textColor = .purple - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() - - init() { - super.init(frame: .zero) - setupUI() + override func viewDidLoad() { + super.viewDidLoad() + CometChatConversationEvents.addListener("my-listener", self) } - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatConversationEvents.removeListener("my-listener") } - private func setupUI() { - backgroundColor = UIColor.purple.withAlphaComponent(0.2) - layer.cornerRadius = 8 - translatesAutoresizingMaskIntoConstraints = false - - addSubview(timeLabel) - addSubview(subtextLabel) - - NSLayoutConstraint.activate([ - timeLabel.centerXAnchor.constraint(equalTo: centerXAnchor), - timeLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8), - - subtextLabel.centerXAnchor.constraint(equalTo: centerXAnchor), - subtextLabel.topAnchor.constraint(equalTo: timeLabel.bottomAnchor, constant: 4), - subtextLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8) - ]) + // Called when a conversation is deleted + func ccConversationDelete(conversation: Conversation) { + print("Conversation deleted: \(conversation.conversationId ?? "")") } } - ``` - - - +## Complete App Example -*** +Here's a full implementation with tab bar integration: -#### SetSubtitleView - -You can customize the subtitle view for each conversation item to meet your requirements - - - ```swift -cometChatConversations.set(subtitleView: { conversation in - let customSubtitleView = CustomSubtitleView() - customSubtitleView.set(conversation: conversation) - return customSubtitleView -}) -``` - - - - - -Demonstration - - - - - -You need to create a `SubtitleView` a custom `UIView` `cocoa touch file` and inflate it in the setSubtitleView apply function. Then, you can define individual actions depending on your requirements. - -* `SubtitleView` file should should appear as follows: - -```swift swift import UIKit import CometChatUIKitSwift import CometChatSDK -class CustomSubtitleView: UIView { - - // MARK: - Properties - private let subtitleLabel: UILabel = { - let label = UILabel() - label.translatesAutoresizingMaskIntoConstraints = false - label.font = UIFont.systemFont(ofSize: 14, weight: .regular) // Customize font - label.textColor = .darkGray // Customize text color - label.numberOfLines = 1 // Single line - label.textAlignment = .left // Align to the left - return label - }() - - // MARK: - Initializers - override init(frame: CGRect) { - super.init(frame: frame) - setupView() - } +class MainTabBarController: UITabBarController { - required init?(coder: NSCoder) { - super.init(coder: coder) - setupView() + override func viewDidLoad() { + super.viewDidLoad() + setupTabs() } - // MARK: - Setup - private func setupView() { - addSubview(subtitleLabel) + private func setupTabs() { + // Conversations Tab + let conversationsVC = ConversationsContainerViewController() + conversationsVC.tabBarItem = UITabBarItem( + title: "Chats", + image: UIImage(systemName: "message"), + selectedImage: UIImage(systemName: "message.fill") + ) - // Constraints - NSLayoutConstraint.activate([ - subtitleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), - subtitleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), - subtitleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 4), - subtitleLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4) - ]) + // Users Tab + let usersVC = UINavigationController(rootViewController: CometChatUsers()) + usersVC.tabBarItem = UITabBarItem( + title: "Users", + image: UIImage(systemName: "person.2"), + selectedImage: UIImage(systemName: "person.2.fill") + ) + + // Groups Tab + let groupsVC = UINavigationController(rootViewController: CometChatGroups()) + groupsVC.tabBarItem = UITabBarItem( + title: "Groups", + image: UIImage(systemName: "person.3"), + selectedImage: UIImage(systemName: "person.3.fill") + ) + + viewControllers = [conversationsVC, usersVC, groupsVC] } +} + +class ConversationsContainerViewController: UINavigationController { - // MARK: - Configuration - func set(conversation: Conversation) { - subtitleLabel.text = conversation.lastMessage + override func viewDidLoad() { + super.viewDidLoad() + + let conversations = CometChatConversations() + + // Navigate to messages on tap + conversations.set(onItemClick: { [weak self] conversation, _ in + let messagesVC = CometChatMessages() + + if let user = conversation.conversationWith as? User { + messagesVC.set(user: user) + } else if let group = conversation.conversationWith as? Group { + messagesVC.set(group: group) + } + + self?.pushViewController(messagesVC, animated: true) + }) + + setViewControllers([conversations], animated: false) } } ``` -*** - -#### SetLoadingView - -You can set a custom loading view using .set(loadingView:). This method accepts a UIView to display while data is being fetched. - - - -```swift -let loadingIndicator = UIActivityIndicatorView(style: .medium) -loadingIndicator.startAnimating() -cometChatConversations.set(loadingView: loadingIndicator) -``` - - - - - -*** - -#### SetErrorView - -You can customize the error view using .set(errorView:). This method accepts a UIView that appears when an error occurs. - - - -```swift -let errorLabel = UILabel() -errorLabel.text = "Something went wrong!" -errorLabel.textColor = .red -cometChatConversations.set(errorView: errorLabel) -``` - - - - - -*** - -#### SetEmptyView - -You can customize the empty state view using .set(emptyView:). This method accepts a UIView that appears when no conversations are available. - - - -```swift -let emptyLabel = UILabel() -emptyLabel.text = "No conversations found" -emptyLabel.textColor = .gray -emptyLabel.textAlignment = .center -cometChatConversations.set(emptyView: emptyLabel) -``` +## Troubleshooting - +| Issue | Solution | +|-------|----------| +| Empty conversation list | Ensure user is logged in and has existing conversations | +| Conversations not updating | Check that real-time listeners are active | +| Navigation not working | Verify `navigationController` is not nil | +| Custom views not appearing | Ensure custom view has proper constraints | - +## Related Components -*** +- [Messages](/ui-kit/ios/message-header) - Display messages in a conversation +- [Users](/ui-kit/ios/users) - List all users to start new conversations +- [Groups](/ui-kit/ios/groups) - List all groups +- [Message Composer](/ui-kit/ios/message-composer) - Send messages diff --git a/ui-kit/ios/core-features.mdx b/ui-kit/ios/core-features.mdx index f8e942813..1f22abf21 100644 --- a/ui-kit/ios/core-features.mdx +++ b/ui-kit/ios/core-features.mdx @@ -1,209 +1,850 @@ --- -title: "Core" +title: "Core Features" +description: "Essential chat features built into CometChat UI Kit for iOS" --- -## Overview - -The UI Kit comprises a variety of components, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. - -Here's how different UI Kit components work together to achieve CometChat's Core features: +CometChat UI Kit provides production-ready components that work together to deliver a complete chat experience. This guide shows how to implement each core feature with copy-paste code examples. ## Instant Messaging -At the heart of CometChat's functionality is the ability to support real-time text messaging. Users can send and receive instant messages, fostering quick and efficient communication. - -| Components | Functionality | -| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [MessageComposer](/ui-kit/ios/message-composer) | [MessageComposer](/ui-kit/ios/message-composer) is a Component that enables users to write and send a variety of messages. | -| [MessageList](/ui-kit/ios/message-list) | [MessageList](/ui-kit/ios/message-list) is a Component that renders a list of messages sent and messages received using [TextBubble](/ui-kit/ios/message-bubble-styling#text-bubble). | - -> [Messages](/ui-kit/ios/message-header) component in CometChat's UI Kit is a comprehensive component that includes both the [MessageComposer](/ui-kit/ios/message-composer) and the [MessageList](/ui-kit/ios/message-list) components. So, if you're looking to implement a messaging feature in your application, using the Messages component would be a straightforward and efficient way to do it. - -## Media Sharing - -Beyond text, CometChat allows users to share various media types within their conversations. This includes images, videos, audio files, and documents, enriching the chat experience and enabling more comprehensive communication. +Send and receive text messages in real-time. -| Components | Functionality | -| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [MessageComposer](/ui-kit/ios/message-composer) | [MessageComposer](/ui-kit/ios/message-composer) is a Component that has ActionSheet, ActionSheet is a menu that appears over the context of the app, providing multiple options for sharing media files. | -| [MessageList](/ui-kit/ios/message-list) | [MessageList](/ui-kit/ios/message-list) is a Component that renders different Media Message bubbles like [Image Bubble](/ui-kit/ios/message-bubble-styling-styling#image-bubble), [File Bubble](/ui-kit/ios/message-bubble-styling-styling), [Audio Bubble](/ui-kit/ios/message-bubble-styling-styling#audio-bubble) [Video Bubble](/ui-kit/ios/message-bubble-styling#video-bubble) | +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ChatViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // For one-on-one chat + let messagesVC = CometChatMessages() + + // Set the user to chat with + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` + +**Components Used:** +- [MessageComposer](/ui-kit/ios/message-composer) - Text input and send button +- [MessageList](/ui-kit/ios/message-list) - Displays sent and received messages +- [Messages](/ui-kit/ios/message-header) - Complete messaging screen (includes both) -> [Messages](/ui-kit/ios/message-header) component in CometChat's UI Kit is a comprehensive component that includes both the [MessageComposer](/ui-kit/ios/message-composer) and the [MessageList](/ui-kit/ios/message-list) components. So, if you're looking to implement a messaging feature in your application, using the Messages component would be a straightforward and efficient way to do it. +## Media Sharing + +Share images, videos, audio files, and documents. + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class MediaChatViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + let messagesVC = CometChatMessages() + + // The message composer automatically includes media sharing options + // Users can tap the attachment button to share: + // - Photos from library + // - Camera capture + // - Documents + // - Audio files + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // Send media programmatically + func sendImage(to receiverUID: String, imageURL: URL) { + let mediaMessage = MediaMessage( + receiverUid: receiverUID, + fileurl: imageURL.absoluteString, + messageType: .image, + receiverType: .user + ) + + CometChat.sendMediaMessage(message: mediaMessage) { message in + print("Image sent successfully") + } onError: { error in + print("Error sending image: \(error?.errorDescription ?? "")") + } + } +} +``` + +**Supported Media Types:** +| Type | Bubble Component | +|------|------------------| +| Images | [Image Bubble](/ui-kit/ios/message-bubble-styling#image-bubble) | +| Videos | [Video Bubble](/ui-kit/ios/message-bubble-styling#video-bubble) | +| Audio | [Audio Bubble](/ui-kit/ios/message-bubble-styling#audio-bubble) | +| Files | [File Bubble](/ui-kit/ios/message-bubble-styling#file-bubble) | ## Read Receipts -CometChat's Read Receipts feature provides visibility into the message status, letting users know when a message has been delivered and read. This brings clarity to the communication and ensures users are informed about the status of their messages. +Show when messages are delivered and read. -| Components | Functionality | -| ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/ios/conversations) | [Conversations](/ui-kit/ios/conversations) is a Component that renders Conversations item List, Conversation item also displays the delivery status of the last message providing users with real-time updates on the status of their messages. | -| [MessageList](/ui-kit/ios/message-list) | [MessageList](/ui-kit/ios/message-list) is a Component that renders different types of Message bubbles, Read Recept status is an integral part of all message bubbles, no matter the type, and provides real-time updates about the status of the message. | -| [MessageInformation](/ui-kit/ios/message-information) | [MessageInformation](/ui-kit/ios/message-information) component provides transparency into the status of each sent message, giving the sender insights into whether their message has been delivered and read. | - +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ReceiptsViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Read receipts are enabled by default + let messagesVC = CometChatMessages() + + // To hide receipts: + // messagesVC.hideReceipts = true + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // View detailed message information + func showMessageInfo(for message: BaseMessage) { + let messageInfo = CometChatMessageInformation() + messageInfo.set(message: message) + navigationController?.pushViewController(messageInfo, animated: true) + } +} +``` + +**Receipt States:** +- ✓ Sent - Message sent to server +- ✓✓ Delivered - Message delivered to recipient's device +- ✓✓ (blue) Read - Recipient has seen the message + +**Components Used:** +- [Conversations](/ui-kit/ios/conversations) - Shows receipt status on last message +- [MessageList](/ui-kit/ios/message-list) - Shows receipts on each message +- [MessageInformation](/ui-kit/ios/message-information) - Detailed delivery/read info ## Mark As Unread -Mark as Unread feature allows users to manually mark messages as unread, helping them keep track of important conversations they want to revisit later. When enabled, the message list can automatically start from the first unread message, making it easier to pick up where you left off. +Let users mark messages as unread to revisit later. -| Components | Functionality | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/ios/message-list) | [Message List](/ui-kit/ios/message-list#functionality) provides the "Mark as unread" option in message actions and supports starting from the first unread message when enabled. | -| [Conversations](/ui-kit/ios/conversations) | [Conversations](/ui-kit/ios/conversations#functionality) component listens to conversation updates and reflects the updated unread count in real-time. | - -## Typing Indicator - -The Typing Indicator feature in CometChat shows when a user is typing a response in real-time, fostering a more interactive and engaging chat environment. This feature enhances the real-time communication experience, making conversations feel more natural and fluid. +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class UnreadMessagesViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + let messagesVC = CometChatMessages() + + // Enable starting from first unread message + messagesVC.scrollToUnreadMessages = true + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // Mark a message as unread programmatically + func markAsUnread(message: BaseMessage) { + CometChat.markAsUnread( + baseMessage: message + ) { _ in + print("Marked as unread") + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` + +## Typing Indicators + +Show when users are typing in real-time. -| Components | Functionality | -| ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/ios/conversations) | [Conversations](/ui-kit/ios/conversations) is a Component that renders Conversations item List, Conversations item also shows real-time typing status indicators. This means that if a user in a one-on-one chat or a participant in a group chat is currently typing a message | -| [Message Header](/ui-kit/ios/message-header) | [Message Header](/ui-kit/ios/message-header) that renders details of User or Groups in ToolBar. The MessageHeader also handles the Typing Indicator functionality. When a user or a member in a group is typing, the MessageHeader dynamically updates to display a 'typing...' status in real-time. | +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class TypingIndicatorViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Typing indicators are enabled by default in: + // - CometChatConversations (shows "typing..." in conversation list) + // - CometChatMessageHeader (shows "typing..." below user name) + + let messagesVC = CometChatMessages() + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // Send typing indicator manually + func startTyping(to receiverUID: String) { + let typingIndicator = TypingIndicator( + receiverID: receiverUID, + receiverType: .user + ) + CometChat.startTyping(indicator: typingIndicator) + } + + func stopTyping(to receiverUID: String) { + let typingIndicator = TypingIndicator( + receiverID: receiverUID, + receiverType: .user + ) + CometChat.endTyping(indicator: typingIndicator) + } +} +``` + +**Components Used:** +- [Conversations](/ui-kit/ios/conversations) - Shows typing in conversation list +- [MessageHeader](/ui-kit/ios/message-header) - Shows typing below user/group name ## User Presence -CometChat's User Presence feature allows users to see whether their contacts are online, offline. This helps users know the best time to initiate a conversation and sets expectations about response times. +Display online/offline status for users. -| Components | Functionality | -| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/ios/conversations) | [Conversations](/ui-kit/ios/conversations) is a Component that renders Conversations item List, Conversations item also shows user presence information. | -| [Message Header](/ui-kit/ios/message-header) | [Message Header](/ui-kit/ios/message-header) that renders details of User or Groups in ToolBar. The MessageHeader also handles user Presence information. | -| [Users](/ui-kit/ios/users) | [Users](/ui-kit/ios/users) renders list of users available in your app.It also responsible to render users Presence information. | -| [Group Members](/ui-kit/ios/group-members) | [Group Members](/ui-kit/ios/group-members) renders list of users available in the group. The Group Members component also handles user Presence information. | +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class PresenceViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // User presence is shown automatically in: + // - CometChatConversations (green dot for online users) + // - CometChatMessageHeader (shows "Online" or "Last seen") + // - CometChatUsers (green dot for online users) + // - CometChatGroupMembers (green dot for online members) + + let conversations = CometChatConversations() + + // To hide user status: + // conversations.hideUserStatus = true + + navigationController?.pushViewController(conversations, animated: true) + } + + // Listen for presence changes + func listenForPresenceChanges() { + CometChat.addUserListener("presence-listener", self) + } +} + +extension PresenceViewController: CometChatUserDelegate { + func onUserOnline(user: User) { + print("\(user.name ?? "") is now online") + } + + func onUserOffline(user: User) { + print("\(user.name ?? "") went offline") + } +} +``` ## Reactions -CometChat's Reactions feature adds a layer of expressiveness to your chat application by allowing users to react to messages. With Reactions, users can convey a range of emotions or express their thoughts on a particular message without typing out a full response, enhancing their user experience and fostering greater engagement. - -The number of reactions displayed depends on the width of the view. For instance, if a message contains 5 reactions but the width of the CometChatReactions view can only accommodate 4 reactions at a time, the first three reactions will be shown along with an additional UI element at the end of the row. This element indicates the number of other unique reactions that are not immediately visible, informing users of the total count of different reactions. - -In the example, tapping on this element (depicted as "+2" in the provided image) will by default trigger the CometChatReactionList component. This action opens a modal sheet from the bottom of the screen, displaying all reactions received by the message. +Let users react to messages with emojis. -| Components | Functionality | -| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [MessageList](/ui-kit/ios/message-list) | [MessageList](/ui-kit/ios/message-list) is a Component that renders different types of Message bubbles, Irrespective of the type of message bubble, Reactions are an integral part and offer a more engaging, expressive way for users to respond to messages. | -| [Messages](/ui-kit/ios/message-header) | [Messages](/ui-kit/ios/message-header) component in CometChat's UI Kit is a comprehensive component that includes both the [MessageComposer](/ui-kit/ios/message-composer) and the [MessageList](/ui-kit/ios/message-list) components. So, if you're looking to implement a messaging feature in your application, using the Messages component would be a straightforward and efficient way to do it. | +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ReactionsViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Reactions are enabled by default + // Users can long-press a message to add reactions + + let messagesVC = CometChatMessages() + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // Add reaction programmatically + func addReaction(to message: BaseMessage, emoji: String) { + CometChat.addReaction( + messageId: message.id, + reaction: emoji + ) { message in + print("Reaction added") + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // Remove reaction + func removeReaction(from message: BaseMessage, emoji: String) { + CometChat.removeReaction( + messageId: message.id, + reaction: emoji + ) { message in + print("Reaction removed") + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` ## Mentions -Mentions is a robust feature provided by CometChat that enhances the interactivity and clarity of group or 1-1 chats by allowing users to directly address or refer to specific individuals in a conversation. +Tag users in messages with @mentions. -| Components | Functionality | -| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/ios/conversations) | [Conversations](/ui-kit/ios/conversations) component provides an enhanced user experience by integrating the Mentions feature. This means that from the conversation list itself, users can see where they or someone else have been specifically mentioned. | -| [MessageComposer](/ui-kit/ios/message-composer) | [MessageComposer](/ui-kit/ios/message-composer)is a component that allows users to craft and send various types of messages, including the usage of the Mentions feature for direct addressing within the conversation. | -| [MessageList](/ui-kit/ios/message-list) | [MessageList](/ui-kit/ios/message-list) is a component that displays a list of sent and received messages. It also supports the rendering of Mentions, enhancing the readability and interactivity of conversations. | -| [Messages](/ui-kit/ios/message-header) | [Messages](/ui-kit/ios/message-header) The component is a comprehensive element in CometChat's UI Kit, encapsulating both the [MessageComposer](/ui-kit/ios/message-composer) and [MessageList](/ui-kit/ios/message-list) components. It fully supports the Mentions feature, providing a streamlined way to implement an interactive and engaging messaging function in your application. | +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class MentionsViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Mentions are enabled by default + // Type @ in the composer to see mention suggestions + + let messagesVC = CometChatMessages() + + CometChat.getGroup(GUID: "group-123") { group in + DispatchQueue.main.async { + messagesVC.set(group: group) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // Send message with mention programmatically + func sendMessageWithMention(to groupID: String, mentionedUser: User) { + let textMessage = TextMessage( + receiverUid: groupID, + text: "Hey @\(mentionedUser.name ?? ""), check this out!", + receiverType: .group + ) + + // Add mentioned users + textMessage.mentionedUsers = [mentionedUser] + + CometChat.sendTextMessage(message: textMessage) { message in + print("Message with mention sent") + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` ## Threaded Conversations -The Threaded Conversations feature enables users to respond directly to a specific message in a chat. This keeps conversations organized and enhances the user experience by maintaining context, especially in group chats. +Reply to specific messages in threads. -| Components | Functionality | -| ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -| [Threaded Messages](/ui-kit/ios/threaded-messages-header) | [Threaded Messages](/ui-kit/ios/threaded-messages-header) that displays all replies made to a particular message in a conversation. | +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ThreadedMessagesViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Threaded messages are enabled by default + // Users can tap "Reply in thread" on any message + + let messagesVC = CometChatMessages() + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // Open thread view for a message + func openThread(for parentMessage: BaseMessage, user: User) { + let threadedMessages = CometChatThreadedMessages() + threadedMessages.set(parentMessage: parentMessage) + threadedMessages.set(user: user) + navigationController?.pushViewController(threadedMessages, animated: true) + } + + // Send reply in thread programmatically + func sendThreadReply(parentMessage: BaseMessage, text: String) { + let reply = TextMessage( + receiverUid: parentMessage.receiverUid, + text: text, + receiverType: parentMessage.receiverType + ) + reply.parentMessageId = parentMessage.id + + CometChat.sendTextMessage(message: reply) { message in + print("Thread reply sent") + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` + +**Component Used:** +- [ThreadedMessages](/ui-kit/ios/threaded-messages-header) - Displays thread replies ## Group Chat -CometChat facilitates Group Chats, allowing users to have conversations with multiple participants simultaneously. This feature is crucial for team collaborations, group discussions, social communities, and more. +Create and manage group conversations. -For a comprehensive understanding and guide on implementing and using the Groups feature in CometChat, you should refer to our detailed guide on [Groups](/ui-kit/ios/groups). - +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class GroupChatViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + showGroupsList() + } + + // Show all groups + func showGroupsList() { + let groups = CometChatGroups() + + groups.set(onItemClick: { [weak self] group, _ in + self?.openGroupChat(group: group) + }) + + navigationController?.pushViewController(groups, animated: true) + } + + // Open chat for a group + func openGroupChat(group: Group) { + let messagesVC = CometChatMessages() + messagesVC.set(group: group) + navigationController?.pushViewController(messagesVC, animated: true) + } + + // Create a new group + func createGroup(name: String, type: CometChat.groupType) { + let group = Group( + guid: UUID().uuidString, + name: name, + groupType: type, + password: nil + ) + + CometChat.createGroup(group: group) { createdGroup in + print("Group created: \(createdGroup.name ?? "")") + DispatchQueue.main.async { + self.openGroupChat(group: createdGroup) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + // Join a public group + func joinGroup(guid: String) { + CometChat.joinGroup( + GUID: guid, + groupType: .public, + password: nil + ) { group in + print("Joined group: \(group.name ?? "")") + DispatchQueue.main.async { + self.openGroupChat(group: group) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` + +**Related Guide:** [Groups](/ui-kit/ios/groups) ## Quoted Reply -Quoted Reply is a robust feature provided by CometChat that enables users to quickly reply to specific messages by selecting the "Reply" option from a message's action menu. This enhances context, keeps conversations organized, and improves overall chat experience in both 1-1 and group chats. +Reply to specific messages with context. -| Components | Functionality | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/android/message-list) | [Message List](/ui-kit/android/message-list) supports replying to messages via the "Reply" option. Users can select "Reply" on a message to open the composer with the quoted reply pre-filled, maintaining context. | -| [Message Composer](/ui-kit/android/message-composer) | [Message Composer](/ui-kit/android/message-composer) works seamlessly with Quoted Message by showing the quoted reply above the input field, letting users compose their response in proper context. | - -## Conversation and Advanced Search - -Conversation and Advanced Search is a powerful feature provided by CometChat that 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. +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class QuotedReplyViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Quoted reply is enabled by default + // Users can swipe right on a message or tap "Reply" in message actions + + let messagesVC = CometChatMessages() + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` + +## Search + +Search across conversations and messages. -| Components | Functionality | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Search](/ui-kit/ios/search) | [Search](/ui-kit/ios/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. | -| [Message Header](/ui-kit/ios/message-header) | [Message Header](/ui-kit/ios/message-header) shows the search button in the chat header, allowing users to search within a conversation. | -| [Message List](/ui-kit/ios/message-list) | [Message List](/ui-kit/ios/message-list) shows the selected message when clicked from search results and highlights it in the message list. | -| [Conversations](/ui-kit/ios/conversations) | [Conversations](/ui-kit/ios/conversations) displays the search input. | - +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class SearchViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Search is available in: + // - CometChatConversations (search bar at top) + // - CometChatMessageHeader (search button) + + let conversations = CometChatConversations() + + // Search is enabled by default + // To hide search: + // conversations.hideSearch = true + + navigationController?.pushViewController(conversations, animated: true) + } + + // Open dedicated search screen + func openSearch() { + let search = CometChatSearch() + navigationController?.pushViewController(search, animated: true) + } +} +``` + +**Components Used:** +- [Search](/ui-kit/ios/search) - Dedicated search screen +- [MessageHeader](/ui-kit/ios/message-header) - Search within conversation +- [Conversations](/ui-kit/ios/conversations) - Search conversations ## Moderation -CometChat's Message Moderation feature helps maintain a safe and respectful chat environment by automatically filtering and managing inappropriate content. Messages can be automatically blocked or flagged based on predefined rules, ensuring harmful content is handled before it reaches users. +Automatically filter inappropriate content. +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ModerationViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Moderation is handled automatically based on your + // CometChat dashboard settings + + // Blocked messages are displayed appropriately + // based on your moderation rules + + let messagesVC = CometChatMessages() + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` + -Learn more about setting up moderation rules and managing content in the [Moderation](/moderation/overview) documentation. +Configure moderation rules in your [CometChat Dashboard](/moderation/overview). -| Components | Functionality | -| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/ios/message-list) | [Message List](/ui-kit/ios/message-list) automatically handles moderated messages, displaying blocked content appropriately based on your moderation settings. | - -After implementing moderation rules, users can report messages they find inappropriate or harmful. As a next step, you can enable the **[Report Message](#report-message)** feature to allow users to flag messages for review by moderators. - ## Report Message -The Report Message feature allows users to report inappropriate or harmful messages within the chat. Users can choose from predefined reasons and provide additional remarks for detailed context. This feature helps maintain a safe and respectful chat environment. - - -Learn more about how flagged messages are handled, reviewed, and moderated in the [Flagged Messages](/moderation/flagged-messages) documentation. - +Allow users to report inappropriate messages. -| Components | Functionality | -| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/android/message-list) | [Message List](/ui-kit/android/message-list) provides the "Report Message" option in the message actions menu, allowing users to initiate the reporting process for inappropriate messages. | +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ReportMessageViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Report message is available in message actions + // Users can long-press a message and select "Report" + + let messagesVC = CometChatMessages() + + CometChat.getUser(UID: "user-123") { user in + DispatchQueue.main.async { + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` + + +View and manage reported messages in [Flagged Messages](/moderation/flagged-messages). + + +## Complete Chat App Example + +Here's a production-ready implementation combining all core features: + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +@main +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + + // Initialize CometChat + let uiKitSettings = UIKitSettings() + .set(appID: "YOUR_APP_ID") + .set(authKey: "YOUR_AUTH_KEY") + .set(region: "YOUR_REGION") + .build() + + CometChatUIKit.init(uiKitSettings: uiKitSettings) { result in + switch result { + case .success: + self.loginAndShowChat() + case .failure(let error): + print("Init failed: \(error.localizedDescription)") + } + } + + return true + } + + private func loginAndShowChat() { + CometChatUIKit.login(uid: "user-123") { result in + switch result { + case .success(let user): + print("Logged in as: \(user.name ?? "")") + DispatchQueue.main.async { + self.showMainScreen() + } + case .failure(let error): + print("Login failed: \(error.localizedDescription)") + } + } + } + + private func showMainScreen() { + let tabBar = MainTabBarController() + window?.rootViewController = tabBar + window?.makeKeyAndVisible() + } +} + +class MainTabBarController: UITabBarController { + + override func viewDidLoad() { + super.viewDidLoad() + + // Conversations Tab + let conversationsNav = UINavigationController() + let conversations = CometChatConversations() + conversations.set(onItemClick: { [weak conversationsNav] conversation, _ in + let messagesVC = CometChatMessages() + if let user = conversation.conversationWith as? User { + messagesVC.set(user: user) + } else if let group = conversation.conversationWith as? Group { + messagesVC.set(group: group) + } + conversationsNav?.pushViewController(messagesVC, animated: true) + }) + conversationsNav.setViewControllers([conversations], animated: false) + conversationsNav.tabBarItem = UITabBarItem( + title: "Chats", + image: UIImage(systemName: "message"), + selectedImage: UIImage(systemName: "message.fill") + ) + + // Users Tab + let usersNav = UINavigationController() + let users = CometChatUsers() + users.set(onItemClick: { [weak usersNav] user, _ in + let messagesVC = CometChatMessages() + messagesVC.set(user: user) + usersNav?.pushViewController(messagesVC, animated: true) + }) + usersNav.setViewControllers([users], animated: false) + usersNav.tabBarItem = UITabBarItem( + title: "Users", + image: UIImage(systemName: "person.2"), + selectedImage: UIImage(systemName: "person.2.fill") + ) + + // Groups Tab + let groupsNav = UINavigationController() + let groups = CometChatGroups() + groups.set(onItemClick: { [weak groupsNav] group, _ in + let messagesVC = CometChatMessages() + messagesVC.set(group: group) + groupsNav?.pushViewController(messagesVC, animated: true) + }) + groupsNav.setViewControllers([groups], animated: false) + groupsNav.tabBarItem = UITabBarItem( + title: "Groups", + image: UIImage(systemName: "person.3"), + selectedImage: UIImage(systemName: "person.3.fill") + ) + + viewControllers = [conversationsNav, usersNav, groupsNav] + } +} +``` + +## Feature Summary + +| Feature | Component | Enabled by Default | +|---------|-----------|-------------------| +| Text Messaging | [Messages](/ui-kit/ios/message-header) | ✅ | +| Media Sharing | [MessageComposer](/ui-kit/ios/message-composer) | ✅ | +| Read Receipts | [MessageList](/ui-kit/ios/message-list) | ✅ | +| Typing Indicators | [MessageHeader](/ui-kit/ios/message-header) | ✅ | +| User Presence | [Conversations](/ui-kit/ios/conversations) | ✅ | +| Reactions | [MessageList](/ui-kit/ios/message-list) | ✅ | +| Mentions | [MessageComposer](/ui-kit/ios/message-composer) | ✅ | +| Threads | [ThreadedMessages](/ui-kit/ios/threaded-messages-header) | ✅ | +| Search | [Search](/ui-kit/ios/search) | ✅ | +| Moderation | Dashboard Config | Configure in Dashboard | diff --git a/ui-kit/ios/events.mdx b/ui-kit/ios/events.mdx index ccdfc705d..a47d9739c 100644 --- a/ui-kit/ios/events.mdx +++ b/ui-kit/ios/events.mdx @@ -1,1462 +1,718 @@ --- title: "Events" +description: "Listen and respond to user actions and state changes in CometChat UI Kit" --- -## Overview +Events allow different parts of your app to communicate without direct dependencies. When a user performs an action (like blocking someone, deleting a conversation, or sending a message), events are emitted so other components can react accordingly. -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. +## How Events Work -Both Components and Composite Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. +1. **Subscribe** to events using `addListener` in `viewDidLoad` +2. **React** to events in your listener callback methods +3. **Unsubscribe** using `removeListener` in `viewWillDisappear` -## User Events - -CometChatUserEvents emits events when the logged-in user executes some action on another user - -It contains the following properties and methods - -### observer - -This is a List of Dictionary that contains components listening to user events in key value pairs - -### Type - -`[String: CometChatUserEventListener]()` - -*** - -### addListener - -this method stores the passed listenerClass against the passed id in the usersListener. - -### Signature - -### Uses - - - -```swift -addListener(_ id: String,_ observer: CometChatUserEventListener) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | -------------------------- | -------------------------------------- | -| id | String | the key to store the component against | -| observer | CometChatUserEventListener | the component listening to user events | - -*** - -### removeListener - -this method removes the entry with the passed id from the usersListener. - -### Signature - - - -```swift -removeListener(_ id: String) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ------ | ------------------------------ | -| id | String | the key of the entry to remove | - -*** - -### onUserBlock - -This method is used to perform some task when the logged-in user has blocked a user - -### Signature - - - ```swift -onUserBlock(user: User) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ---- | ------------------------------ | -| user | User | the user that has been blocked | - -*** - -### onUserUnblock - -This method is used to perform some task when the logged-in user has unblocked a blocked user. - -### Signature - - - -```swift -onUserUnblock(user: User) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ---- | -------------------------------- | -| user | User | the user that has been unblocked | - -### Return Type - -`void` - -### Emitting User Events - -There are two types of user event listeners, one is for the SDK, which listens for events emitted from the backend for actions taken by users other than the logged in user and second, the events specific to the UI Kit which listens for events emitted from the client side for actions made by the logged-in user. The code snippets shared below contains how to emit such client-side user events to inform other UI components in your project that a user has been blocked or unblocked, the methods being used are static and hence they can be called without having to create an instance of CometChatUserEvents class. - - - -```swift -//pass the [User] object of the user which has been blocked by the logged in user - CometChatUserEvents.emitOnUserBlock(user: User) - -//pass the [User] object of the user which has been unblocked by the logged in user - CometChatUserEvents.emitOnUserUnblock(user: User) -``` - - - - - -*** - -### Listening to User Events - -Here we will go through how anyone can listen to these client-side User Events to update the state of the UI accordingly. - -| Events | Description | -| ----------------- | --------------------------------------------------------------------- | -| `onUserBlocked` | This will get triggered when the logged in user blocks another user | -| `onUserUnblocked` | This will get triggered when the logged in user unblocks another user | - - - -```swift -// View controller from your project where you want to listen events. -public class ViewController: UIViewController { - - public override func viewDidLoad() { - super.viewDidLoad() - - // Subscribing for the listener to listen events from user module - CometChatUserEvents.addListener("UNIQUE_ID", self as CometChatUserEventListener) - } - - public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from user module - CometChatUserEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") - } - - -} - - // Listener events from user module -extension ViewController: CometChatUserEventListener { - - func onUserBlock(user: User) { - // Do Stuff - } - - func onUserUnblock(user: User) { - // Do Stuff - } -} -``` - - - - - -## Group Events - -CometChatGroupEvents emits events when the logged-in user executes some action on a group or group member - -It contains the following properties and methods: - -### observer - -This is a List of Dictionary that contains components listening to group events in key value pairs - -### Type - -`[String: CometChatGroupEventListener]()` - -*** - -### addListener - -this method stores the passed listenerClass against the passed listenerId in the observer. - -### Signature - - - -```swift -addListener(_ id: String,_ observer: CometChatGroupEventListener) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | --------------------------- | --------------------------------------- | -| id | String | the key to store the component against | -| observer | CometChatGroupEventListener | the component listening to group events | - -*** - -### removeListener - -this method removes the entry with the passed listenerId from the observer. - -### Signature - - - -```swift -removeListener(_ id: String) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ------ | ------------------------------ | -| id | String | the key of the entry to remove | - -*** - -### onGroupCreate - -This method is used to perform some task when the logged-in user has created a group - -### Signature - - - -```swift -onGroupCreate(group: Group) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ----- | ----------------------------------- | -| group | Group | the new group that has been created | - -*** - -### onCreateGroupClick - -This method is used to perform some task when the logged-in user click on Create group button - -### Signature - - - -```swift -onCreateGroupClick() -``` - - - - - -*** - -### onGroupDelete - -This method is used to perform some task when the logged-in user has deleted a group. - -### Signature - - - -```swift -onGroupDelete(group: Group) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ----- | ------------------------------- | -| group | Group | the group that has been deleted | - -*** - -### onGroupMemberLeave - -This method is used to perform some task when the logged-in user has left a group. - -### Signature - - - -```swift -onGroupMemberLeave(leftUser: User, leftGroup: Group) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ----- | --------------------------------------------- | -| leftUser | User | the user that has left the group | -| leftGroup | Group | the group from which the logged-user has left | - -*** - -### onGroupMemberChangeScope - -This method is used to perform some task when the logged-in user has changed the scope of a member of a group. - -### Signature - - - -```swift -onGroupMemberChangeScope(updatedBy: User , updatedUser: User , scopeChangedTo: CometChat.MemberScope , scopeChangedFrom: CometChat.MemberScope, group: Group) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------------- | ------ | -------------------------------------------------- | -| updatedBy | User | the user who changed the scope of group member | -| updatedUser | User | the user whose scope has been changed | -| scopeChangedTo | String | the new scope | -| scopeChangedFrom | String | the old scope | -| group | Group | the group from where the scope change has occurred | - -*** - -### onGroupMemberBan - -This method is used to perform some task when the logged-in user has banned a user from the group. - -### Signature - - - -```swift -onGroupMemberBan(bannedUser: User, bannedGroup: Group, bannedBy: User) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ----- | --------------------------------------------- | -| bannedUser | User | the user that has been banned | -| bannedBy | User | the user who has banned | -| bannedFrom | Group | the group from which the user has been banned | - -*** - -### onGroupMemberKick - -This method is used to perform some task when the logged-in user has kicked a user from the group. - -### Signature - - - -```swift -onGroupMemberKick(kickedUser: User, kickedGroup: Group, kickedBy: User) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ----------- | ----- | --------------------------------------------- | -| kickedUser | User | the banned user that has been kicked | -| kickedBy | User | the user who has kicked | -| kickedGroup | Group | the group from which the user has been kicked | - -*** - -### onGroupMemberUnban - -This method is used to perform some task when the logged-in user has unbanned a banned user from a group. - -### Signature - - - -```swift -onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group, unbannedBy: User) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ------------ | ----- | ------------------------------------------------------ | -| unbannedUser | User | the banned user that has been unbanned | -| unbannedBy | User | the user who has unbanned | -| unbannedFrom | Group | the group from which the banned user has been unbanned | - -*** - -### onGroupMemberJoin - -This method is used to perform some task when the logged-in user has joined a group. - -### Signature - - - -```swift -onGroupMemberJoin(joinedUser: User, joinedGroup: Group) -``` - - - - - -### Parameters +import UIKit +import CometChatUIKitSwift +import CometChatSDK -| Parameters | Type | Description | -| ----------- | ----- | -------------------------------------- | -| joinedUser | User | the user that has been unblocked | -| joinedGroup | Group | the group the users have been added to | - -*** - -### onGroupMemberAdd - -This method is used to perform some task when the logged-in user has added new members to the group - -### Signature - - - -```swift -onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ----------- | ---------------------------------------- | -| members | List\ | the list of users added | -| group | Group | the group the users have been added to | -| addedBy | User | the user who has added those new members | - -*** - -### onOwnershipChange - -This method is used to perform some task when the logged-in user has transferred their ownership of a group. - -### Signature - - - -```swift -onOwnershipChange(group: Group?, member: GroupMember?) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ----------- | ----------------------------------------------------- | -| group | Group | the group where the ownership has been changed | -| member | GroupMember | the group member who has been made owner of the group | - -*** - -### Emitting Group Events - -There are two types of group event listeners, one is for the SDK, which listens for events emitted from the backend for actions taken by users other than the logged in user and second, the events specific to the UI Kit which listens for events emitted from the client side for actions made by the logged-in user. The code snippets shared below contains how to emit such client-side group events to inform other UI components in a project that a group has been created or deleted or new members have been added to the group, the logged in user themselves have joined a group, members being banned by the logged in user or the change of ownership or scope of a group member, the methods being used are static and hence they can be called without having to create an instance of CometChatGroupEvents class. - - - -```swift -//you need to pass the [Group] object of the group which is created -CometChatGroupEvents.emitOnGroupCreate(group: Group) - -//you need to pass the [Group] object of the group which is deleted -CometChatGroupEvents.emitOnGroupDelete(group: Group) - -//emit this when logged in user leaves the group. -CometChatGroupEvents.emitOnGroupMemberLeave(leftUser: User, leftGroup: Group) - -//emit this when group member's scope is changed by logged in user. -CometChatGroupEvents.emitOnGroupMemberChangeScope(updatedBy: User , updatedUser: User , scopeChangedTo: CometChat.MemberScope , scopeChangedFrom: CometChat.MemberScope, group: Group) - -//emit this when group member is banned from the group by logged in user. -CometChatGroupEvents.emitOnGroupMemberBan(bannedUser: User, bannedGroup: Group, bannedBy: User) - -//emit this when group member is kicked from the group by logged in user. -CometChatGroupEvents.emitOnGroupMemberKick(kickedUser: User, kickedGroup: Group, kickedBy: User) - -//emit this when a banned group member is unbanned from group by logged in user. -CometChatGroupEvents.emitOnGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group, unbannedBy: User) - -//emit this when logged in user has joined a group successfully. -CometChatGroupEvents.emitOnGroupMemberJoin(joinedUser: User, joinedGroup: Group) - -//emit this when members are added to a group by the logged in user. -CometChatGroupEvents.emitOnGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) - -//emit this when ownership is changed by logged in user. -CometChatGroupEvents.emitOnGroupMemberChangeScope(updatedBy: User , updatedUser: User , scopeChangedTo: CometChat.MemberScope , scopeChangedFrom: CometChat.MemberScope, group: Group) -``` - - - - - -*** - -### Listening to Group Events - -Here we will go through how anyone can listen to these client-side Group Events to update the state of the UI accordingly. - -| Events | Description | -| -------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `onGroupCreate` | This will get triggered when the logged in user creates a group | -| `onGroupDelete` | This will get triggered when the logged in user deletes a group | -| `onGroupMemberLeave` | This will get triggered when the logged in user leaves a group | -| `onGroupMemberChangeScope` | This will get triggered when the logged in user changes the scope of another group member | -| `onGroupMemberBan` | This will get triggered when the logged in user bans a group member from the group | -| `onGroupMemberKick` | This will get triggered when the logged in user kicks another group member from the group | -| `onGroupMemberUnban` | This will get triggered when the logged in user unbans a user banned from the group | -| `onGroupMemberJoin` | This will get triggered when the logged in user joins a group | -| `onGroupMemberAdd` | This will get triggered when the logged in user add new members to the group | -| `onOwnershipChange` | This will get triggered when the logged in user transfer the ownership of their group to some other member | - - - -```swift -// View controller from your project where you want to listen events. -public class ViewController: UIViewController { - - public override func viewDidLoad() { +class MyViewController: UIViewController { + + private let listenerId = "my-unique-listener" + + override func viewDidLoad() { super.viewDidLoad() - - // Subscribing for the listener to listen events from user module - CometChatGroupEvents.addListener("UNIQUE_ID", self as CometChatGroupEventListener) - } - - public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from user module - CometChatGroupEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") - } - - -} - - // Listener events from groups module -extension ViewController: CometChatGroupEventListener { - - public func onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) { - // Do Stuff - } - - public func onCreateGroupClick() { - // Do Stuff - } - - public func onGroupCreate(group: Group) { - // Do Stuff - } - - public func onGroupDelete(group: Group) { - // Do Stuff - } - - public func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { - // Do Stuff - } - - public func onGroupMemberLeave(leftUser: User, leftGroup: Group) { - // Do Stuff + + // Subscribe to events + CometChatUserEvents.addListener(listenerId, self) + CometChatGroupEvents.addListener(listenerId, self) + CometChatConversationEvents.addListener(listenerId, self) + CometChatMessageEvents.addListener(listenerId, self) + CometChatCallEvents.addListener(listenerId, self) } - - public func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { - // Do Stuff - } - - public func onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group) { - // Do Stuff - } - - public func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { - // Do Stuff - } - - public func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { - // Do Stuff - } - - public func onOwnershipChange(group: Group?, member: GroupMember?) { - // Do Stuff + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + + // Unsubscribe to prevent memory leaks + CometChatUserEvents.removeListener(listenerId) + CometChatGroupEvents.removeListener(listenerId) + CometChatConversationEvents.removeListener(listenerId) + CometChatMessageEvents.removeListener(listenerId) + CometChatCallEvents.removeListener(listenerId) } } ``` - - - - -## Conversation Events - -CometChatConversationEvents emits events when the logged-in user executes some action on a conversation object - -It contains the following properties and methods: - -* `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. -* `ccUpdateConversation`: Triggered when there is an update in the conversation. - -### observer - -This is a List of Dictionary that contains components listening to user events in key value pairs - -### Type - -`[String: CometChatConversationEventListener]()` - -*** - -### addListener - -this method stores the passed listenerClass against the passed listenerId in the observer. - -### Signature - - - -```swift -addListener(_ id: String, _ observer: CometChatConversationEventListener) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | --------------------------- | ---------------------------------------------- | -| id | String | the key to store the component against | -| observer | CometChatConversationEvents | the component listening to conversation events | - -*** - -### removeListener - -this method removes the entry with the passed id from the observer. - -### Signature - - - -```swift -removeListener(_ id: String) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ------ | ------------------------------ | -| id | String | the key of the entry to remove | - -### Return Type - -`void` - -*** - -### Parameters - -| Parameters | Type | Description | -| ------------ | ------------ | ------------------------------ | -| conversation | Conversation | the user that has been deleted | - -*** - -### Emitting Conversation Events +## User Events -Here we will go through how to emit events specific to the UI Kit which listens for events emitted from the client side for actions made by the logged-in user. The code snippets shared below contains how to emit such client-side conversation events to inform other UI components in a project that a conversation has been deleted, the methods being used are static and hence they can be called without having to create an instance of CometChatConversationEvents class. +Listen for user-related actions like blocking and unblocking. - - ```swift -//pass the conversation object you want to delete -CometChatConversationEvents.ccConversationDelete(conversation: Conversation) -CometChatConversationEvents.ccUpdateConversation(conversation: Conversation) -``` - - - - +import UIKit +import CometChatUIKitSwift +import CometChatSDK -*** - -### Listening to Conversation Events - -Here we will go through how anyone can listen to these client-side Conversation Events to update the state of the UI accordingly. - -| Event | Description | -| ---------------------- | --------------------------------------------------------------------------- | -| `onConversationDelete` | This event will be triggered when the logged in user deletes a conversation | -| `ccUpdateConversation` | This event will be triggered when the logged in user updates a conversation | - - - - -```swift -// View controller from your project where you want to listen events. -public class ViewController: UIViewController { - public override func viewDidLoad() { +class UserEventsViewController: UIViewController { + + override func viewDidLoad() { super.viewDidLoad() - - // Subscribing for the listener to listen events from conversation module - CometChatConversationEvents.addListener("UNIQUE_ID", self as CometChatConversationEventListener) + CometChatUserEvents.addListener("user-listener", self) } - - public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from conversation module - CometChatConversationEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatUserEvents.removeListener("user-listener") } } - // Listener events from conversation module -extension ViewController: CometChatConversationEventListener { +extension UserEventsViewController: CometChatUserEventListener { - func ccConversationDeleted(conversation: Conversation) { - // Do stuff + func onUserBlock(user: User) { + print("Blocked: \(user.name ?? "")") + // Update UI - hide user from lists, disable messaging } - func ccUpdateConversation(conversation: Conversation) { - // Do stuff + func onUserUnblock(user: User) { + print("Unblocked: \(user.name ?? "")") + // Update UI - show user in lists, enable messaging } } ``` - - - - -## Message Events - -CometChatMessageEvents emits events when the logged-in user executes some action involving any message object. - -It contains the following properties and methods: - -### observer - -This is a List of Dictionary that contains components listening to message events in key value pairs - -### Type - -`[String: CometChatMessageEventListener]()` - -*** - -### addListener - -this method stores the passed listenerClass against the passed id in the observer. - -### Signature - - - -```swift -addListener(_ id: String,_ observer: CometChatMessageEventListener) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ----------------------------- | ----------------------------------------- | -| id | String | the key to store the component against | -| observer | CometChatMessageEventListener | the component listening to message events | - -*** - -### removeListener - -this method removes the entry with the passed id from the observer. - -### Signature - - - -```swift -removeListener(_ id: String) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ------ | ------------------------------ | -| id | String | the key of the entry to remove | - -*** - -### onMessageSent - -This method is used to perform some task when the logged-in user has sent a message - -### Signature - - - -```swift -onMessageSent(message: BaseMessage, status: MessageStatus) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ------------- | ------------- | -------------------------------------------------------------------- | -| message | BaseMessage | the message that has been sent | -| messageStatus | MessageStatus | the status of the message, it can be `inProgress`, `sent` or `error` | - -*** - -### onMessageEdit - -This method is used to perform some task when the logged-in user has edited a message - -### Signature - - - -```swift -onMessageEdit(message: BaseMessage, status: MessageStatus) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ------------- | ----------------- | -------------------------------------------------------------- | -| message | BaseMessage | the message that has been sent | -| messageStatus | MessageEditStatus | the status of the message, it can be `inProgress` or `success` | - -*** - -### onMessageDelete - -This method is used to perform some task when the logged-in user has deleted a message - -### Signature - - - -```swift -onMessageDelete(message: BaseMessage) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ------------- | ----------- | -------------------------------------------------------------- | -| message | BaseMessage | the message that has been sent | -| messageStatus | EventStatus | the status of the message, it can be `inProgress` or `success` | - -*** - -### onMessageRead - -This method is used to perform some task when the logged-in user has read a message - -### Signature - - - -```swift -onMessageRead(message: BaseMessage) -``` - - - - - -### Parameters - -| Parameters | Type | Description | -| ---------- | ----------- | ------------------------------ | -| message | BaseMessage | the message that has been read | - -*** - -### onLiveReaction - -This method is used to perform some task when the logged-in user has a sent a transient message +### Emit User Events -### Signature +Notify other components when you block/unblock a user: - - ```swift -onLiveReaction(reaction: TransientMessage) +// After blocking a user +CometChatUserEvents.emitOnUserBlock(user: blockedUser) + +// After unblocking a user +CometChatUserEvents.emitOnUserUnblock(user: unblockedUser) ``` - +### User Events Reference + +| Event | Description | +|-------|-------------| +| `onUserBlock` | User was blocked by logged-in user | +| `onUserUnblock` | User was unblocked by logged-in user | - +## Group Events -### Parameters +Listen for group-related actions like creating groups, adding members, and role changes. -| Parameters | Type | Description | -| ---------- | ---------------- | -------------------------------------- | -| reaction | TransientMessage | the image to send as transient message | +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK -*** +class GroupEventsViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + CometChatGroupEvents.addListener("group-listener", self) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatGroupEvents.removeListener("group-listener") + } +} -### onViewInformation +extension GroupEventsViewController: CometChatGroupEventListener { + + // Group lifecycle + func onGroupCreate(group: Group) { + print("Group created: \(group.name ?? "")") + } + + func onGroupDelete(group: Group) { + print("Group deleted: \(group.name ?? "")") + } + + func onCreateGroupClick() { + print("Create group button tapped") + } + + // Member join/leave + func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { + print("\(joinedUser.name ?? "") joined \(joinedGroup.name ?? "")") + } + + func onGroupMemberLeave(leftUser: User, leftGroup: Group) { + print("\(leftUser.name ?? "") left \(leftGroup.name ?? "")") + } + + func onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) { + print("\(members.count) members added to \(group.name ?? "")") + } + + // Moderation + func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { + print("\(kickedUser.name ?? "") kicked from \(kickedGroup.name ?? "")") + } + + func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { + print("\(bannedUser.name ?? "") banned from \(bannedGroup.name ?? "")") + } + + func onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group) { + print("\(unbannedUserUser.name ?? "") unbanned") + } + + // Role changes + func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { + print("\(updatedUser.name ?? "") role: \(scopeChangedFrom) → \(scopeChangedTo)") + } + + func onOwnershipChange(group: Group?, member: GroupMember?) { + print("Ownership transferred to \(member?.name ?? "")") + } +} +``` -This method is used to perform some task when the logged-in user click on detail button. +### Emit Group Events -### Signature +Notify other components about group actions: - - ```swift -onViewInformation(group: Group) -``` +// Group created +CometChatGroupEvents.emitOnGroupCreate(group: newGroup) - +// Group deleted +CometChatGroupEvents.emitOnGroupDelete(group: deletedGroup) - +// Member joined +CometChatGroupEvents.emitOnGroupMemberJoin(joinedUser: user, joinedGroup: group) -| Parameters | Type | Description | -| ---------- | ----- | -------------------------------------------------- | -| group | Group | the group for which the information has been shown | +// Member left +CometChatGroupEvents.emitOnGroupMemberLeave(leftUser: user, leftGroup: group) -*** +// Members added +CometChatGroupEvents.emitOnGroupMemberAdd(group: group, members: newMembers, addedBy: currentUser) -### onParentMessageUpdate +// Member kicked +CometChatGroupEvents.emitOnGroupMemberKick(kickedUser: user, kickedGroup: group, kickedBy: admin) -This method is used to perform some task when the logged-in user updates a message that has replies. +// Member banned +CometChatGroupEvents.emitOnGroupMemberBan(bannedUser: user, bannedGroup: group, bannedBy: admin) -### Signature +// Member unbanned +CometChatGroupEvents.emitOnGroupMemberUnban(unbannedUserUser: user, unbannedUserGroup: group, unbannedBy: admin) - - -```swift -onParentMessageUpdate(message: BaseMessage) +// Role changed +CometChatGroupEvents.emitOnGroupMemberChangeScope( + updatedBy: admin, + updatedUser: member, + scopeChangedTo: .admin, + scopeChangedFrom: .participant, + group: group +) ``` - +### Group Events Reference - +| Event | Description | +|-------|-------------| +| `onGroupCreate` | New group created | +| `onGroupDelete` | Group deleted | +| `onCreateGroupClick` | Create group button tapped | +| `onGroupMemberJoin` | User joined a group | +| `onGroupMemberLeave` | User left a group | +| `onGroupMemberAdd` | Members added to group | +| `onGroupMemberKick` | Member kicked from group | +| `onGroupMemberBan` | Member banned from group | +| `onGroupMemberUnban` | Member unbanned | +| `onGroupMemberChangeScope` | Member role changed | +| `onOwnershipChange` | Group ownership transferred | -| Parameters | Type | Description | -| ---------- | ----------- | --------------------------------- | -| message | BaseMessage | the message that has been updated | - -*** - -### Emitting Message Events +## Conversation Events -There are two types of message event listeners, one is for the SDK, which listens for events emitted from the backend for actions taken by users other than the logged in user; and second, the events specific to the UI Kit which listens for events emitted from the client side for actions made by the logged-in user. The code snippets shared below contains how to emit such client-side message events to inform other UI components in a project. +Listen for conversation-level actions like delete and update. - - ```swift -//emit this when the logged in user has sent a message. Pass the object of the [TextMessage], [MediaMessage] or [CustomMessage] being sent and the [MessageStatus] if [inProgress], [sent] successfully or failed with [error]*_ -CometChatMessageEvents.emitOnMessageSent(message: BaseMessage, status: MessageStatus) - -//emit this for when a message is edited by logged-in user. Pass the object of the [TextMessage], [MediaMessage] or [CustomMessage] being edited and the [MessageEditStatus] if [inProgress] or [success]*_ -CometChatMessageEvents.emitOnMessageEdit(message: BaseMessage, status: MessageStatus) +import UIKit +import CometChatUIKitSwift +import CometChatSDK -//emit this when a message is being deleted by logged-in user. Pass the object of the [TextMessage], [MediaMessage] or [CustomMessage] being deleted and also pass the [EventStatus] if [inProgress] or [success]*_ -CometChatMessageEvents.emitOnMessageDelete(message: BaseMessage) +class ConversationEventsViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + CometChatConversationEvents.addListener("conversation-listener", self) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatConversationEvents.removeListener("conversation-listener") + } +} -//emit this when a message is read by logged-in user. Pass the object of the [TextMessage], [MediaMessage] or [CustomMessage] being read*_ -CometChatMessageEvents.emitOnMessageRead(message: BaseMessage) +extension ConversationEventsViewController: CometChatConversationEventListener { + + func ccConversationDeleted(conversation: Conversation) { + print("Conversation deleted: \(conversation.conversationId ?? "")") + // Remove from local list, update UI + } + + func ccUpdateConversation(conversation: Conversation) { + print("Conversation updated: \(conversation.conversationId ?? "")") + // Refresh conversation data in UI + } +} +``` -//emit this when a transient message is sent by logged-in user. Pass a [String] asset image of the Live Reaction to show in the animation*_ -CometChatMessageEvents.emitOnLiveReaction(reaction: TransientMessage) +### Emit Conversation Events -//emit this when the logged in user clicked on detail icon.*_ -CometChatMessageEvents.emitOnViewInformation(user: User) +```swift +// Conversation deleted +CometChatConversationEvents.ccConversationDelete(conversation: deletedConversation) -//emit this when the logged in user updates a message that contains replies.*_ -CometChatMessageEvents.emitOnParentMessageUpdate(message: BaseMessage) +// Conversation updated +CometChatConversationEvents.ccUpdateConversation(conversation: updatedConversation) ``` - - - +### Conversation Events Reference -*** +| Event | Description | +|-------|-------------| +| `ccConversationDeleted` | Conversation was deleted | +| `ccUpdateConversation` | Conversation was updated | -### Listening to Message Events - -Here we will go through how anyone can listen to these client-side Message Events to update the state of the UI accordingly. +## Message Events -| Events | Description | -| --------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -| onMessageSent | Triggers whenever a loggedIn user sends any message, it will have two states such as: inProgress & sent | -| onMessageEdit | Triggers whenever a loggedIn user edits any message from the list of messages .it will have two states such as: inProgress & sent | -| onMessageDelete | Triggers whenever a loggedIn user deletes any message from the list of messages | -| onMessageRead | Triggers whenever a loggedIn user reads any message. | -| onLiveReaction | Triggers whenever a loggedIn user clicks on live reaction | -| onViewInformation | Triggers whenever a loggedIn user clicks on detail icon | -| onParentMessageUpdate | Triggers whenever a loggedIn user updates a message that contains replies. | +Listen for message-related actions like send, edit, delete, and reactions. - - ```swift -// View controller from your project where you want to listen events. -public class ViewController: UIViewController { +import UIKit +import CometChatUIKitSwift +import CometChatSDK - public override func viewDidLoad() { +class MessageEventsViewController: UIViewController { + + override func viewDidLoad() { super.viewDidLoad() - - // Subscribing for the listener to listen events from message module - CometChatMessageEvents.addListener("UNIQUE_ID", self as CometChatMessageEventListener) + CometChatMessageEvents.addListener("message-listener", self) } - - public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from message module - CometChatMessageEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatMessageEvents.removeListener("message-listener") } - - } - // Listener events from message module -extension ViewController: CometChatMessageEventListener { - - func onMessageSent(message: BaseMessage, status: MessageStatus) { - // Do Stuff +extension MessageEventsViewController: CometChatMessageEventListener { + + // Message lifecycle + func onMessageSent(message: BaseMessage, status: MessageStatus) { + switch status { + case .inProgress: + print("Sending...") + case .success: + print("Message sent: \(message.id)") + case .error: + print("Send failed") + @unknown default: + break + } } - + func onMessageEdit(message: BaseMessage, status: MessageStatus) { - // Do Stuff + print("Message edited: \(message.id)") } - + func onMessageDelete(message: BaseMessage, status: MessageStatus) { - // Do Stuff + print("Message deleted: \(message.id)") } - + + func onMessageRead(message: BaseMessage) { + print("Message read: \(message.id)") + } + func onMessageReply(message: BaseMessage, status: MessageStatus) { - // Do Stuff + print("Reply sent to: \(message.id)") } - - func onMessageRead(message: BaseMessage) { - // Do Stuff + + // Reactions + func onMessageReact(message: BaseMessage, reaction: CometChatMessageReaction) { + print("Reaction: \(reaction.reaction ?? "")") } - + func onLiveReaction(reaction: TransientMessage) { - // Do Stuff + print("Live reaction received") } - - func onMessageError(error: CometChatException) { - // Do Stuff + + // Thread updates + func onParentMessageUpdate(message: BaseMessage) { + print("Thread parent updated: \(message.id)") } - - func onVoiceCall(user: User) { - // Do Stuff + + // Navigation + func onViewInformation(user: User) { + print("View user info: \(user.name ?? "")") } - - func onVoiceCall(group: Group) { - // Do Stuff + + func onViewInformation(group: Group) { + print("View group info: \(group.name ?? "")") } - + + // Calls from message screen + func onVoiceCall(user: User) { + print("Voice call to: \(user.name ?? "")") + } + func onVideoCall(user: User) { - // Do Stuff + print("Video call to: \(user.name ?? "")") } - - func onVideoCall(group: Group) { - // Do Stuff + + func onVoiceCall(group: Group) { + print("Group voice call: \(group.name ?? "")") } - - func onViewInformation(user: User) { - // Do Stuff + + func onVideoCall(group: Group) { + print("Group video call: \(group.name ?? "")") } - - func onMessageReact(message: BaseMessage, reaction: CometChatMessageReaction) { - // Do Stuff + + // Errors + func onMessageError(error: CometChatException) { + print("Error: \(error.errorDescription)") } - } ``` - - - - -## Call Events - -CometChatCallEvents emits events when the logged-in user executes some action involving any call object. - -It contains the following properties and methods: - -### observer - -This is a List of Dictionary that contains components listening to call events in key value pairs - -### Type - -`[String:`CometChatCallEventListener]\() - -*** - -### addListener - -This method stores the passed listenerClass against the passed id in the addListener. - -### Signature - - - -```swift -addListener(_ id: String,_ observer: CometChatCallEventListener) -``` - - - - - -| Parameters | Type | Description | -| ---------- | -------------------------- | -------------------------------------- | -| id | String | the key to store the component against | -| observer | CometChatCallEventListener | the component listening to call events | +### Emit Message Events -*** - -### removeListener - -This method removes the entry with the passed id from the observer. - -### Signature - - - ```swift -removeListener(_ id: String) -``` - - +// Message sent (with status) +CometChatMessageEvents.emitOnMessageSent(message: sentMessage, status: .success) - +// Message edited +CometChatMessageEvents.emitOnMessageEdit(message: editedMessage, status: .success) -| Parameter | Type | Description | -| --------- | ------ | ------------------------------ | -| id | String | the key of the entry to remove | +// Message deleted +CometChatMessageEvents.emitOnMessageDelete(message: deletedMessage) -*** +// Message read +CometChatMessageEvents.emitOnMessageRead(message: readMessage) -### onIncomingCallAccepted +// Live reaction +CometChatMessageEvents.emitOnLiveReaction(reaction: transientMessage) -This method is used to perform some task when the logged-in user accepts the incoming call +// View user/group info +CometChatMessageEvents.emitOnViewInformation(user: selectedUser) -### Signature - - - -```swift -onIncomingCallAccepted(call: Call) +// Thread parent updated +CometChatMessageEvents.emitOnParentMessageUpdate(message: parentMessage) ``` - +### Message Events Reference - +| Event | Description | +|-------|-------------| +| `onMessageSent` | Message sent (inProgress, success, or error) | +| `onMessageEdit` | Message edited | +| `onMessageDelete` | Message deleted | +| `onMessageRead` | Message marked as read | +| `onMessageReply` | Reply sent to a message | +| `onMessageReact` | Reaction added to message | +| `onLiveReaction` | Live reaction sent | +| `onParentMessageUpdate` | Thread parent message updated | +| `onViewInformation` | Info button tapped (user or group) | +| `onVoiceCall` | Voice call initiated | +| `onVideoCall` | Video call initiated | +| `onMessageError` | Message operation failed | -| Parameters | Type | Description | -| ---------- | ---- | ------------------------------- | -| call | Call | the call that has been accepted | - -*** - -### onIncomingCallRejected - -This method is used to perform some task when the logged-in user rejects the incoming call +## Call Events -### Signature +Listen for call-related actions like initiating, accepting, and ending calls. - - ```swift -onIncomingCallRejected(call: Call) -``` - - - - - -| Parameters | Type | Description | -| ---------- | ---- | ------------------------------- | -| call | Call | the call that has been rejected | +import UIKit +import CometChatUIKitSwift +import CometChatSDK -*** - -### onCallInitiated - -This method is used to perform some task when the logged-in user initiates a call - -### Signature +class CallEventsViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + CometChatCallEvents.addListener("call-listener", self) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatCallEvents.removeListener("call-listener") + } +} - - -```swift -onCallInitiated(call: Call) +extension CallEventsViewController: CometChatCallEventListener { + + // Outgoing calls + func onCallInitiated(call: Call) { + print("Calling: \(call.receiverUid)") + } + + func onOutgoingCallAccepted(call: Call) { + print("Call accepted by recipient") + } + + func onOutgoingCallRejected(call: Call) { + print("Call rejected by recipient") + } + + // Incoming calls + func onIncomingCallAccepted(call: Call) { + print("You accepted the call") + } + + func onIncomingCallRejected(call: Call) { + print("You rejected the call") + } + + // Call ended + func onCallEnded(call: Call) { + print("Call ended") + } +} ``` - - - - -| Parameters | Type | Description | -| ---------- | ---- | -------------------------------- | -| call | Call | the call that has been initiated | - -*** - -### onCallEnded - -This method is used to perform some task when the ongoing or outgoing call ends. - -### Signature +### Emit Call Events - - ```swift -onCallEnded(call: Call) -``` - - - - - -| Parameters | Type | Description | -| ---------- | ---- | ---------------------------- | -| call | Call | the call that has been ended | +// Call initiated +CometChatCallEvents.emitOnCallInitiated(call: outgoingCall) -*** +// Call ended +CometChatCallEvents.emitOnCallEnded(call: endedCall) -### onOutgoingCallAccepted +// Incoming call accepted +CometChatCallEvents.emitOnIncomingCallAccepted(call: acceptedCall) -This method is used to perform some task when the outgoing call is accepted. +// Incoming call rejected +CometChatCallEvents.emitOnIncomingCallRejected(call: rejectedCall) -### Signature +// Outgoing call accepted +CometChatCallEvents.emitOnOutgoingCallAccepted(call: acceptedCall) - - -```swift -onOutgoingCallAccepted(call: Call) +// Outgoing call rejected +CometChatCallEvents.emitOnOutgoingCallRejected(call: rejectedCall) ``` - - - - -| Parameters | Type | Description | -| ---------- | ---- | -------------------------------------------------- | -| call | Call | the call that has been accepted by the other user. | - -*** +### Call Events Reference -### onOutgoingCallRejected +| Event | Description | +|-------|-------------| +| `onCallInitiated` | Outgoing call started | +| `onOutgoingCallAccepted` | Recipient accepted the call | +| `onOutgoingCallRejected` | Recipient rejected the call | +| `onIncomingCallAccepted` | You accepted an incoming call | +| `onIncomingCallRejected` | You rejected an incoming call | +| `onCallEnded` | Call ended (any reason) | -This method is used to perform some task when the outgoing call is rejected. +## Complete Example: App-Wide Event Manager -### Signature +Create a centralized event manager to handle events across your entire app: - - ```swift -onOutgoingCallRejected(call: Call) -``` - - - - - -| Parameters | Type | Description | -| ---------- | ---- | -------------------------------------------------- | -| call | Call | the call that has been rejected by the other user. | +import UIKit +import CometChatUIKitSwift +import CometChatSDK -*** - -### Emitting Call Events +// MARK: - Singleton Event Manager +class ChatEventManager { + + static let shared = ChatEventManager() + private let listenerId = "app-event-manager" + + private init() {} + + func startListening() { + CometChatUserEvents.addListener(listenerId, self) + CometChatGroupEvents.addListener(listenerId, self) + CometChatConversationEvents.addListener(listenerId, self) + CometChatMessageEvents.addListener(listenerId, self) + CometChatCallEvents.addListener(listenerId, self) + } + + func stopListening() { + CometChatUserEvents.removeListener(listenerId) + CometChatGroupEvents.removeListener(listenerId) + CometChatConversationEvents.removeListener(listenerId) + CometChatMessageEvents.removeListener(listenerId) + CometChatCallEvents.removeListener(listenerId) + } +} -There are two types of call event listeners, one for the SDK, which listens for events emitted from the backend for actions taken by users other than the logged-in user; and another for events specific to the UI Kit, which listens for events emitted from the client side for actions made by the logged-in user. The code snippets shared below contain how to emit such client-side call events to inform other UI components in a project. +// MARK: - User Events +extension ChatEventManager: CometChatUserEventListener { + func onUserBlock(user: User) { + NotificationCenter.default.post(name: .userBlocked, object: user) + } + + func onUserUnblock(user: User) { + NotificationCenter.default.post(name: .userUnblocked, object: user) + } +} - - -```swift -//emit this when logged in user initiates a call -CometChatCallEvents.emitOnCallInitiated(call: Call) +// MARK: - Group Events +extension ChatEventManager: CometChatGroupEventListener { + func onGroupCreate(group: Group) { + NotificationCenter.default.post(name: .groupCreated, object: group) + } + + func onGroupDelete(group: Group) { + NotificationCenter.default.post(name: .groupDeleted, object: group) + } + + func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { + NotificationCenter.default.post(name: .memberJoined, object: nil, + userInfo: ["user": joinedUser, "group": joinedGroup]) + } + + func onGroupMemberLeave(leftUser: User, leftGroup: Group) { + NotificationCenter.default.post(name: .memberLeft, object: nil, + userInfo: ["user": leftUser, "group": leftGroup]) + } + + // Implement other required methods... + func onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) {} + func onGroupMemberKick(kickedUser: User, kickedGroup: Group) {} + func onGroupMemberBan(bannedUser: User, bannedGroup: Group) {} + func onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group) {} + func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) {} + func onOwnershipChange(group: Group?, member: GroupMember?) {} + func onCreateGroupClick() {} +} -//emit this when logged in user cancels a call -CometChatCallEvents.emitOnCallEnded(call: Call) +// MARK: - Conversation Events +extension ChatEventManager: CometChatConversationEventListener { + func ccConversationDeleted(conversation: Conversation) { + NotificationCenter.default.post(name: .conversationDeleted, object: conversation) + } + + func ccUpdateConversation(conversation: Conversation) { + NotificationCenter.default.post(name: .conversationUpdated, object: conversation) + } +} -//emit this when logged in user accepts the incoming call -CometChatCallEvents.emitOnIncomingCallAccepted(call: Call) +// MARK: - Message Events +extension ChatEventManager: CometChatMessageEventListener { + func onMessageSent(message: BaseMessage, status: MessageStatus) { + if status == .success { + NotificationCenter.default.post(name: .messageSent, object: message) + } + } + + // Implement other required methods... + func onMessageEdit(message: BaseMessage, status: MessageStatus) {} + func onMessageDelete(message: BaseMessage, status: MessageStatus) {} + func onMessageRead(message: BaseMessage) {} + func onLiveReaction(reaction: TransientMessage) {} + func onMessageReact(message: BaseMessage, reaction: CometChatMessageReaction) {} + func onParentMessageUpdate(message: BaseMessage) {} + func onViewInformation(user: User) {} + func onViewInformation(group: Group) {} + func onVoiceCall(user: User) {} + func onVideoCall(user: User) {} + func onVoiceCall(group: Group) {} + func onVideoCall(group: Group) {} + func onMessageError(error: CometChatException) {} + func onMessageReply(message: BaseMessage, status: MessageStatus) {} +} -//emit this when logged in user rejects the incoming call -CometChatCallEvents.emitOnIncomingCallRejected(call: Call) -//emit this when the other user accepts the call -CometChatCallEvents.emitOnOutgoingCallAccepted(call: Call) +// MARK: - Call Events +extension ChatEventManager: CometChatCallEventListener { + func onCallInitiated(call: Call) { + NotificationCenter.default.post(name: .callStarted, object: call) + } + + func onCallEnded(call: Call) { + NotificationCenter.default.post(name: .callEnded, object: call) + } + + func onIncomingCallAccepted(call: Call) {} + func onIncomingCallRejected(call: Call) {} + func onOutgoingCallAccepted(call: Call) {} + func onOutgoingCallRejected(call: Call) {} +} -//emit this when the other user rejects a call -CometChatCallEvents.emitOnOutgoingCallRejected(call: Call) +// MARK: - Notification Names +extension Notification.Name { + static let userBlocked = Notification.Name("userBlocked") + static let userUnblocked = Notification.Name("userUnblocked") + static let groupCreated = Notification.Name("groupCreated") + static let groupDeleted = Notification.Name("groupDeleted") + static let memberJoined = Notification.Name("memberJoined") + static let memberLeft = Notification.Name("memberLeft") + static let conversationDeleted = Notification.Name("conversationDeleted") + static let conversationUpdated = Notification.Name("conversationUpdated") + static let messageSent = Notification.Name("messageSent") + static let callStarted = Notification.Name("callStarted") + static let callEnded = Notification.Name("callEnded") +} ``` - - - - -### Listening to Call Events - -Here we will go through how anyone can listen to these client-side Call Events to update the state of the UI accordingly. - -| Event | Description | -| ---------------------- | ------------------------------------------------------- | -| onIncomingCallAccepted | Triggers whenever incoming call is accepted by the user | -| onIncomingCallRejected | Triggers whenever incoming call is rejected by the user | -| onCallEnded | Triggers whenever the call is ended | -| onCallInitiated | Triggers whenever the call is getting initiated | -| onOutgoingCallAccepted | Triggers whenever outgoing call is accepted by the user | -| onOutgoingCallRejected | Triggers whenever outgoing call is rejected by the user | +### Using the Event Manager - - ```swift -// View controller from your project where you want to listen events. -public class ViewController: UIViewController { +// AppDelegate.swift +class AppDelegate: UIResponder, UIApplicationDelegate { + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + + // Start listening for events app-wide + ChatEventManager.shared.startListening() + + return true + } +} - public override func viewDidLoad() { +// Any ViewController +class MyViewController: UIViewController { + + override func viewDidLoad() { super.viewDidLoad() - - // Subscribing for the listener to listen events from user module - CometChatCallEvents.addListener("UNIQUE_ID", self as CometChatCallEventListener) + + // Listen for specific events via NotificationCenter + NotificationCenter.default.addObserver( + self, + selector: #selector(handleUserBlocked), + name: .userBlocked, + object: nil + ) } - - public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from user module - CometChatCallEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") + + @objc private func handleUserBlocked(_ notification: Notification) { + guard let user = notification.object as? User else { return } + print("User blocked: \(user.name ?? "")") + // Update your UI + } + + deinit { + NotificationCenter.default.removeObserver(self) } - - } +``` - // Listener events from user module -extension ViewController: CometChatCallEventListener { - - func onIncomingCallAccepted(call: Call) { - // Do Stuff - } +## Best Practices - func onIncomingCallRejected(call: Call) - // Do Stuff - } +1. **Always remove listeners** - Call `removeListener` in `viewWillDisappear` to prevent memory leaks - func onCallEnded(call: Call) { - // Do Stuff - } +2. **Use unique listener IDs** - Avoid conflicts between components by using descriptive, unique IDs - func onCallInitiated(call: Call) - // Do Stuff - } +3. **Update UI on main thread** - Dispatch UI updates to the main thread when handling events - func onOutgoingCallAccepted(call: Call) { - // Do Stuff - } +4. **Don't emit unnecessarily** - Only emit events when state actually changes - func onOutgoingCallRejected(call: Call) - // Do Stuff - } -} -``` +5. **Use a central manager** - For app-wide event handling, create a singleton manager - +## Troubleshooting - +| Issue | Solution | +|-------|----------| +| Events not firing | Verify listener is added before the action occurs | +| Duplicate events | Check you're not adding the same listener multiple times | +| Memory leaks | Ensure `removeListener` is called in `viewWillDisappear` | +| UI not updating | Dispatch UI updates to main thread with `DispatchQueue.main.async` | +| Listener ID conflicts | Use unique, descriptive IDs for each listener | From 7253d2ed6f9067436fbfdacbd918c29a915406da Mon Sep 17 00:00:00 2001 From: Aditya Date: Thu, 12 Feb 2026 12:26:02 +0530 Subject: [PATCH 004/106] imprved extensions , getting-started , group-members --- ui-kit/ios/extensions.mdx | 162 +++-- ui-kit/ios/getting-started.mdx | 604 +++++++--------- ui-kit/ios/group-members.mdx | 1234 ++++++++------------------------ 3 files changed, 693 insertions(+), 1307 deletions(-) diff --git a/ui-kit/ios/extensions.mdx b/ui-kit/ios/extensions.mdx index fef6939e0..8bde20ada 100644 --- a/ui-kit/ios/extensions.mdx +++ b/ui-kit/ios/extensions.mdx @@ -1,131 +1,209 @@ --- title: "Extensions" +description: "Enable powerful chat features with zero code using CometChat extensions" --- -## Overview +Extensions add powerful features to your chat app without writing any code. Simply enable them in your [CometChat Dashboard](https://app.cometchat.com), and they automatically appear in the UI Kit components. -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. +## How Extensions Work -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) +1. Log in to your [CometChat Dashboard](https://app.cometchat.com) +2. Navigate to the **Extensions** section +3. Enable the extensions you want +4. The features automatically appear in your app after initialization -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 the extension features will only be available if they are supported by CometChat UI Kit. + +Extensions are enabled at the dashboard level. Once activated, they work across all platforms (iOS, Android, Web) using the same CometChat app. No code changes required. + -CometChat’s UI Kit offers built-in support for 12 powerful 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. +For detailed information on all extensions, see [Extensions Overview](/fundamentals/extensions-overview). -## Built-in Extensions - -Here's a guide on how you can enable and integrate these extensions: +## Available 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/ios/message-composer) component of UI Kits. +Let users express emotions with fun, pre-designed stickers. -### Polls +| Feature | Details | +|---------|---------| +| Appears in | [Message Composer](/ui-kit/ios/message-composer) attachment menu | +| Setup guide | [Sticker Extension](/fundamentals/stickers) | +| Code required | None - automatic after dashboard activation | -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). +### 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/ios/message-composer) component of UI Kits. +Create polls to gather opinions in group chats quickly. -### Collaborative Whiteboard +| Feature | Details | +|---------|---------| +| Appears in | [Message Composer](/ui-kit/ios/message-composer) action sheet | +| Setup guide | [Polls Extension](/fundamentals/polls) | +| Code required | None - automatic after dashboard activation | -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](/fundamentals/collaborative-whiteboard). +### Collaborative Whiteboard -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/ios/message-composer) component of UI Kits. +Real-time whiteboard for drawing, brainstorming, and sharing ideas together. -### Collaborative Document +| Feature | Details | +|---------|---------| +| Appears in | [Message Composer](/ui-kit/ios/message-composer) action sheet | +| Setup guide | [Collaborative Whiteboard](/fundamentals/collaborative-whiteboard) | +| Code required | None - automatic after dashboard activation | -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](/fundamentals/collaborative-document). +### Collaborative Document -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/ios/message-composer) component of UI Kits. +Work together on shared documents in real-time with other users. -### Message Reactions +| Feature | Details | +|---------|---------| +| Appears in | [Message Composer](/ui-kit/ios/message-composer) action sheet | +| Setup guide | [Collaborative Document](/fundamentals/collaborative-document) | +| Code required | None - automatic after dashboard activation | -Message Reactions extension lets users express their emotions towards a message by choosing from a range of emojis. It provides a quick way to respond to any shared message. For a comprehensive understanding and guide on implementing and using the Message Reactions Extension, refer to our specific guide on the [Message Reactions Extension](/fundamentals/reactions). +### Message Reactions -Once you have successfully activated the [Message Reactions Extension](/fundamentals/reactions) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of [MessageList Component](/ui-kit/ios/message-list) component of UI Kits. +Let users react to messages with a range of emojis for quick responses. -### Message Translation +| Feature | Details | +|---------|---------| +| Appears in | [Message List](/ui-kit/ios/message-list) long-press menu | +| Setup guide | [Reactions Extension](/fundamentals/reactions) | +| Code required | None - automatic after dashboard activation | -The Message Translation extension in CometChat is designed to translate any message into your local. 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). +### 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/ios/message-list) component of UI Kits. +Translate messages into any language instantly, eliminating language barriers. -### Link Preview +| Feature | Details | +|---------|---------| +| Appears in | [Message List](/ui-kit/ios/message-list) message actions | +| Setup guide | [Message Translation](/fundamentals/message-translation) | +| Code required | None - automatic after dashboard activation | -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). +### 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/ios/message-list) component of UI Kits. +Show rich previews for URLs shared in chat including title, description, and thumbnail. -### Profanity Filter +| Feature | Details | +|---------|---------| +| Appears in | [Message List](/ui-kit/ios/message-list) message bubbles | +| Setup guide | [Link Preview](/fundamentals/link-preview) | +| Code required | None - automatic after dashboard activation | -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). +### Profanity Filter -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/ios/message-list) component of UI Kits. +Automatically censor inappropriate and obscene words in messages. -### Data Masking +| Feature | Details | +|---------|---------| +| Appears in | [Message List](/ui-kit/ios/message-list) - filtered automatically | +| Setup guide | [Legacy Extensions](/moderation/legacy-extensions) | +| Code required | None - automatic after dashboard activation | -The Data Masking extension helps secure sensitive data by masking information like credit card numbers and phone numbers in a chat message. For a comprehensive understanding and guide on implementing and using the Data Masking Extension, refer to our specific guide on the [Legacy Extensions](/moderation/legacy-extensions). +### Data Masking -Once you have successfully activated the Data Masking Extension from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/ios/message-list) component of UI Kits. +Automatically mask sensitive data like credit card numbers and phone numbers. -### Image Moderation +| Feature | Details | +|---------|---------| +| Appears in | [Message List](/ui-kit/ios/message-list) - masked automatically | +| Setup guide | [Legacy Extensions](/moderation/legacy-extensions) | +| Code required | None - automatic after dashboard activation | -The Image Moderation extension uses machine learning to detect and filter out inappropriate or explicit images shared in the chat. For a comprehensive understanding and guide on implementing and using the Image Moderation Extension, refer to our specific guide on the [Legacy Extensions](/moderation/legacy-extensions). +### Image Moderation -Once you have successfully activated the Image Moderation Extension from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/ios/message-list) component of UI Kits. +Detect and filter inappropriate or explicit images using AI/ML. -### Thumbnail Generation +| Feature | Details | +|---------|---------| +| Appears in | [Message List](/ui-kit/ios/message-list) - filtered automatically | +| Setup guide | [Legacy Extensions](/moderation/legacy-extensions) | +| Code required | None - automatic after dashboard activation | -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). +### 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/ios/message-list) component of UI Kits. +Automatically create smaller preview images for faster loading and reduced bandwidth. +| Feature | Details | +|---------|---------| +| Appears in | [Message List](/ui-kit/ios/message-list) image bubbles | +| Setup guide | [Thumbnail Generation](/fundamentals/thumbnail-generation) | +| Code required | None - automatic after dashboard activation | + ### Smart Replies -Smart Replies extension provides automated, predictive text responses, making the conversation more efficient by reducing the response time. For a comprehensive understanding and guide on implementing and using the Smart Replies Extension, refer to our specific guide on the [Smart Replies Extension](/fundamentals/smart-replies). +AI-powered suggested responses for faster, more efficient conversations. + +| Feature | Details | +|---------|---------| +| Appears in | [Message Composer](/ui-kit/ios/message-composer) suggestions | +| Setup guide | [Smart Replies](/fundamentals/smart-replies) | +| Code required | None - automatic after dashboard activation | + +## Extensions Summary + +| Extension | Component | Use Case | +|-----------|-----------|----------| +| Stickers | Message Composer | Fun expression | +| Polls | Message Composer | Group decisions | +| Whiteboard | Message Composer | Visual collaboration | +| Document | Message Composer | Document collaboration | +| Reactions | Message List | Quick responses | +| Translation | Message List | Multi-language support | +| Link Preview | Message List | Rich URL previews | +| Profanity Filter | Message List | Content moderation | +| Data Masking | Message List | Privacy protection | +| Image Moderation | Message List | Safe content | +| Thumbnails | Message List | Faster loading | +| Smart Replies | Message Composer | Quick responses | + +## Related + +- [Extensions Overview](/fundamentals/extensions-overview) - Full extension documentation +- [Moderation](/moderation/overview) - Content moderation features +- [Message Composer](/ui-kit/ios/message-composer) - Where composer extensions appear +- [Message List](/ui-kit/ios/message-list) - Where message extensions appear diff --git a/ui-kit/ios/getting-started.mdx b/ui-kit/ios/getting-started.mdx index 0fabda03d..5ea059a3e 100644 --- a/ui-kit/ios/getting-started.mdx +++ b/ui-kit/ios/getting-started.mdx @@ -1,448 +1,396 @@ --- -title: "Getting Started With CometChat iOS UI Kit" +title: "Getting Started" sidebarTitle: "Integration" +description: "Add chat to your iOS app in minutes with CometChat UI Kit" --- -The **CometChat UI Kit for iOS** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI elements**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. - -With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat iOS UI Kit. +The CometChat iOS UI Kit provides pre-built chat components with theming support, one-on-one and group messaging, and full customization capabilities. -*** - -## **Prerequisites** - -Before installing the **CometChat UI Kit for iOS**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: - -* **User Management** -* **Group Chat & Messaging** -* **Voice & Video Calling** -* **Real-time Notifications** - - - -To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: - -1. **App ID** -2. **Auth Key** -3. **Region** - -Ensure you have these details ready before proceeding with the installation and configuration. - - - -*** - -## **Register & Set Up CometChat** - -Follow these steps to **register on CometChat** and **set up your development environment**. - -### **Step 1: Register on CometChat** - -To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. +## Prerequisites -🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** +Before starting, ensure you have: -### **Step 2: Get Your Application Keys** - -After registering, create a **new app** and retrieve your **authentication details**: - -1. Navigate to the **QuickStart** or **API & Auth Keys section**. - -2. Note down the following keys: - - * **App ID** - * **Auth Key** - * **Region** +- **Xcode 16+** installed on your Mac +- **iOS 13.0+** deployment target +- **Swift 5.0+** +- A [CometChat account](https://app.cometchat.com) with your App ID, Auth Key, and Region - -Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **web and mobile**. - +Get your credentials from the [CometChat Dashboard](https://app.cometchat.com) under **QuickStart** or **API & Auth Keys** section. -### **Step 3: Set Up Your Development Environment** - -Ensure your system meets the following **prerequisites** before proceeding with integration. - -**System Requirements:** +## Step 1: Create iOS Project -* **Xcode 16 or later** installed on your machine. -* An **iOS device or simulator** with iOS version 13.0 or above. -* **Swift 5.0**. -* **macOS**. +Open Xcode and create a new project: -*** +1. File → New → Project → **iOS App** +2. Enter your **Product Name** and **Bundle Identifier** +3. Interface: **Storyboard** +4. Language: **Swift** +5. Click **Create** -## **Integration Steps** - -### **Create an iOS Project** - -To get started, open Xcode and create a new project for UI Kit in the Project window as follows: - -1. Select **iOS App** in the **Choose a template for your new project** window and click Next. -2. Enter your project name in the **Name** field in the **Choose options for your new project** window. -3. Enter your identifier in the **Bundle Identifier** field in the **Choose options for your new project** window. -4. Select **Storyboard** in the **Interface** field in the **Choose options for your new project** window. -5. Select **Swift** in the **Language** field in the **Choose options for your new project** window. - -*** - -### **Install Dependencies** - -This developer kit is an add-on feature to CometChat iOS SDK so installing it will also install the core Chat SDK. You can install CometChat UI Kit into your iOS project using CocoaPods or Swift Package Manager (SPM). +## Step 2: Install SDK -We recommend using CocoaPods, as they are the most advanced way of managing iOS project dependencies. - -1. Create pod file by running the following command in your project's base level: +1. Open Terminal and navigate to your project folder: +```bash +cd /path/to/your/project +``` -```ruby Swift +2. Create a Podfile: +```bash pod init ``` -2. Add CometChat SDKs to Your Podfile: - -```ruby Swift +3. Open the Podfile and add CometChat dependencies: +```ruby platform :ios, '13.0' use_frameworks! target 'YourApp' do - # CometChat UI Kit for Swift pod 'CometChatUIKitSwift', '5.1.7' - - # Optional: Include if you're using Audio/Video Calling - pod 'CometChatCallsSDK', '4.2.2' + pod 'CometChatCallsSDK', '4.2.2' # Optional: for voice/video calls end ``` -3. Install the CometChat UI Kit framework through CocoaPods: - -```ruby Swift +4. Install the pods: +```bash pod install ``` -If you're facing any issues while installing pods, use the following command: - -```ruby Swift -pod install --repo-update -``` - -To get the latest version of CometChat UI Kit, use: - -```ruby Swift -pod update CometChatUIKitSwift -pod update CometChatCallsSDK +5. Open the `.xcworkspace` file (not `.xcodeproj`): +```bash +open YourApp.xcworkspace ``` - -Always ensure to open the XCFramework file after adding the dependencies. - +If pod install fails, try: `pod install --repo-update` - - -**Swift Package Manager** (SPM) is Apple's built-in tool for managing dependencies in Swift projects. It allows developers to integrate and manage third-party libraries seamlessly. - -1. Go to **File** tab and select **Add Package Dependencies.** - -2. Enter the repository URL of the Swift package: + +1. In Xcode, go to **File → Add Package Dependencies** +2. Enter the UI Kit repository URL: ``` https://github.com/cometchat/cometchat-uikit-ios ``` -3. To add the package, select Version Rules, enter Up to Exact Version and click Add package. - - Exact Version: - - ``` - 5.1.7 - ``` - -4. Add `CometChatSDK` repeating the above steps for following link and exact version: - - Link: - - ``` - https://github.com/cometchat/chat-sdk-ios - ``` - - Exact Version: - - ``` - 4.1.0 - ``` +3. Select version **5.1.7** and click **Add Package** +4. Repeat for the Chat SDK: +``` +https://github.com/cometchat/chat-sdk-ios +``` +Version: **4.1.0** - -*** - -### **Configure Privacy Permissions** - -1. To enable media messaging in your app, you must allow **Camera**, **Microphone**, and **Photo Library** access in `Info.plist`. These permissions are required for sending and receiving media files. - - ```ruby Info.plist - NSCameraUsageDescription - Allow access to the camera to capture photos and videos. - - NSMicrophoneUsageDescription - Enable microphone access for voice and video communication. - - NSPhotoLibraryAddUsageDescription - Allow saving photos and videos to your device's photo library. - - NSPhotoLibraryUsageDescription - Grant access to select and upload photos from your library. - ``` - - - - - -2. Navigate to your Build Settings and disable the User Script Sandboxing option. - - Disabling User Script Sandboxing ensures that WebView can load and execute scripts necessary for collaborative tools. - - - - +## Step 3: Configure Permissions -*** +Add the following keys to your `Info.plist` file to enable camera, microphone, and photo library access: -### **Step 4: Initialize & Login to CometChat UI Kit** +```xml +NSCameraUsageDescription +Camera access for capturing photos and videos -To authenticate a user, you need a **`UID`**. You can either: +NSMicrophoneUsageDescription +Microphone access for voice and video calls -1. **Create new users** on the **[CometChat Dashboard](https://app.cometchat.com)**, **[CometChat SDK Method](/ui-kit/react/methods#create-user)** or **[via the API](https://api-explorer.cometchat.com/reference/creates-user)**. +NSPhotoLibraryUsageDescription +Photo library access to share images -2. **Use pre-generated test users**: - - * `cometchat-uid-1` - * `cometchat-uid-2` - * `cometchat-uid-3` - * `cometchat-uid-4` - * `cometchat-uid-5` - -The **Login** method returns a **User object** containing all relevant details of the logged-in user. - -*** - - +NSPhotoLibraryAddUsageDescription +Save photos and videos to your library +``` -**Security Best Practices** + + + -* The **Auth Key** method is recommended for **proof-of-concept (POC) development** and early-stage testing. -* For **production environments**, it is strongly advised to use an **[Auth Token](/ui-kit/ios/methods#login-using-auth-token)** instead of an **Auth Key** to enhance security and prevent unauthorized access. +Also, in **Build Settings**, disable **User Script Sandboxing** to enable collaborative features like whiteboard and document sharing. - + + + -You can initialize CometChat and log in a user in your `SceneDelegate.swift` file: +## Step 4: Initialize and Login -> ⚠️ **Important:** Initialization and login are independent steps. However, the CometChat SDK **must be initialized before** you call the login method. +Replace the contents of your `SceneDelegate.swift` with the following code: -```swift SceneDelegate.swift highlight={13-15} lines +```swift import UIKit import CometChatUIKitSwift class SceneDelegate: UIResponder, UIWindowSceneDelegate { - + var window: UIWindow? - + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - guard let windowScene = (scene as? UIWindowScene) else { return } - - let uikitSettings = UIKitSettings() - .set(appID: "<#Enter Your App ID Here#>") - .set(region: "<#Enter Your Region Code Here#>") - .set(authKey: "<#Enter Your AuthKey Here#>") + + // 1. Configure CometChat UI Kit + let settings = UIKitSettings() + .set(appID: "YOUR_APP_ID") // Replace with your App ID + .set(authKey: "YOUR_AUTH_KEY") // Replace with your Auth Key + .set(region: "YOUR_REGION") // "us" or "eu" .subscribePresenceForAllUsers() .build() - - CometChatUIKit.init(uiKitSettings: uikitSettings) { result in + + // 2. Initialize CometChat + CometChatUIKit.init(uiKitSettings: settings) { result in switch result { case .success: - debugPrint("CometChat UI Kit initialization succeeded") - - let uid = "cometchat-uid-1" - - CometChatUIKit.login(uid: uid) { loginResult in - switch loginResult { - case .success: - debugPrint("CometChat UI Kit login succeeded") - - // ✅ Option 1: Launch One-to-One or Group Chat Screen - // DispatchQueue.main.async { - // self.setUpOneOneOrGroupConversation(windowScene: windowScene, uid: "cometchat-uid-2") - // } - - // ✅ Option 2: Launch Conversation List + Message View (Split-Screen Style) - // DispatchQueue.main.async { - // self.setupConversationsView(windowScene: windowScene) - // } - - // ✅ Option 3: Launch Tab-Based Chat Experience (Chats, Calls, Users, Groups) - // DispatchQueue.main.async { - // self.setupTabbedView(windowScene: windowScene) - // } - - case .onError(let error): - debugPrint("CometChat UI Kit login failed with error: \(error.description)") - @unknown default: - break - } - } - + print("✅ CometChat initialized successfully") + self.loginUser(windowScene: windowScene) + case .failure(let error): - debugPrint("CometChat UI Kit initialization failed with error: \(error.localizedDescription)") + print("❌ Initialization failed: \(error.localizedDescription)") } } } + + private func loginUser(windowScene: UIWindowScene) { + // Use a test user ID or your own user ID + let uid = "cometchat-uid-1" + + CometChatUIKit.login(uid: uid) { result in + switch result { + case .success(let user): + print("✅ Logged in as: \(user.name ?? uid)") + DispatchQueue.main.async { + self.showConversations(windowScene: windowScene) + } + + case .onError(let error): + print("❌ Login failed: \(error.description)") + + @unknown default: + break + } + } + } + + private func showConversations(windowScene: UIWindowScene) { + let conversations = CometChatConversations() + + // Handle conversation tap - open messages + conversations.set(onItemClick: { [weak self] conversation, _ in + self?.openMessages(for: conversation) + }) + + let navigationController = UINavigationController(rootViewController: conversations) + + window = UIWindow(windowScene: windowScene) + window?.rootViewController = navigationController + window?.makeKeyAndVisible() + } + + private func openMessages(for conversation: Conversation) { + let messages = CometChatMessages() + + if let user = conversation.conversationWith as? User { + messages.set(user: user) + } else if let group = conversation.conversationWith as? Group { + messages.set(group: group) + } + + if let nav = window?.rootViewController as? UINavigationController { + nav.pushViewController(messages, animated: true) + } + } } ``` - - -Ensure you replace the following placeholders with your actual CometChat credentials: - -* App ID → Your CometChat App ID -* Auth Key → Your CometChat Auth Key -* Region → Your App Region + +**Security Note**: Use Auth Key only for development and testing. In production, use [Auth Tokens](/ui-kit/ios/methods#login-using-auth-token) generated from your backend server. + -These values are required for proper authentication and seamless integration. +## Step 5: Run Your App - - -After running the app, you should see the following log message: +Build and run your app (⌘ + R). You should see these messages in the console: -```sh Console -"CometChat UI Kit initialization succeeded" -"CometChat UI Kit login succeeded" +``` +✅ CometChat initialized successfully +✅ Logged in as: cometchat-uid-1 ``` -*** +Your app will display the conversations list. Tap any conversation to open the chat screen. -### **Step 5: Choose a Chat Experience** +## Test Users -Integrate a conversation view that suits your application's **UX requirements**. Below are the available options: +CometChat provides pre-created test users for development: -*** +| User ID | Description | +|---------|-------------| +| `cometchat-uid-1` | Test User 1 | +| `cometchat-uid-2` | Test User 2 | +| `cometchat-uid-3` | Test User 3 | +| `cometchat-uid-4` | Test User 4 | +| `cometchat-uid-5` | Test User 5 | -### **1️⃣ Conversation List + Message View** +## Chat Experience Options -**Best for:** Native iOS apps using **stack-based navigation** to switch between conversations and messages. +Choose the layout that best fits your app: -**Highlights:** +### Option 1: Conversation List + Messages -* **Push-Based Navigation** – Taps on conversations open full message views. -* **Supports One-to-One & Group Chats** – Handles all CometChat conversation types. -* **Real-Time Sync** – Messages auto-refresh using live CometChat event listeners. -* **Session-Aware** – Message states persist across app sessions and devices. -* **Customizable UI** – Modify styling, actions, or behavior using CometChat UI Kit. +Standard chat app layout with a conversation list that opens message views. -**Use When:** - -* You need a **native iOS chat experience** with clean transitions. -* Your app supports **private and group messaging**. -* You want **seamless sync and navigation** between list and messages. +This is the default implementation shown in Step 4 above. -[Integrate Conversation List + Message View](./ios-conversation) +[Full Integration Guide →](/ui-kit/ios/ios-conversation) -*** +### Option 2: Direct Chat -### **2️⃣ One-to-One / Group Chat** - -**Best for:** iOS apps that launch **directly into a conversation screen** without showing a list. - -**Highlights:** - -* **Single View Chat** – Use `CometChatMessages` with a passed user or group object. -* **No Sidebar or List** – Ideal for contextual entry points (support, match, invite, etc.). -* **Works with UINavigationController & SwiftUI NavigationStack** -* **Lightweight** – Launches faster and uses minimal memory. -* **Full-Screen Messaging** – Clear, immersive chat UI. +Open a chat directly with a specific user or group without showing a list. -**Use When:** - -* Your app starts directly with a **specific user or group chat**. -* You want a **clean, distraction-free** chat experience. -* Ideal for **support workflows, community replies, or invitations.** - -[Integrate One-to-One / Group Chat](./ios-one-to-one-chat) - -*** +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK -### **3️⃣ Tab-Based Messaging UI (All-in-One)** +class DirectChatViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + openChatWithUser(uid: "cometchat-uid-2") + } + + func openChatWithUser(uid: String) { + CometChat.getUser(UID: uid) { [weak self] user in + DispatchQueue.main.async { + let messages = CometChatMessages() + messages.set(user: user) + self?.navigationController?.pushViewController(messages, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } + + func openChatWithGroup(guid: String) { + CometChat.getGroup(GUID: guid) { [weak self] group in + DispatchQueue.main.async { + let messages = CometChatMessages() + messages.set(group: group) + self?.navigationController?.pushViewController(messages, animated: true) + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } + } +} +``` -**Best for:** iOS apps needing a **multi-tab interface** with seamless transitions between Chats, Users, Calls, and Settings. +[Full Integration Guide →](/ui-kit/ios/ios-one-to-one-chat) -**Highlights:** +### Option 3: Tab-Based Layout -* **UITabBarController or SwiftUI TabView** – Native navigation pattern for iOS. -* **Modular UI** – Isolated controllers or views for each tab. -* **Full-Screen Messaging** – Dedicated message views within the Chat tab. -* **Extensible** – Add future tabs like Notifications, Search, or Profile. -* **Responsive Layouts** – Works across iPhones and iPads. -* **Great for SuperApps & Enterprise Tools** +Full-featured chat app with tabs for Chats, Users, Groups, and more. -**Use When:** - -* You need a **structured layout** for navigating chat, calls, and contacts. -* Your app supports **multiple modules** (e.g., user directory, history, chat). -* Designed for **enterprise, support, or social use cases**. - -[Integrate Tab-Based Chat](./ios-tab-based-chat) - -*** - -## **Build Your Own Chat Experience** - -**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app’s design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. - -**Recommended for:** - -* Apps that require **a fully customized chat experience**. -* Developers who want to **extend functionalities and modify UI components**. -* Businesses integrating chat seamlessly into **existing platforms**. - -**Key Areas to Explore:** +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK -* **[iOS Sample App](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp)** – Fully functional sample applications to accelerate your development. -* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities. -* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design. -* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding. -* **[Build Your Own UI](/sdk/javascript/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience. +class ChatTabBarController: UITabBarController { + + override func viewDidLoad() { + super.viewDidLoad() + setupTabs() + } + + private func setupTabs() { + // Chats Tab + let chatsNav = UINavigationController() + let conversations = CometChatConversations() + conversations.set(onItemClick: { [weak chatsNav] conversation, _ in + let messages = CometChatMessages() + if let user = conversation.conversationWith as? User { + messages.set(user: user) + } else if let group = conversation.conversationWith as? Group { + messages.set(group: group) + } + chatsNav?.pushViewController(messages, animated: true) + }) + chatsNav.setViewControllers([conversations], animated: false) + chatsNav.tabBarItem = UITabBarItem( + title: "Chats", + image: UIImage(systemName: "message"), + selectedImage: UIImage(systemName: "message.fill") + ) + + // Users Tab + let usersNav = UINavigationController() + let users = CometChatUsers() + users.set(onItemClick: { [weak usersNav] user, _ in + let messages = CometChatMessages() + messages.set(user: user) + usersNav?.pushViewController(messages, animated: true) + }) + usersNav.setViewControllers([users], animated: false) + usersNav.tabBarItem = UITabBarItem( + title: "Users", + image: UIImage(systemName: "person.2"), + selectedImage: UIImage(systemName: "person.2.fill") + ) + + // Groups Tab + let groupsNav = UINavigationController() + let groups = CometChatGroups() + groups.set(onItemClick: { [weak groupsNav] group, _ in + let messages = CometChatMessages() + messages.set(group: group) + groupsNav?.pushViewController(messages, animated: true) + }) + groupsNav.setViewControllers([groups], animated: false) + groupsNav.tabBarItem = UITabBarItem( + title: "Groups", + image: UIImage(systemName: "person.3"), + selectedImage: UIImage(systemName: "person.3.fill") + ) + + viewControllers = [chatsNav, usersNav, groupsNav] + } +} +``` -*** +[Full Integration Guide →](/ui-kit/ios/ios-tab-based-chat) -## **Next Steps** +## Troubleshooting -Now that you’ve selected your **chat experience**, proceed to the **integration guide**: +| Issue | Solution | +|-------|----------| +| Pod install fails | Run `pod install --repo-update` | +| Initialization fails | Verify App ID, Auth Key, and Region are correct | +| Login fails | Check that the user exists in your CometChat dashboard | +| UI not displaying | Ensure UI updates are on the main thread | +| Permissions denied | Add all required keys to Info.plist | +| Collaborative features not working | Disable User Script Sandboxing in Build Settings | -* **[Integrate Conversation List + Message](/ui-kit/ios/ios-conversation)** -* **[Integrate One-to-One Chat](/ui-kit/ios/ios-one-to-one-chat)** -* **[Integrate Tab-Based Chat](/ui-kit/ios/ios-tab-based-chat)** -* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** +## Next Steps -*** +- [Core Features](/ui-kit/ios/core-features) - Messaging, reactions, threads, and more +- [Components](/ui-kit/ios/components-overview) - All available UI components +- [Theming](/ui-kit/ios/theme-introduction) - Customize colors, fonts, and styles +- [Events](/ui-kit/ios/events) - Listen for chat events +- [Extensions](/ui-kit/ios/extensions) - Enable additional features +- [Sample App](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) - Full working example diff --git a/ui-kit/ios/group-members.mdx b/ui-kit/ios/group-members.mdx index 0d7d3e211..3a5a9c3e7 100644 --- a/ui-kit/ios/group-members.mdx +++ b/ui-kit/ios/group-members.mdx @@ -1,1080 +1,440 @@ --- title: "Group Members" +description: "Display and manage members of a CometChat group" --- -## Overview - -`CometChatGroupMembers` is a versatile [Component](/ui-kit/ios/components-overview#components) designed to showcase all users who are either added to or invited to a group, thereby enabling them to participate in group discussions, access shared content, and engage in collaborative activities. Group members have the capability to communicate in real-time through messaging, voice and video calls, and various other interactions. Additionally, they can interact with each other, share files, and join calls based on the permissions established by the group administrator or owner. +The `CometChatGroupMembers` component displays all members of a group with their roles (owner, admin, participant). It supports member management actions like kick, ban, and role changes. -The `CometChatGroupMembers` component is composed of the following BaseComponents: - -| Components | Description | -| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [CometChatListBase](/ui-kit/ios/list-base) | `CometChatListBase` serves as a container component equipped with a title (navigationBar), search functionality (search-bar), background settings, and a container for embedding a list view. | -| [CometChatListItem](/ui-kit/ios/list-item) | This component renders information extracted from a `User` object onto a tile, featuring a title, subtitle, leading view, and trailing view. experience, facilitating seamless navigation and interaction within the component. | - -*** - -## Usage - -### Integration - -`CometChatGroupMembers`, as a custom **view controller**, offers flexible integration options, allowing it to be launched directly via button clicks or any user-triggered action. Additionally, it seamlessly integrates into tab view controllers. With group members, users gain access to a wide range of parameters and methods for effortless customization of its user interface. - -The following code snippet exemplifies how you can seamlessly integrate the GroupMembers component into your application. - - - -```swift -let group = Group(guid: <#T##String#>, name: <#T##String#>, groupType: <#T##CometChat.groupType#>, password: <#T##String?#>) -let cometChatGroupMembers = CometChatGroupMembers(group: group) -let naviVC = UINavigationController(rootViewController: cometChatGroupMembers) -self.present(naviVC, animated: true) -``` - - - - - - - -If you are already using a navigation controller, you can use the pushViewController function instead of presenting the view controller. - - - -*** - -### Actions - -[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -1. ##### set(onItemClick:) - -`set(OnItemClick:)` is triggered when you click on a ListItem of the groups component. This `set(OnItemClick:)` method proves beneficial when a user intends to customize the on-click behavior in CometChatGroupMembers. - - - -```swift -cometChatGroupMembers.set(onItemClick: { user, indexPath in - // Override on item click -}) -``` - - - - - -*** - -2. ##### set(OnItemLongClick:) - -`set(OnItemLongClick:)` is triggered when you long press on a ListItem of the group members component. This `set(OnItemLongClick:)` method proves beneficial when a user intends to additional functionality on long press on list item in CometChatGroupMembers. - - - -```swift -cometChatGroupMembers.set(onItemLongClick: { groupMember, indexPath in - // Override on item click -}) -``` - - - - - -*** - -##### 3. set(onBack:) - -This `set(onBack:)` method becomes valuable when a user needs to override the action triggered upon pressing the back button in CometChatGroupMembers. - - - -```swift -cometChatGroupMembers.set(onBack: { - // Override on back -}) -``` - - - - - -*** - -##### 4. set(onSelection:) - -The `set(onSelection:)` only gets trigger when selection mode is set to multiple of single. And this gets trigger on every selection, and returns the list of selected group members. - - - -```swift - -cometChatGroupMembers.set(onSelection: { groupMembers in - //Handle action -}) -``` - - - - - -*** - -##### 5. set(onError:) - -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatGroupMembers. - - - -```swift -cometChatGroupMembers.set(onError: { error in - // Override on error -}) -``` - - - - - -*** - -##### 6. set(onEmpty:) - -This `set(onEmpty:)` method is triggered when the groups list is empty in CometChatGroupMembers. - - - -```swift -cometChatGroupMembers.set(onEmpty: { - // Handle empty state -}) -``` - - - - - -*** - -##### 7. setOnLoad - -This set(onLoad:) gets triggered when a group members list is fully fetched and going to displayed on the screen, this return the list of group members to get displayed on the screen. - - - -```swift -cometChatGroupMembers.set(onLoad: { groups in - // Handle loaded users -}) -``` - - - - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a `Component`. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. - -##### 1. GroupsRequestBuilder - -The [GroupsRequestBuilder](/sdk/ios/retrieve-groups) enables you to filter and customize the group list based on available parameters in GroupsRequestBuilder. This feature allows you to create more specific and targeted queries when fetching groups. The following are the parameters available in [GroupsRequestBuilder](/sdk/ios/retrieve-groups) - -| Methods | Type | Description | -| -------------------- | --------- | ------------------------------------------------------------------------------------------------------------------- | -| **setLimit** | Int | Configure the maximum number of groups to fetch in a single request, optimizing pagination for smoother navigation. | -| **setSearchKeyword** | String | Employed to retrieve groups that match the provided string, facilitating precise searches. | -| **scopes** | \[String] | used for fetching group members based on multiple scopes | - -**Example** - -In the example below, we are applying a filter to the Group List based on limit and scope. - - - -```swift -let group = Group(guid: "mrc-uid", name: "", groupType: .public, password: .none) -let groupMembersRequestBuilder = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid).set(limit: 2).set(scopes: ["admin"]) - -let cometChatGroupMembers = CometChatGroupMembers(group: group, groupMembersRequestBuilder: groupMembersRequestBuilder) - -let naviVC = UINavigationController(rootViewController: cometChatGroupMembers) -self.present(naviVC, animated: true) -``` - - - - - -##### 2. SearchRequestBuilder +## Prerequisites -The SearchRequestBuilder uses [GroupsRequestBuilder](/sdk/ios/retrieve-groups) enables you to filter and customize the search list based on available parameters in GroupsRequestBuilder. This feature allows you to keep uniformity between the displayed Groups List and searched Group List. +Before using this component: +1. [Initialize CometChat UI Kit](/ui-kit/ios/getting-started) +2. [Log in a user](/ui-kit/ios/getting-started#step-4-initialize-and-login) +3. Have a valid `Group` object -**Example** +## Basic Usage - - ```swift -let group = Group(guid: "mrc-uid", name: "", groupType: .public, password: .none) -let groupMembersRequestBuilder = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid) - .set(searchKeyword: "") - -let cometChatGroupMembers = CometChatGroupMembers(group: group, groupMembersRequestBuilder: groupMembersRequestBuilder) +import UIKit +import CometChatUIKitSwift +import CometChatSDK -let naviVC = UINavigationController(rootViewController: cometChatGroupMembers) -self.present(naviVC, animated: true) +class GroupDetailViewController: UIViewController { + + var group: Group! + + func showGroupMembers() { + let groupMembers = CometChatGroupMembers(group: group) + let nav = UINavigationController(rootViewController: groupMembers) + present(nav, animated: true) + } +} ``` - - - - -*** - -### Events - -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +## Production-Ready Implementation -Events emitted by the Join Group component is as follows. +Complete example with member actions and navigation: -| Event | Description | -| ---------------------------- | ----------------------------------------------------------------- | -| **onGroupMemberBan** | Triggers when the group member banned from the group successfully | -| **onGroupMemberKick** | Triggers when the group member kicked from the group successfully | -| **onGroupMemberChangeScope** | Triggers when the group member scope is changed in the group | - - - ```swift -// View controller from your project where you want to listen events. -public class ViewController: UIViewController { +import UIKit +import CometChatUIKitSwift +import CometChatSDK - public override func viewDidLoad() { +class GroupMembersViewController: UIViewController { + + var group: Group! + + override func viewDidLoad() { super.viewDidLoad() - - // Subscribing for the listener to listen events from user module - CometChatGroupEvents.addListener("UNIQUE_ID", self as CometChatGroupEventListener) + setupGroupMembers() } -} - // Listener events from groups module -extension ViewController: CometChatGroupEventListener { - public func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { - // Do Stuff + + private func setupGroupMembers() { + let groupMembers = CometChatGroupMembers(group: group) + + // Handle member tap + groupMembers.set(onItemClick: { [weak self] member, indexPath in + self?.showMemberProfile(member) + }) + + // Handle long press for options + groupMembers.set(onItemLongClick: { [weak self] member, indexPath in + self?.showMemberOptions(member) + }) + + // Handle errors + groupMembers.set(onError: { error in + print("Error: \(error.errorDescription)") + }) + + // Handle empty state + groupMembers.set(onEmpty: { + print("No members found") + }) + + // Handle back button + groupMembers.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) + }) + + navigationController?.pushViewController(groupMembers, animated: true) } - public func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { - // Do Stuff + + private func showMemberProfile(_ member: GroupMember) { + // Open user profile or start direct chat + let messages = CometChatMessages() + messages.set(user: member) + navigationController?.pushViewController(messages, animated: true) } - public func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { - // Do Stuff + + private func showMemberOptions(_ member: GroupMember) { + let alert = UIAlertController(title: member.name, message: nil, preferredStyle: .actionSheet) + + alert.addAction(UIAlertAction(title: "Message", style: .default) { [weak self] _ in + self?.showMemberProfile(member) + }) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + present(alert, animated: true) } } ``` -```swift Emitting Group Events -///emit this when group member is banned from the group by logged in user. -CometChatGroupEvents.emitOnGroupMemberBan(bannedUser: User, bannedGroup: Group, bannedBy: User) - -///emit this when group member is kicked from the group by logged in user. -CometChatGroupEvents.emitOnGroupMemberKick(kickedUser: User, kickedGroup: Group, kickedBy: User) - -///emit this when group member's scope is changed by logged in user. -CometChatGroupEvents.emitOnGroupMemberChangeScope(updatedBy: User , updatedUser: User , scopeChangedTo: CometChat.MemberScope , scopeChangedFrom: CometChat.MemberScope, group: Group) -``` - - +## Filter Members - +Use `GroupMembersRequestBuilder` to filter the member list: -*** +```swift +// Filter by scope (admin, moderator, participant) +let requestBuilder = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid) + .set(limit: 20) + .set(scopes: ["admin", "moderator"]) - - -```swift View Controller -public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from user module -CometChatGroupEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") -} +let groupMembers = CometChatGroupMembers( + group: group, + groupMembersRequestBuilder: requestBuilder +) ``` - +```swift +// Search members +let searchBuilder = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid) + .set(searchKeyword: "john") - +let groupMembers = CometChatGroupMembers( + group: group, + groupMembersRequestBuilder: searchBuilder +) +``` -## Customization +## Actions Reference -To fit your app's design requirements, you can customize the appearance of the Groups component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +| Method | Description | +|--------|-------------| +| `set(onItemClick:)` | Member tapped | +| `set(onItemLongClick:)` | Member long-pressed | +| `set(onBack:)` | Back button pressed | +| `set(onSelection:)` | Selection changed (multi-select mode) | +| `set(onError:)` | Error occurred | +| `set(onEmpty:)` | No members found | +| `set(onLoad:)` | Members loaded | -### Style +## Hide UI Elements -Using **Style** you can **customize** the look and feel of the component in your app, These parameters typically control elements such as the **color**, **size**, **shape**, and **fonts** used within the component. +```swift +let groupMembers = CometChatGroupMembers(group: group) -##### 1. GroupMembers Style +groupMembers.hideSearch = true // Hide search bar +groupMembers.hideUserStatus = true // Hide online/offline status +groupMembers.hideKickMemberOption = true // Hide kick option +groupMembers.hideBanMemberOption = true // Hide ban option +groupMembers.hideScopeChangeOption = true // Hide role change option +groupMembers.hideNavigationBar = true // Hide navigation bar +groupMembers.hideBackIcon = true // Hide back button +``` -You can set the `GroupMembersStyle` to the `Group Memebers` Component to customize the styling. +## Styling -**Global level styling** +### Quick Styling - - ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) - -CometChatGroupMembers.style.titleColor = UIColor(hex: "#F76808") -CometChatGroupMembers.style.titleFont = UIFont(name: "Times-New-Roman", size: 34) -CometChatGroupMembers.avatarStyle = customAvatarStyle -``` +// Global styling +CometChatGroupMembers.style.titleColor = UIColor(hex: "#6851D6") +CometChatGroupMembers.style.titleFont = .systemFont(ofSize: 20, weight: .bold) +CometChatGroupMembers.style.backgroundColor = .systemBackground - - - +// Custom avatar style +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) +CometChatGroupMembers.avatarStyle = avatarStyle +``` -**Instance level styling** +### Instance Styling - - ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) - let groupMembersStyle = GroupMembersStyle() groupMembersStyle.titleColor = UIColor(hex: "#F76808") -groupMembersStyle.titleFont = UIFont(name: "Times-New-Roman", size: 34) - -let groupMember = CometChatGroupMembers() -groupMember.style = groupMembersStyle -groupMember.avatarStyle = customAvatarStyle -``` - - +groupMembersStyle.backgroundColor = .white +groupMembersStyle.listItemTitleTextColor = .black - +let groupMembers = CometChatGroupMembers(group: group) +groupMembers.style = groupMembersStyle +``` -List of properties exposed by GroupMemberStyle - -| Property | Description | Code | -| --------------------------------- | ---------------------------------------------------- | ------------------------------------------------ | -| retryButtonTextColor | Sets the text color for the retry button. | `.retryButtonTextColor: UIColor` | -| retryButtonTextFont | Sets the text font for the retry button. | `.retryButtonTextFont: UIFont` | -| retryButtonBackgroundColor | Sets the background color for the retry button. | `.retryButtonBackgroundColor: UIColor` | -| retryButtonBorderColor | Sets the border color for the retry button. | `.retryButtonBorderColor: UIColor` | -| retryButtonBorderWidth | Sets the border width for the retry button. | `.retryButtonBorderWidth: CGFloat` | -| retryButtonCornerRadius | Sets the corner radius for the retry button. | `.retryButtonCornerRadius: CometChatCornerStyle` | -| listItemSelectedBackground | Sets the background color for selected list items. | `.listItemSelectedBackground: UIColor` | -| listItemDeSelectedImageTint | Sets the tint color for deselected list item images. | `.listItemDeSelectedImageTint: UIColor` | -| listItemSelectionImageTint | Sets the tint color for selected list item images. | `.listItemSelectionImageTint: UIColor` | -| listItemSelectedImage | Sets the image for selected list items. | `.listItemSelectedImage: UIImage` | -| listItemDeSelectedImage | Sets the image for deselected list items. | `.listItemDeSelectedImage: UIImage` | -| backgroundColor | Sets the background color. | `.backgroundColor: UIColor` | -| borderWidth | Sets the border width. | `.borderWidth: CGFloat` | -| borderColor | Sets the border color. | `.borderColor: UIColor` | -| cornerRadius | Sets the corner radius style. | `.cornerRadius: CometChatCornerStyle` | -| titleFont | Sets the font for the title. | `.titleFont: UIFont?` | -| largeTitleFont | Sets the font for the large title. | `.largeTitleFont: UIFont?` | -| titleColor | Sets the color for the title text. | `.titleColor: UIColor?` | -| largeTitleColor | Sets the color for the large title text. | `.largeTitleColor: UIColor?` | -| navigationBarTintColor | Sets the tint color for the navigation bar. | `.navigationBarTintColor: UIColor?` | -| navigationBarItemsTintColor | Sets the tint color for navigation bar items. | `.navigationBarItemsTintColor: UIColor?` | -| errorTitleTextFont | Sets the font for the error title text. | `.errorTitleTextFont: UIFont` | -| errorTitleTextColor | Sets the color for the error title text. | `.errorTitleTextColor: UIColor` | -| errorSubTitleFont | Sets the font for the error subtitle text. | `.errorSubTitleFont: UIFont` | -| errorSubTitleTextColor | Sets the color for the error subtitle text. | `.errorSubTitleTextColor: UIColor` | -| emptyTitleTextFont | Sets the font for the empty state title text. | `.emptyTitleTextFont: UIFont` | -| emptyTitleTextColor | Sets the color for the empty state title text. | `.emptyTitleTextColor: UIColor` | -| emptySubTitleFont | Sets the font for the empty state subtitle text. | `.emptySubTitleFont: UIFont` | -| emptySubTitleTextColor | Sets the color for the empty state subtitle text. | `.emptySubTitleTextColor: UIColor` | -| tableViewSeparator | Sets the color for the table view separator. | `.tableViewSeparator: UIColor` | -| listItemTitleTextColor | Sets the text color for list item titles. | `.listItemTitleTextColor: UIColor` | -| listItemTitleFont | Sets the font for list item titles. | `.listItemTitleFont: UIFont` | -| listItemSubTitleTextColor | Sets the text color for list item subtitles. | `.listItemSubTitleTextColor: UIColor` | -| listItemSubTitleFont | Sets the font for list item subtitles. | `.listItemSubTitleFont: UIFont` | -| listItemBackground | Sets the background color for list items. | `.listItemBackground: UIColor` | -| listItemBorderWidth | Sets the border width for list items. | `.listItemBorderWidth: CGFloat` | -| listItemBorderColor | Sets the border color for list items. | `.listItemBorderColor: UIColor` | -| listItemCornerRadius | Sets the corner radius for list items. | `.listItemCornerRadius: CometChatCornerStyle` | -| messageTypeImageTint | Sets the tint color for message type icons. | `.messageTypeImageTint: UIColor` | -| passwordGroupImageTintColor | Sets the tint color for password group icons. | `.passwordGroupImageTintColor: UIColor` | -| passwordGroupImageBackgroundColor | Sets the background color for password group icons. | `.passwordGroupImageBackgroundColor: UIColor` | -| privateGroupImageTintColor | Sets the tint color for private group icons. | `.privateGroupImageTintColor: UIColor` | -| privateGroupImageBackgroundColor | Sets the background color for private group icons. | `.privateGroupImageBackgroundColor: UIColor` | - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - - -```swift -let cometChatGroupMembers = CometChatGroupMembers(group: group) -cometChatGroupMembers.set(title: "Cc", mode: .automatic) -cometChatGroupMembers.disable(usersPresence: true) -``` +## Custom Views - +### Custom List Item - +Replace the entire member row with your own design: -| Method | Description | Code | -| -------------------------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------- | -| set(groupMembersRequestBuilder:) | Sets the request builder for fetching group members. | `set(groupMembersRequestBuilder: GroupMembersRequest.GroupMembersRequestBuilder)` | -| set(searchRequestBuilder:) | Sets the request builder for searching group members. | `set(searchRequestBuilder: searchRequestBuilder)` | -| set(searchKeyword:) | Sets the search keyword to filter group members. | `set(searchKeyword: "group_name")` | -| hideError | Hides the error state view. | `hideError = true` | -| hideUserStatus | Hides the online/offline status of users. | `hideUserStatus = true` | -| hideNavigationBar | Hides or shows the navigation bar. | `hideNavigationBar = true` | -| hideLoadingState | Hides the loading state indicator. | `hideLoadingState = true` | -| hideBackIcon | Hides the back button/icon. | `hideBackIcon = true` | -| hideKickMemberOption | Hides the option to kick a member from the group. | `hideKickMemberOption = true` | -| hideBanMemberOption | Hides the option to ban a member from the group. | `hideBanMemberOption = true` | -| hideScopeChangeOption | Hides the option to change a member’s scope (role). | `hideScopeChangeOption = true` | -| hideSearch | Hides the search bar. | `hideSearch = true` | - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. - -The `Join Group` component does not provide additional functionalities beyond this level of customization. - -#### SetListItemView - -Utilize this property to assign a custom ListItem to the GroupMembers Component, allowing for enhanced customization and flexibility in its rendering. - - - ```swift -let cometChatGroupMembers = CometChatGroupMembers(group: group) -cometChatGroupMembers.set(listItemView:{ groupMember in - let customListItemGroupView = CustomListItemGroupView() - customListItemGroupView.configure(with: groupMember!) // pass group member here - return customListItemGroupView +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(listItemView: { member in + let customView = MemberRowView() + customView.configure(with: member!) + return customView }) ``` - - - - -**Example** - -In this example, we will create a UIView file `CustomListItemGroupView` and pass it inside the `setListItemView()` method. - -```swift CustomListItemGroupView - +```swift +// MemberRowView.swift import UIKit import CometChatSDK import CometChatUIKitSwift -class CustomListItemView: UIView { - - private let profileImageView: CometChatAvatar = { - let imageView = CometChatAvatar() - imageView.layer.cornerRadius = 12 // Rounded corners - imageView.translatesAutoresizingMaskIntoConstraints = false - return imageView - }() +class MemberRowView: UIView { - private let nameLabel: UILabel = { - let label = UILabel() - label.textColor = .black - label.font = UIFont.boldSystemFont(ofSize: 18) - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() - - private let roleBadgeButton: UIButton = { - let button = UIButton(type: .system) - button.setTitle("Owner", for: .normal) - button.setTitleColor(.white, for: .normal) - button.backgroundColor = UIColor.purple - button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium) - button.layer.cornerRadius = 12 - button.translatesAutoresizingMaskIntoConstraints = false - return button - }() + private let avatar = CometChatAvatar(image: UIImage()) + private let nameLabel = UILabel() + private let roleButton = UIButton(type: .system) override init(frame: CGRect) { super.init(frame: frame) - setupView() + setupUI() } required init?(coder: NSCoder) { - super.init(coder: coder) - setupView() + fatalError("init(coder:) has not been implemented") } - private func setupView() { - addSubview(profileImageView) - addSubview(nameLabel) - addSubview(roleBadgeButton) + private func setupUI() { + avatar.translatesAutoresizingMaskIntoConstraints = false + avatar.layer.cornerRadius = 20 - NSLayoutConstraint.activate([ - // Profile Image Constraints - profileImageView.leadingAnchor.constraint(equalTo: leadingAnchor), - profileImageView.centerYAnchor.constraint(equalTo: centerYAnchor), - profileImageView.widthAnchor.constraint(equalToConstant: 50), - profileImageView.heightAnchor.constraint(equalToConstant: 50), - - // Name Label Constraints - nameLabel.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 12), - nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor), - - // Role Badge Button Constraints - roleBadgeButton.leadingAnchor.constraint(greaterThanOrEqualTo: nameLabel.trailingAnchor, constant: 12), - roleBadgeButton.trailingAnchor.constraint(equalTo: trailingAnchor), - roleBadgeButton.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor), - roleBadgeButton.heightAnchor.constraint(equalToConstant: 24), - roleBadgeButton.widthAnchor.constraint(equalToConstant: 70) - ]) - } - - // Method to configure the view with data - func configure(with groupMember: GroupMember) { - nameLabel.text = groupMember.name ?? "" - profileImageView.setAvatar(avatarUrl: groupMember.avatar ?? "") - roleBadgeButton.setTitle("\(groupMember.scope)", for: .normal) - } -} -``` - -*** - -#### SetLeadingView - -You can modify the leading view of a group member cell using .set(leadingView:). - - - -```swift -cometChatGroupMember.set(leadingView: { groupMember in - let view = CustomLeadingView() - view.configure(with groupMember: groupMember) - return view -}) -``` - - - - - -Demonstration - - - - - -You can create a `CustomLeadingView` as a custom `UIView`. Which we will inflate in `setLeadingView()` - - - -```swift -import UIKit - -class CustomLeadingView: UIView { - - private let profileImageView: CometChatAvatar = { - let imageView = CometChatAvatar() - imageView.layer.cornerRadius = 12 // Rounded corners - imageView.translatesAutoresizingMaskIntoConstraints = false - return imageView - }() - - private let badgeContainer: UIView = { - let view = UIView() - view.backgroundColor = UIColor.blue - view.layer.cornerRadius = 8 - view.translatesAutoresizingMaskIntoConstraints = false - return view - }() - - private let starIcon: UIImageView = { - let imageView = UIImageView() - imageView.image = UIImage(systemName: "star.fill") // SF Symbol for star - imageView.tintColor = .yellow - imageView.translatesAutoresizingMaskIntoConstraints = false - return imageView - }() - - private let roleLabel: UILabel = { - let label = UILabel() - label.textColor = .white - label.font = UIFont.boldSystemFont(ofSize: 16) - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() - - override init(frame: CGRect) { - super.init(frame: frame) - setupView() - } - - required init?(coder: NSCoder) { - super.init(coder: coder) - setupView() - } - - private func setupView() { - addSubview(profileImageView) - addSubview(badgeContainer) - badgeContainer.addSubview(starIcon) - badgeContainer.addSubview(roleLabel) + nameLabel.translatesAutoresizingMaskIntoConstraints = false + nameLabel.font = .systemFont(ofSize: 16, weight: .semibold) - NSLayoutConstraint.activate([ - profileImageView.topAnchor.constraint(equalTo: topAnchor), - profileImageView.leadingAnchor.constraint(equalTo: leadingAnchor), - profileImageView.trailingAnchor.constraint(equalTo: trailingAnchor), - profileImageView.heightAnchor.constraint(equalTo: profileImageView.widthAnchor), // Square shape - - badgeContainer.leadingAnchor.constraint(equalTo: profileImageView.leadingAnchor), - badgeContainer.trailingAnchor.constraint(equalTo: profileImageView.trailingAnchor), - badgeContainer.bottomAnchor.constraint(equalTo: profileImageView.bottomAnchor), - badgeContainer.heightAnchor.constraint(equalToConstant: 40), - - starIcon.leadingAnchor.constraint(equalTo: badgeContainer.leadingAnchor, constant: 10), - starIcon.centerYAnchor.constraint(equalTo: badgeContainer.centerYAnchor), - starIcon.widthAnchor.constraint(equalToConstant: 20), - starIcon.heightAnchor.constraint(equalToConstant: 20), - - roleLabel.leadingAnchor.constraint(equalTo: starIcon.trailingAnchor, constant: 5), - roleLabel.centerYAnchor.constraint(equalTo: badgeContainer.centerYAnchor) - ]) - } - - func configure(with groupMember: GroupMember) { - if let avatarUrl = groupMember.avatar { - groupImageView.setAvatar(avatarUrl: avatarUrl, with: groupMember.name ?? "") - } - roleLabel.text = "\(groupMember.scope)" - } -} -``` - - - - - -*** - -#### SetTitleView - -You can customize the title view of a group member cell using .set(titleView:). - - - -```swift -cometChatGroupMember.set(titleView: { groupMember in - let view = CustomTitleView() - view.configure(with groupMember: groupMember) - return view -}) -``` - - - - - -Demonstration - - - - - -You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()` - - - -```swift - import UIKit - -class CustomTitleView: UIView { - - private let nameLabel: UILabel = { - let label = UILabel() - label.font = UIFont.boldSystemFont(ofSize: 20) - label.textColor = .black - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() - - private let roleButton: UIButton = { - let button = UIButton() - button.setTitleColor(.white, for: .normal) - button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) - button.backgroundColor = .blue - button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10) - button.layer.cornerRadius = 12 - button.translatesAutoresizingMaskIntoConstraints = false - return button - }() - - override init(frame: CGRect) { - super.init(frame: frame) - setupView() - } - - required init?(coder: NSCoder) { - super.init(coder: coder) - setupView() - } - - private func setupView() { + roleButton.translatesAutoresizingMaskIntoConstraints = false + roleButton.titleLabel?.font = .systemFont(ofSize: 12, weight: .medium) + roleButton.setTitleColor(.white, for: .normal) + roleButton.backgroundColor = .systemPurple + roleButton.layer.cornerRadius = 10 + roleButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) + + addSubview(avatar) addSubview(nameLabel) addSubview(roleButton) NSLayoutConstraint.activate([ - nameLabel.leadingAnchor.constraint(equalTo: leadingAnchor), + avatar.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), + avatar.centerYAnchor.constraint(equalTo: centerYAnchor), + avatar.widthAnchor.constraint(equalToConstant: 40), + avatar.heightAnchor.constraint(equalToConstant: 40), + + nameLabel.leadingAnchor.constraint(equalTo: avatar.trailingAnchor, constant: 12), nameLabel.centerYAnchor.constraint(equalTo: centerYAnchor), - roleButton.leadingAnchor.constraint(equalTo: nameLabel.trailingAnchor, constant: 8), - roleButton.centerYAnchor.constraint(equalTo: centerYAnchor), - roleButton.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor) + roleButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), + roleButton.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } - func configure(with groupMember: GroupMember) { - nameLabel.text = groupMember.name ?? "" - roleButton.setTitle("\(groupMember.scope)", for: .normal) + func configure(with member: GroupMember) { + nameLabel.text = member.name ?? "" + avatar.setAvatar(avatarUrl: member.avatar ?? "", with: member.name ?? "") + roleButton.setTitle(member.scope.rawValue.capitalized, for: .normal) } } ``` - - - - -*** +### Custom Subtitle View -#### SetTrailView +Customize the subtitle area below the member name: -You can set a custom Tailview using `.setTailView()` to match the `TailView` view of your app. - - - ```swift -let cometChatGroupMembers = CometChatGroupMembers(group: group) -cometChatGroupMembers.setTailView(tailView: { groupMember in - let customTailGroupView = CustomTailGroupView() - customTailGroupView.configure(with: groupMember!) - return customTailGroupView +groupMembers.setSubtitleView(subtitleView: { member in + let label = UILabel() + label.font = .systemFont(ofSize: 12) + label.textColor = .secondaryLabel + + let date = Date(timeIntervalSince1970: Double(member!.joinedAt)) + let formatter = DateFormatter() + formatter.dateStyle = .medium + label.text = "Joined: \(formatter.string(from: date))" + + return label }) ``` - - - - -**Example** - - + -In this example, we will create a UIView file `Custom_Tail_GroupView` and pass it inside the `.setTailView()` method. - -```swift Custom_Tail_GroupView - -import UIKit -import CometChatSDK -import CometChatUIKitSwift - -class CustomTailGroupView: UIView { - - let tailLabel: UILabel = { - let label = UILabel() - label.translatesAutoresizingMaskIntoConstraints = false - label.font = UIFont.systemFont(ofSize: 10, weight: .semibold) - label.textColor = UIColor(hex: "#6852D6") - return label - }() - - override init(frame: CGRect) { - super.init(frame: frame) - addSubview(tailLabel) - NSLayoutConstraint.activate([ - tailLabel.centerXAnchor.constraint(equalTo: centerXAnchor), - tailLabel.centerYAnchor.constraint(equalTo: centerYAnchor), - self.heightAnchor.constraint(equalToConstant: 22), - self.layer.cornerRadius = 11 - ]) - self.backgroundColor = UIColor(hex: "#EDEAFA") - } +### Custom Tail View - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } +Add custom content on the right side of each row: - // Configure the view with a group member - func configure(with groupMember: GroupMember) { - tailLabel.text = "\(groupMember.name!.description )" - } -} -``` - -*** - -#### SubtitleView - -You can set your custom Subtitle view using the `.setSubtitleView()` method. But keep in mind, by using this you will override the default Subtitle view functionality. - - - ```swift -let cometChatGroupMembers = CometChatGroupMembers(group: group) -cometChatGroupMembers.setSubtitleView(subtitleView: { groupMember in - let customSubtitleGroupMemberView = CustomSubtitleGroupMemberView() - customSubtitleGroupMemberView.configure(with: groupMember!) - return customSubtitleGroupMemberView +groupMembers.setTailView(tailView: { member in + let badge = UILabel() + badge.text = member!.scope.rawValue.capitalized + badge.font = .systemFont(ofSize: 10, weight: .semibold) + badge.textColor = UIColor(hex: "#6852D6") + badge.backgroundColor = UIColor(hex: "#EDEAFA") + badge.textAlignment = .center + badge.layer.cornerRadius = 10 + badge.clipsToBounds = true + return badge }) ``` - - - - -* You can customize the subtitle view for each GroupMembers item to meet your requirements - -**Example** - - + -In this example, we will create a `Custom_Subtitle_GroupMember_View`a UIView file. +## Custom Swipe Options -```swift Custom_Subtitle_GroupMember_View +Add custom actions when swiping on a member: -import UIKit -import CometChatSDK -import CometChatUIKitSwift - -class CustomSubtitleGroupMemberView: UIView { - - let memberNameLabel: UILabel = { - let label = UILabel() - label.translatesAutoresizingMaskIntoConstraints = false - label.textColor = .init(red: 0.42, green: 0.01, blue: 0.84, alpha: 1.00) - label.font = UIFont.systemFont(ofSize: 15, weight: .bold) - return label - }() - - let joinedAtLabel: UILabel = { - let label = UILabel() - label.translatesAutoresizingMaskIntoConstraints = false - label.textColor = .systemBrown - label.font = UIFont.systemFont(ofSize: 10, weight: .medium) - return label - }() - - override init(frame: CGRect) { - super.init(frame: frame) - addSubview(memberNameLabel) - addSubview(joinedAtLabel) - - NSLayoutConstraint.activate([ - memberNameLabel.topAnchor.constraint(equalTo: topAnchor), - memberNameLabel.leadingAnchor.constraint(equalTo: leadingAnchor), - memberNameLabel.trailingAnchor.constraint(equalTo: trailingAnchor), - - joinedAtLabel.topAnchor.constraint(equalTo: memberNameLabel.bottomAnchor, constant: 2), - joinedAtLabel.leadingAnchor.constraint(equalTo: leadingAnchor), - joinedAtLabel.trailingAnchor.constraint(equalTo: trailingAnchor), - joinedAtLabel.bottomAnchor.constraint(equalTo: bottomAnchor) - ]) - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") +```swift +let deleteOption = CometChatGroupMemberOption( + id: "delete", + title: "Remove", + icon: UIImage(systemName: "trash"), + backgroundColor: .systemRed, + onClick: { member, group, section, option, controller in + print("Remove \(member.name ?? "")") + // Implement remove logic } - - func configure(with groupMember: GroupMember) { - memberNameLabel.text = "Member: \(groupMember.name ?? "")" - - let date = Date(timeIntervalSince1970: Double(groupMember.joinedAt)) - let dateFormatter = DateFormatter() - dateFormatter.dateStyle = .medium - joinedAtLabel.text = "Joined at: \(dateFormatter.string(from: date))" +) + +let messageOption = CometChatGroupMemberOption( + id: "message", + title: "Message", + icon: UIImage(systemName: "message"), + backgroundColor: .systemBlue, + onClick: { member, group, section, option, controller in + let messages = CometChatMessages() + messages.set(user: member) + controller.navigationController?.pushViewController(messages, animated: true) } -} -``` - -*** - -#### Options - -Enhance your GroupsMembers component by setting Custom Options to incorporate additional functionalities when swiping +) - - -```swift -let cometChatGroupMembers = CometChatGroupMembers(group: group) -cometChatGroupMembers.setOptions (options:{ group, groupMember in - //Perform Your Action +groupMembers.setOptions(options: { group, member in + return [messageOption, deleteOption] }) ``` - - - - -* You can customize the options for group members to meet your requirements - -**Example** - -In this example, we've enhanced the interface of `CometChatGroupMembers` by introducing a tailored feature. By adding a custom option, such as "Delete" with a corresponding trash icon, users can now enjoy a more interactive and user-friendly experience. - - - -```swift -let customOption = CometChatGroupMemberOption(id: "custom_option_1", - title: "Delete", - icon: UIImage(systemName: "trash.square"), - backgroundColor: .red, - onClick: { groupMember, group, section, option, controller in - print("Custom option clicked!") -}) - -let cometChatGroupMembers = CometChatGroupMembers(group: group) -cometChatGroupMembers.setOptions(options: { group, groupMember in - return [customOption] -}) -``` - - - - - -*** +## Custom Menu Buttons -#### Menus +Add buttons to the navigation bar: -You can set the Custom Menus to add more options to the Group members component. - - - ```swift -let cometChatGroupMembers = CometChatGroupMembers(group: group) -cometChatGroupMembers.set(menus: [UIBarButtonItem]) +let addButton = UIBarButtonItem( + image: UIImage(systemName: "person.badge.plus"), + style: .plain, + target: self, + action: #selector(addMemberTapped) +) + +groupMembers.set(menus: [addButton]) + +@objc func addMemberTapped() { + // Show add member screen + let addMembers = CometChatAddMembers(group: group) + navigationController?.pushViewController(addMembers, animated: true) +} ``` - - - - -* You can customize the menus for groups to meet your requirements - -**Example** - -In this example, we'll craft a custom button tailored for `CometChatGroupMembers`, enhancing its interface with a personalized `menu` for a more user-friendly experience. - - - -```swift -let customMenuButton: UIBarButtonItem = { - let button = UIButton(type: .system) - button.setImage(UIImage(systemName: "person.badge.plus"), for: .normal) - button.setTitle("", for: .normal) - button.addTarget(self, action: #selector(handleCustomMenu), for: .touchUpInside) - let barButtonItem = UIBarButtonItem(customView: button) - return barButtonItem -}() - -let cometChatGroupMembers = CometChatGroupMembers(group: group) -cometChatGroupMembers.set(menus: [customMenuButton]) -``` +## Listen for Events - +React to member changes in your app: - - -*** - -#### SetLoadingView - -You can set a custom loading view using .set(loadingView:). This method accepts a UIView to display while data is being fetched. - - - ```swift -let loadingIndicator = UIActivityIndicatorView(style: .medium) -loadingIndicator.startAnimating() -cometChatGroupMember.set(loadingView: loadingIndicator) -``` - - - - - -*** - -#### SetErrorView - -You can customize the error view using .set(errorView:). This method accepts a UIView that appears when an error occurs. - - - -```swift -let errorLabel = UILabel() -errorLabel.text = "Something went wrong!" -errorLabel.textColor = .red -cometChatGroupMember.set(errorView: errorLabel) -``` - - - - - -*** - -#### SetEmptyView - -You can customize the empty state view using .set(emptyView:). This method accepts a UIView that appears when no group members are available. - - - -```swift -let emptyLabel = UILabel() -emptyLabel.text = "No groups found" -emptyLabel.textColor = .gray -emptyLabel.textAlignment = .center -cometChatGroupMember.set(emptyView: emptyLabel) +class MyViewController: UIViewController, CometChatGroupEventListener { + + override func viewDidLoad() { + super.viewDidLoad() + CometChatGroupEvents.addListener("member-listener", self) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatGroupEvents.removeListener("member-listener") + } + + // Member kicked + func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { + print("\(kickedUser.name ?? "") was kicked") + } + + // Member banned + func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { + print("\(bannedUser.name ?? "") was banned") + } + + // Member role changed + func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { + print("\(updatedUser.name ?? "") is now \(scopeChangedTo)") + } +} ``` - - - +## Style Properties -*** +| Property | Description | +|----------|-------------| +| `backgroundColor` | Background color | +| `titleColor` | Title text color | +| `titleFont` | Title font | +| `listItemTitleTextColor` | Member name color | +| `listItemTitleFont` | Member name font | +| `listItemSubTitleTextColor` | Subtitle color | +| `listItemBackground` | Row background color | +| `separatorColor` | Row separator color | - +## Troubleshooting -Ensure to pass and present `CometChatGroupMembers`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. +| Issue | Solution | +|-------|----------| +| Empty member list | Verify group GUID is correct | +| Actions not showing | Check user has admin/owner permissions | +| Custom views not appearing | Ensure views have proper constraints | +| Events not firing | Verify listener is added before actions | - +## Related Components -*** +- [Groups](/ui-kit/ios/groups) - List all groups +- [Banned Members](/ui-kit/ios/banned-members) - View banned users From 65441304518631018c363fa1e1e6f0ebe2adcc13 Mon Sep 17 00:00:00 2001 From: Aditya Date: Thu, 12 Feb 2026 13:25:05 +0530 Subject: [PATCH 005/106] modified , groups , ai-agaent-guid, block-unblock guide --- ui-kit/ios/groups.mdx | 1174 +++++++++++------------ ui-kit/ios/guide-ai-agent.mdx | 601 +++++++++--- ui-kit/ios/guide-block-unblock-user.mdx | 762 ++++++++++++--- 3 files changed, 1696 insertions(+), 841 deletions(-) diff --git a/ui-kit/ios/groups.mdx b/ui-kit/ios/groups.mdx index d105be4db..5db2c5ffb 100644 --- a/ui-kit/ios/groups.mdx +++ b/ui-kit/ios/groups.mdx @@ -1,560 +1,583 @@ --- title: "Groups" +description: "Display and manage group chats in your iOS app" --- -## Overview - -`CometChatGroups` functions as a standalone [component](/ui-kit/ios/components-overview#components) designed to create a screen displaying a list of groups, with the added functionality of enabling users to search for specific groups. Acting as a container component, CometChatGroups encapsulates and formats the `CometChatListBase` without introducing any additional behavior of its own. +The `CometChatGroups` component displays a searchable list of groups, enabling users to browse, join, and interact with group conversations. -The `Groups` component is composed of the following BaseComponents: +## Prerequisites -| Components | Description | -| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [CometChatListBase](/ui-kit/ios/list-base) | `CometChatListBase` serves as a container component equipped with a title (navigationBar), search functionality (search-bar), background settings, and a container for embedding a list view. | -| [CometChatListItem](/ui-kit/ios/list-item) | This component renders information extracted from a `Group` object onto a tile, featuring a title, subtitle, leading view, and trailing view. | +Before using this component, ensure you have: -*** +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- User logged in with `CometChatUIKit.login()` +- At least one group created in your CometChat dashboard ## Usage -### Integration +### Basic Implementation -The following code snippet illustrates how you can can launch **CometChatGroups**. +Display a groups list and open messages when a group is tapped: - - ```swift -let groups = CometChatGroups() -let naviVC = UINavigationController(rootViewController: groups) -self.present(naviVC, animated: true) -``` - - - - - - - -If you are already using a navigation controller, you can use the `pushViewController` function instead of presenting the view controller. - - - -### Actions - -[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -1. ##### set(onItemClick:) - -`set(OnItemClick:)` is triggered when you click on a ListItem of the groups component. This `set(OnItemClick:)` method proves beneficial when a user intends to customize the on-click behavior in CometChatGroups. +import UIKit +import CometChatUIKitSwift +import CometChatSDK - - -```swift -cometChatGroups.set(onItemClick: { group, indexPath in - // Override on item click -}) +class GroupsViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + setupGroups() + } + + private func setupGroups() { + let groups = CometChatGroups() + + // Handle group selection + groups.set(onItemClick: { [weak self] group, indexPath in + self?.openMessages(for: group) + }) + + let navController = UINavigationController(rootViewController: groups) + navController.modalPresentationStyle = .fullScreen + present(navController, animated: true) + } + + private func openMessages(for group: Group) { + let messages = CometChatMessages() + messages.set(group: group) + + if let nav = presentedViewController as? UINavigationController { + nav.pushViewController(messages, animated: true) + } + } +} ``` - - - - -*** - -2. ##### set(OnItemLongClick:) +### Production Implementation -`set(OnItemLongClick:)` is triggered when you long press on a ListItem of the groups component. This `set(OnItemLongClick:)` method proves beneficial when a user intends to additional functionality on long press on list item in CometChatGroups. +Complete implementation with selection mode, error handling, and navigation: - - ```swift -cometChatGroups.set(onItemLongClick: { group, indexPath in - // Override on item click -}) -``` - - - - - -*** - -##### 3. set(onBack:) +import UIKit +import CometChatUIKitSwift +import CometChatSDK -This `set(onBack:)` method becomes valuable when a user needs to override the action triggered upon pressing the back button in CometChatGroups. +class ProductionGroupsViewController: UIViewController { + + private var groups: CometChatGroups! + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemBackground + setupGroups() + setupEventListeners() + } + + private func setupGroups() { + // Configure request builder for joined groups only + let requestBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) + .set(joinedOnly: true) + + groups = CometChatGroups(groupsRequestBuilder: requestBuilder) + + // Handle group tap + groups.set(onItemClick: { [weak self] group, indexPath in + self?.openGroupChat(group) + }) + + // Handle long press for options + groups.set(onItemLongClick: { [weak self] group, indexPath in + self?.showGroupOptions(group) + }) + + // Handle back button + groups.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) + }) + + // Handle errors + groups.set(onError: { [weak self] error in + self?.showError(error) + }) + + // Handle empty state + groups.set(onEmpty: { [weak self] in + print("No groups available") + }) + + // Handle loaded groups + groups.set(onLoad: { groups in + print("Loaded \(groups.count) groups") + }) + + navigationController?.pushViewController(groups, animated: true) + } + + private func setupEventListeners() { + CometChatGroupEvents.addListener("groups-vc-listener", self as CometChatGroupEventListener) + } + + private func openGroupChat(_ group: Group) { + let messages = CometChatMessages() + messages.set(group: group) + navigationController?.pushViewController(messages, animated: true) + } + + private func showGroupOptions(_ group: Group) { + let alert = UIAlertController(title: group.name, message: nil, preferredStyle: .actionSheet) + + alert.addAction(UIAlertAction(title: "View Details", style: .default) { [weak self] _ in + self?.showGroupDetails(group) + }) + + alert.addAction(UIAlertAction(title: "Leave Group", style: .destructive) { [weak self] _ in + self?.leaveGroup(group) + }) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + + present(alert, animated: true) + } + + private func showGroupDetails(_ group: Group) { + let details = CometChatGroupDetails() + details.set(group: group) + navigationController?.pushViewController(details, animated: true) + } + + private func leaveGroup(_ group: Group) { + CometChat.leaveGroup(GUID: group.guid) { [weak self] _ in + DispatchQueue.main.async { + self?.groups.remove(group: group) + } + } onError: { error in + print("Leave group error: \(error?.errorDescription ?? "")") + } + } + + private func showError(_ error: CometChatException) { + let alert = UIAlertController( + title: "Error", + message: error.errorDescription, + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } + + deinit { + CometChatGroupEvents.removeListener("groups-vc-listener") + } +} - - -```swift -cometChatGroups.set(onBack: { - // Override on back -}) +// MARK: - Group Event Listener +extension ProductionGroupsViewController: CometChatGroupEventListener { + + func onGroupCreate(group: Group) { + groups.insert(group: group, at: 0) + } + + func onGroupDelete(group: Group) { + groups.remove(group: group) + } + + func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { + groups.update(group: joinedGroup) + } + + func onGroupMemberLeave(leftUser: User, leftGroup: Group) { + groups.update(group: leftGroup) + } + + func onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) { + groups.update(group: group) + } + + func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { + groups.update(group: bannedGroup) + } + + func onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group) { + groups.update(group: unbannedUserGroup) + } + + func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { + groups.update(group: kickedGroup) + } + + func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { + groups.update(group: group) + } + + func onOwnershipChange(group: Group?, member: GroupMember?) { + if let group = group { + groups.update(group: group) + } + } +} ``` - - - +## Actions -*** +Actions let you customize component behavior through callbacks. -##### 4. set(onSelection:) +| Action | Description | +|--------|-------------| +| `set(onItemClick:)` | Triggered when a group is tapped | +| `set(onItemLongClick:)` | Triggered on long press | +| `set(onBack:)` | Triggered when back button is pressed | +| `set(onSelection:)` | Triggered when groups are selected (selection mode) | +| `set(onError:)` | Triggered when an error occurs | +| `set(onEmpty:)` | Triggered when the list is empty | +| `set(onLoad:)` | Triggered when groups are loaded | -The `set(onSelection:)` only gets trigger when selection mode is set to multiple of single. And this gets trigger on every selection, and returns the list of selected groups. - - - ```swift +let groups = CometChatGroups() -cometChatGroups.set(onSelection: { groups in - //Handle action +groups.set(onItemClick: { group, indexPath in + print("Tapped: \(group.name ?? "")") }) -``` - - - - - -*** -##### 5. set(onError:) - -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatGroups. - - - -```swift -cometChatGroups.set(onError: { error in - // Override on error +groups.set(onItemLongClick: { group, indexPath in + print("Long pressed: \(group.name ?? "")") }) -``` - - - - - -*** - -##### 6. set(onEmpty:) - -This `set(onEmpty:)` method is triggered when the groups list is empty in CometChatGroups. - - -```swift -cometChatGroups.set(onEmpty: { - // Handle empty state +groups.set(onBack: { + print("Back button pressed") }) -``` - - - - -*** +groups.set(onSelection: { selectedGroups in + print("Selected \(selectedGroups.count) groups") +}) -##### 7. setOnLoad +groups.set(onError: { error in + print("Error: \(error.errorDescription)") +}) -This set(onLoad:) gets triggered when a group list is fully fetched and going to displayed on the screen, this return the list of groups to get displayed on the screen. +groups.set(onEmpty: { + print("No groups found") +}) - - -```swift -cometChatGroups.set(onLoad: { groups in - // Handle loaded groups +groups.set(onLoad: { groups in + print("Loaded \(groups.count) groups") }) ``` - +## Filters - +Filter the groups list using `GroupsRequestBuilder`. -*** +| Method | Type | Description | +|--------|------|-------------| +| `setLimit` | Int | Maximum groups per request | +| `setSearchKeyword` | String | Filter by search term | +| `joinedOnly` | Bool | Show only joined groups | +| `setTags` | [String] | Filter by tags | +| `withTags` | Bool | Include tag information | -### Filters +### Show Only Joined Groups -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. - -##### 1. GroupsRequestBuilder - -The [GroupsRequestBuilder](/sdk/ios/retrieve-groups) enables you to filter and customize the group list based on available parameters in GroupsRequestBuilder. This feature allows you to create more specific and targeted queries when fetching groups. The following are the parameters available in [GroupsRequestBuilder](/sdk/ios/retrieve-groups) - -| Methods | Type | Description | -| -------------------- | --------- | ------------------------------------------------------------------------------------------------------------------- | -| **setLimit** | Int | Configure the maximum number of groups to fetch in a single request, optimizing pagination for smoother navigation. | -| **setSearchKeyword** | String | Employed to retrieve groups that match the provided string, facilitating precise searches. | -| **joinedOnly** | boolean | Exclusively fetches joined groups. | -| **setTags** | \[String] | Utilized to fetch groups containing the specified tags. | -| **withTags** | boolean | Utilized to retrieve groups with specific tags. | - -**Example** - -In the example below, we are applying a filter to the Group List based on only joined groups. - - - ```swift -// You can create GroupRequestBuilder as per your requirement -let groupsRequestBuilder = GroupsRequest.GroupsRequestBuilder(limit: 20).set(joinedOnly: true) +let requestBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) + .set(joinedOnly: true) -let groups = CometChatGroups(groupsRequestBuilder: groupsRequestBuilder) -let naviVC = UINavigationController(rootViewController: groups) -self.present(naviVC, animated: true) +let groups = CometChatGroups(groupsRequestBuilder: requestBuilder) ``` - - - - -##### 2. SearchRequestBuilder - -The SearchRequestBuilder uses [GroupsRequestBuilder](/sdk/ios/retrieve-groups) enables you to filter and customize the search list based on available parameters in GroupsRequestBuilder. This feature allows you to keep uniformity between the displayed Groups List and searched Group List. +### Search Groups -**Example** - - - ```swift -// You can create GroupRequestBuilder as per your requirement -let groupsRequestBuilder = GroupsRequest.GroupsRequestBuilder(limit: 2).set(searchKeyword: "") +let searchBuilder = GroupsRequest.GroupsRequestBuilder(limit: 20) + .set(searchKeyword: "design") -let groups = CometChatGroups(groupsRequestBuilder: groupsRequestBuilder) -let naviVC = UINavigationController(rootViewController: groups) -self.present(naviVC, animated: true) +let groups = CometChatGroups(groupsRequestBuilder: searchBuilder) ``` - - - +### Filter by Tags -*** +```swift +let tagBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) + .set(tags: ["engineering", "marketing"]) + .set(withTags: true) -### Events +let groups = CometChatGroups(groupsRequestBuilder: tagBuilder) +``` -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +## Events -The list of events emitted by the Groups component is as follows. +Listen for group-related events across your app. -| Event | Description | -| ---------------------------- | -------------------------------------------------------------------------------------------------------- | -| **onGroupCreate** | This gets triggered when the logged in user creates a group. | -| **onGroupDelete** | This gets triggered when the logged in user deletes a group. | -| **onGroupMemberLeave** | This gets triggered when the logged in user leaves a group. | -| **onGroupMemberChangeScope** | This gets triggered when the logged in user changes the scope of another group member. | -| **onGroupMemberBan** | This gets triggered when the logged in user bans a group member from the group. | -| **onGroupMemberKick** | This gets triggered when the logged in user kicks another group member from the group. | -| **onGroupMemberUnban** | This gets triggered when the logged in user unbans a user banned from the group. | -| **onGroupMemberJoin** | This gets triggered when the logged in user joins a group. | -| **onGroupMemberAdd** | This gets triggered when the logged in user adds new members to the group. | -| **onOwnershipChange** | This gets triggered when the logged in user transfers the ownership of their group to some other member. | +| Event | Description | +|-------|-------------| +| `onGroupCreate` | Group was created | +| `onGroupDelete` | Group was deleted | +| `onGroupMemberJoin` | User joined a group | +| `onGroupMemberLeave` | User left a group | +| `onGroupMemberAdd` | Members were added | +| `onGroupMemberBan` | Member was banned | +| `onGroupMemberUnban` | Member was unbanned | +| `onGroupMemberKick` | Member was kicked | +| `onGroupMemberChangeScope` | Member scope changed | +| `onOwnershipChange` | Group ownership transferred | -Adding `CometChatGroupsEvents` Listener's +### Add Event Listener - - ```swift -// View controller from your project where you want to listen events. -public class ViewController: UIViewController { +import UIKit +import CometChatUIKitSwift +import CometChatSDK - public override func viewDidLoad() { +class GroupEventsViewController: UIViewController { + + private let listenerID = "group-events-listener" + + override func viewDidLoad() { super.viewDidLoad() - - // Subscribing for the listener to listen events from user module - CometChatGroupEvents.addListener("UNIQUE_ID", self as CometChatGroupEventListener) + CometChatGroupEvents.addListener(listenerID, self as CometChatGroupEventListener) } - -} - - // Listener events from groups module -extension ViewController: CometChatGroupEventListener { - - public func onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) { - // Do Stuff + + deinit { + CometChatGroupEvents.removeListener(listenerID) } +} - public func onCreateGroupClick() { - // Do Stuff +extension GroupEventsViewController: CometChatGroupEventListener { + + func onGroupCreate(group: Group) { + print("Group created: \(group.name ?? "")") } - - public func onGroupCreate(group: Group) { - // Do Stuff + + func onGroupDelete(group: Group) { + print("Group deleted: \(group.name ?? "")") } - - public func onGroupDelete(group: Group) { - // Do Stuff + + func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { + print("\(joinedUser.name ?? "") joined \(joinedGroup.name ?? "")") } - - public func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { - // Do Stuff + + func onGroupMemberLeave(leftUser: User, leftGroup: Group) { + print("\(leftUser.name ?? "") left \(leftGroup.name ?? "")") } - - public func onGroupMemberLeave(leftUser: User, leftGroup: Group) { - // Do Stuff + + func onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) { + print("\(members.count) members added to \(group.name ?? "")") } - - public func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { - // Do Stuff + + func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { + print("\(bannedUser.name ?? "") banned from \(bannedGroup.name ?? "")") } - - public func onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group) { - // Do Stuff + + func onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group) { + print("\(unbannedUserUser.name ?? "") unbanned from \(unbannedUserGroup.name ?? "")") } - - public func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { - // Do Stuff + + func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { + print("\(kickedUser.name ?? "") kicked from \(kickedGroup.name ?? "")") } - - public func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { - // Do Stuff + + func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { + print("\(updatedUser.name ?? "") scope changed to \(scopeChangedTo)") } - - public func onOwnershipChange(group: Group?, member: GroupMember?) { - // Do Stuff + + func onOwnershipChange(group: Group?, member: GroupMember?) { + print("Ownership transferred to \(member?.name ?? "")") } } ``` - +### Emit Events - - -```swift Emitting Group Events -///you need to pass the [Group] object of the group which is created -CometChatGroupEvents.emitOnGroupCreate(group: Group) - -///you need to pass the [Group] object of the group which is deleted -CometChatGroupEvents.emitOnGroupDelete(group: Group) - -///emit this when logged in user leaves the group. -CometChatGroupEvents.emitOnGroupMemberLeave(leftUser: User, leftGroup: Group) +```swift +// Emit group created event +CometChatGroupEvents.emitOnGroupCreate(group: group) -///emit this when group member's scope is changed by logged in user. -CometChatGroupEvents.emitOnGroupMemberChangeScope(updatedBy: User , updatedUser: User , scopeChangedTo: CometChat.MemberScope , scopeChangedFrom: CometChat.MemberScope, group: Group) +// Emit group deleted event +CometChatGroupEvents.emitOnGroupDelete(group: group) -///emit this when group member is banned from the group by logged in user. -CometChatGroupEvents.emitOnGroupMemberBan(bannedUser: User, bannedGroup: Group, bannedBy: User) +// Emit member joined event +CometChatGroupEvents.emitOnGroupMemberJoin(joinedUser: user, joinedGroup: group) -///emit this when group member is kicked from the group by logged in user. -CometChatGroupEvents.emitOnGroupMemberKick(kickedUser: User, kickedGroup: Group, kickedBy: User) +// Emit member left event +CometChatGroupEvents.emitOnGroupMemberLeave(leftUser: user, leftGroup: group) -///emit this when a banned group member is unbanned from group by logged in user. -CometChatGroupEvents.emitOnGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group, unbannedBy: User) +// Emit members added event +CometChatGroupEvents.emitOnGroupMemberAdd(group: group, members: members, addedBy: user) -///emit this when logged in user has joined a group successfully. -CometChatGroupEvents.emitOnGroupMemberJoin(joinedUser: User, joinedGroup: Group) +// Emit member banned event +CometChatGroupEvents.emitOnGroupMemberBan(bannedUser: user, bannedGroup: group, bannedBy: admin) -//emit this when members are added to a group by the logged in user. -CometChatGroupEvents.emitOnGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) +// Emit member unbanned event +CometChatGroupEvents.emitOnGroupMemberUnban(unbannedUserUser: user, unbannedUserGroup: group, unbannedBy: admin) -///emit this when ownership is changed by logged in user. -CometChatGroupEvents.emitOnGroupMemberChangeScope(updatedBy: User , updatedUser: User , scopeChangedTo: CometChat.MemberScope , scopeChangedFrom: CometChat.MemberScope, group: Group) +// Emit member kicked event +CometChatGroupEvents.emitOnGroupMemberKick(kickedUser: user, kickedGroup: group, kickedBy: admin) ``` -Removing `CometChatGroupsEvents` Listener's - - - -```swift -public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events -CometChatGroupEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") -} -``` +## Styling - +Customize the appearance using `GroupsStyle`. - +### Global Styling -## Customization +Apply styles to all `CometChatGroups` instances: -To fit your app's design requirements, you can customize the appearance of the groups component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +```swift +// Configure avatar style +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) -### Style +// Configure groups style +CometChatGroups.style.titleColor = UIColor(hex: "#F76808") +CometChatGroups.style.titleFont = UIFont.systemFont(ofSize: 34, weight: .bold) +CometChatGroups.avatarStyle = avatarStyle +``` -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +### Instance Styling -##### 1. Groups Style +Apply styles to a specific instance: -Enhance your Groups Component by setting the GroupsStyle to customize its appearance. +```swift +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) -**Group level styling** +let groupsStyle = GroupsStyle() +groupsStyle.titleColor = UIColor(hex: "#F76808") +groupsStyle.titleFont = UIFont.systemFont(ofSize: 34, weight: .bold) +groupsStyle.backgroundColor = .systemBackground +groupsStyle.listItemTitleTextColor = .label +groupsStyle.listItemSubTitleTextColor = .secondaryLabel - - -```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) - -CometChatGroups.style.titleColor = UIColor(hex: "#F76808") -CometChatGroups.style.titleFont = UIFont(name: "Times-New-Roman", size: 34) -CometChatGroups.avatarStyle = customAvatarStyle +let groups = CometChatGroups() +groups.style = groupsStyle +groups.avatarStyle = avatarStyle ``` - - - + + + -**Instance level styling** +### Style Properties + +| Property | Description | Code | +|----------|-------------|------| +| `listItemSelectedImage` | Check box image when a list item is selected | `listItemSelectedImage` | +| `listItemDeSelectedImage` | Check box image when a list item is deselected | `listItemDeSelectedImage` | +| `searchIconTintColor` | Tint color for the search icon | `searchIconTintColor` | +| `searchBarStyle` | Style of the search bar | `searchBarStyle` | +| `searchTintColor` | Tint color for the search bar | `searchTintColor` | +| `searchBarTintColor` | Background color of the search bar | `searchBarTintColor` | +| `searchBarPlaceholderTextColor` | Placeholder text color for the search bar | `searchBarPlaceholderTextColor` | +| `searchBarPlaceholderTextFont` | Font for the placeholder text in the search bar | `searchBarPlaceholderTextFont` | +| `searchBarTextColor` | Color of the text entered in the search bar | `searchBarTextColor` | +| `searchBarTextFont` | Font for the text in the search bar | `searchBarTextFont` | +| `searchBarBackgroundColor` | Background color of the search bar | `searchBarBackgroundColor` | +| `searchBarCancelIconTintColor` | Tint color for the cancel icon in the search bar | `searchBarCancelIconTintColor` | +| `searchBarCrossIconTintColor` | Tint color for the cross icon in the search bar | `searchBarCrossIconTintColor` | +| `backgroundColor` | Background color of the overall view | `backgroundColor` | +| `borderWidth` | Width of the border around the view | `borderWidth` | +| `borderColor` | Color of the border around the view | `borderColor` | +| `cornerRadius` | Corner radius settings for the view | `cornerRadius` | +| `titleColor` | Color for the title text | `titleColor` | +| `titleFont` | Font used for the title text | `titleFont` | +| `largeTitleColor` | Color for the large title text | `largeTitleColor` | +| `largeTitleFont` | Font used for the large title text | `largeTitleFont` | +| `navigationBarTintColor` | Background color of the navigation bar | `navigationBarTintColor` | +| `navigationBarItemsTintColor` | Tint color for items in the navigation bar | `navigationBarItemsTintColor` | +| `errorTitleTextFont` | Font used for the error title text | `errorTitleTextFont` | +| `errorTitleTextColor` | Color of the error title text | `errorTitleTextColor` | +| `errorSubTitleFont` | Font used for the error subtitle text | `errorSubTitleFont` | +| `errorSubTitleTextColor` | Color of the error subtitle text | `errorSubTitleTextColor` | +| `retryButtonTextColor` | Color for the retry button text | `retryButtonTextColor` | +| `retryButtonTextFont` | Font used for the retry button text | `retryButtonTextFont` | +| `retryButtonBackgroundColor` | Background color for the retry button | `retryButtonBackgroundColor` | +| `retryButtonBorderColor` | Border color for the retry button | `retryButtonBorderColor` | +| `retryButtonBorderWidth` | Width of the border around the retry button | `retryButtonBorderWidth` | +| `retryButtonCornerRadius` | Corner radius settings for the retry button | `retryButtonCornerRadius` | +| `emptyTitleTextFont` | Font used for the empty state title text | `emptyTitleTextFont` | +| `emptyTitleTextColor` | Color of the empty state title text | `emptyTitleTextColor` | +| `emptySubTitleFont` | Font used for the empty state subtitle text | `emptySubTitleFont` | +| `emptySubTitleTextColor` | Color of the empty state subtitle text | `emptySubTitleTextColor` | +| `tableViewSeparator` | Color of the table view separator | `tableViewSeparator` | +| `listItemTitleTextColor` | Color of the title text in list items | `listItemTitleTextColor` | +| `listItemTitleFont` | Font used for the title text in list items | `listItemTitleFont` | +| `listItemSubTitleTextColor` | Color of the subtitle text in list items | `listItemSubTitleTextColor` | +| `listItemSubTitleFont` | Font used for the subtitle text in list items | `listItemSubTitleFont` | +| `listItemBackground` | Background color for list items | `listItemBackground` | +| `listItemSelectedBackground` | Background color for list items if selected | `listItemSelectedBackground` | +| `listItemBorderWidth` | Width of the border around list items | `listItemBorderWidth` | +| `listItemBorderColor` | Color of the border around list items | `listItemBorderColor` | +| `listItemCornerRadius` | Corner radius settings for list items | `listItemCornerRadius` | +| `listItemSelectionImageTint` | Tint color for the selection image in list items | `listItemSelectionImageTint` | +| `listItemDeSelectedImageTint` | Tint color for the deselected image in list items | `listItemDeSelectedImageTint` | +| `passwordGroupImageTintColor` | Tint color for the password group image | `passwordGroupImageTintColor` | +| `passwordGroupImageBackgroundColor` | Background color for the password group image | `passwordGroupImageBackgroundColor` | +| `privateGroupImageTintColor` | Tint color for the private group image | `privateGroupImageTintColor` | +| `privateGroupImageBackgroundColor` | Background color for the private group image | `privateGroupImageBackgroundColor` | +| `privateGroupIcon` | Image for a private group icon | `privateGroupIcon` | +| `protectedGroupIcon` | Image for a protected group icon | `protectedGroupIcon` | + +## Functionality + +Configure component behavior with these properties and methods: + +| Method | Description | Code | +|--------|-------------|------| +| `set(groupsRequestBuilder:)` | Sets the request builder for fetching groups | `set(groupsRequestBuilder: requestBuilder)` | +| `set(searchRequestBuilder:)` | Sets the request builder for searching groups | `set(searchRequestBuilder: searchRequestBuilder)` | +| `set(searchKeyword:)` | Sets the search keyword to filter groups | `set(searchKeyword: "group_name")` | +| `hideErrorView` | Hides the error state view | `hideErrorView = true` | +| `hideNavigationBar` | Hides or shows the navigation bar | `hideNavigationBar = true` | +| `hideSearch` | Hides the search bar | `hideSearch = true` | +| `hideBackButton` | Hides the back button | `hideBackButton = true` | +| `hideLoadingState` | Hides the loading state indicator | `hideLoadingState = true` | +| `hideReceipts` | Hides message read/delivery receipts | `hideReceipts = true` | +| `hideDeleteConversationOption` | Hides the option to delete a conversation | `hideDeleteConversationOption = true` | +| `hideUserStatus` | Hides the online/offline status of users | `hideUserStatus = true` | +| `hideGroupType` | Hides the group type (private/public) | `hideGroupType = true` | - - ```swift -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) - -let groupStyle = GroupsStyle() -groupStyle.titleColor = UIColor(hex: "#F76808") -groupStyle.titleFont = UIFont(name: "Times-New-Roman", size: 34) - -let customGroup = CometChatGroups() -customGroup.style = groupStyle -customGroup.avatarStyle = customAvatarStyle +let groups = CometChatGroups() +groups.hideSearch = true +groups.hideGroupType = false +groups.hideBackButton = true +groups.hideErrorView = false +groups.hideLoadingState = false ``` - +## Custom Views - +### SetOptions - - - +You can define custom options for each group using `.set(options:)`. This method allows you to return an array of `CometChatGroupOption` based on the group object. -| **Property** | **Description** | **Code** | -| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ----------------------------------- | -| **List Item Selected Image** | Check box image when a list item is selected. | `listItemSelectedImage` | -| **List Item Deselected Image** | Check box image when a list item is deselected. | `listItemDeSelectedImage` | -| **Search Icon Tint Color** | Tint color for the search icon, defaults to the secondary icon color from CometChatTheme. | `searchIconTintColor` | -| **Search Bar Style** | Style of the search bar, defaulting to the standard style. | `searchBarStyle` | -| **Search Tint Color** | Tint color for the search bar, defaults to the primary color from CometChatTheme. | `searchTintColor` | -| **Search Bar Tint Color** | Background color of the search bar, defaulting to clear. | `searchBarTintColor` | -| **Search Bar Placeholder Text Color** | Placeholder text color for the search bar, defaults to the tertiary text color from CometChatTheme. | `searchBarPlaceholderTextColor` | -| **Search Bar Placeholder Text Font** | Font used for the placeholder text in the search bar, defaults to regular body font. | `searchBarPlaceholderTextFont` | -| **Search Bar Text Color** | Color of the text entered in the search bar, defaults to the primary text color from CometChatTheme. | `searchBarTextColor` | -| **Search Bar Text Font** | Font used for the text in the search bar, defaults to regular body font. | `searchBarTextFont` | -| **Search Bar Background Color** | Background color of the search bar, defaults to a specific background color from CometChatTheme. | `searchBarBackgroundColor` | -| **Search Bar Cancel Icon Tint Color** | Tint color for the cancel icon in the search bar, defaults to the primary color from CometChatTheme. | `searchBarCancelIconTintColor` | -| **Search Bar Cross Icon Tint Color** | Tint color for the cross icon in the search bar, defaults to the secondary icon color from CometChatTheme. | `searchBarCrossIconTintColor` | -| **Background Color** | Background color of the overall view, defaults to a specific background color from CometChatTheme. | `backgroundColor` | -| **Border Width** | Width of the border around the view, defaults to 0 (no border). | `borderWidth` | -| **Border Color** | Color of the border around the view, defaults to clear. | `borderColor` | -| **Corner Radius** | Corner radius settings for the view, defaults to no corner radius. | `cornerRadius` | -| **Title Color** | Color for the title text, defaults to the primary text color from CometChatTheme. | `titleColor` | -| **Title Font** | Font used for the title text, defaults to nil (not set). | `titleFont` | -| **Large Title Color** | Color for the large title text, defaults to the primary text color from CometChatTheme. | `largeTitleColor` | -| **Large Title Font** | Font used for the large title text, defaults to nil (not set). | `largeTitleFont` | -| **Navigation Bar Tint Color** | Background color of the navigation bar, defaults to a specific background color from CometChatTheme. | `navigationBarTintColor` | -| **Navigation Bar Items Tint Color** | Tint color for items in the navigation bar, defaults to the highlight color from CometChatTheme. | `navigationBarItemsTintColor` | -| **Error Title Text Font** | Font used for the error title text, defaults to a bold heading 3 font from CometChatTypography. | `errorTitleTextFont` | -| **Error Title Text Color** | Color of the error title text, defaults to the primary text color from CometChatTheme. | `errorTitleTextColor` | -| **Error Subtitle Font** | Font used for the error subtitle text, defaults to regular body font. | `errorSubTitleFont` | -| **Error Subtitle Text Color** | Color of the error subtitle text, defaults to the secondary text color from CometChatTheme. | `errorSubTitleTextColor` | -| **Retry Button Text Color** | Color for the retry button text, defaults to button text color from CometChatTheme. | `retryButtonTextColor` | -| **Retry Button Text Font** | Font used for the retry button text, defaults to medium button font from CometChatTypography. | `retryButtonTextFont` | -| **Retry Button Background Color** | Background color for the retry button, defaults to the primary color from CometChatTheme. | `retryButtonBackgroundColor` | -| **Retry Button Border Color** | Border color for the retry button, defaults to clear. | `retryButtonBorderColor` | -| **Retry Button Border Width** | Width of the border around the retry button, defaults to 0 (no border). | `retryButtonBorderWidth` | -| **Retry Button Corner Radius** | Corner radius settings for the retry button, defaults to a specific corner radius from CometChatSpacing. | `retryButtonCornerRadius` | -| **Empty State Title Font** | Font used for the empty state title text, defaults to a bold heading 3 font from CometChatTypography. | `emptyTitleTextFont` | -| **Empty State Title Color** | Color of the empty state title text, defaults to the primary text color from CometChatTheme. | `emptyTitleTextColor` | -| **Empty State Subtitle Font** | Font used for the empty state subtitle text, defaults to regular body font. | `emptySubTitleFont` | -| **Empty State Subtitle Color** | Color of the empty state subtitle text, defaults to the secondary text color from CometChatTheme. | `emptySubTitleTextColor` | -| **Table View Separator** | Color of the table view separator, defaults to clear. | `tableViewSeparator` | -| **List Item Title Text Color** | Color of the title text in list items, defaults to the primary text color from CometChatTheme. | `listItemTitleTextColor` | -| **List Item Title Font** | Font used for the title text in list items, defaults to medium heading 4 font from CometChatTypography. | `listItemTitleFont` | -| **List Item Subtitle Text Color** | Color of the subtitle text in list items, defaults to the secondary text color from CometChatTheme. | `listItemSubTitleTextColor` | -| **List Item Subtitle Font** | Font used for the subtitle text in list items, defaults to regular body font. | `listItemSubTitleFont` | -| **List Item Background** | Background color for list items, defaults to clear. | `listItemBackground` | -| **List Item Selected Background** | Background color for list items if selected, defaults to clear. | `listItemSelectedBackground` | -| **List Item Border Width** | Width of the border around list items, defaults to 0 (no border). | `listItemBorderWidth` | -| **List Item Border Color** | Color of the border around list items, defaults to the light border color from CometChatTheme. | `listItemBorderColor` | -| **List Item Corner Radius** | Corner radius settings for list items, defaults to no corner radius. | `listItemCornerRadius` | -| **List Item Selection Image Tint** | Tint color for the selection image in list items, defaults to the highlight color from CometChatTheme. | `listItemSelectionImageTint` | -| **List Item Deselection Image Tint** | Tint color for the deselected image in list items. | `listItemDeSelectedImageTint` | -| **Password Group Image Tint Color** | Tint color for the password group image, defaults to the background color from CometChatTheme. | `passwordGroupImageTintColor` | -| **Password Group Image Background Color** | Background color for the password group image, defaults to the warning color from CometChatTheme. | `passwordGroupImageBackgroundColor` | -| **Private Group Image Tint Color** | Tint color for the private group image, defaults to the background color from CometChatTheme. | `privateGroupImageTintColor` | -| **Private Group Image Background Color** | Background color for the private group image, defaults to the success color from CometChatTheme. | `privateGroupImageBackgroundColor` | -| **Private Group Icon** | Image for a private group icon. | `privateGroupIcon` | -| **Protected Group Icon** | Image for a protected group icon. | `protectedGroupIcon` | - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets - -| Method | Description | Code | -| ---------------------------- | ---------------------------------------------- | ------------------------------------------------- | -| set(groupsRequestBuilder:) | Sets the request builder for fetching groups. | `set(groupsRequestBuilder: requestBuilder)` | -| set(searchRequestBuilder:) | Sets the request builder for searching groups. | `set(searchRequestBuilder: searchRequestBuilder)` | -| set(searchKeyword:) | Sets the search keyword to filter groups. | `set(searchKeyword: "group_name")` | -| hideErrorView | Hides the error state view. | `hideErrorView = true` | -| hideNavigationBar | Hides or shows the navigation bar. | `hideNavigationBar = true` | -| hideSearch | Hides the search bar. | `hideSearch = true` | -| hideBackButton | Hides the back button. | `hideBackButton = true` | -| hideLoadingState | Hides the loading state indicator. | `hideLoadingState = true` | -| hideReceipts | Hides message read/delivery receipts. | `hideReceipts = true` | -| hideDeleteConversationOption | Hides the option to delete a conversation. | `hideDeleteConversationOption = true` | -| hideUserStatus | Hides the online/offline status of users. | `hideUserStatus = true` | -| hideGroupType | Hides the group type (private/public). | `hideGroupType = true` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** - -#### SetOptions - -You can define custom options for each group using .set(options:). This method allows you to return an array of CometChatGroupOption based on the group object. - - - ```swift cometChatGroups.set(options: { group in return [CometChatGroupOptions] }) ``` - - - - -*** +### AddOptions -#### AddOptions +You can dynamically add options to groups using `.add(options:)`. This method lets you return additional `CometChatGroupOption` elements. -You can dynamically add options to groups using .add(options:). This method lets you return additional CometChatGroupOption elements. - - - ```swift cometChatGroups.add(options: { group in return [ArchiveOption()] }) ``` - - - - -*** - -#### SetListItemView +### SetListItemView With this function, you can assign a custom ListItem to the groups Component. - - ```swift let cometChatGroups = CometChatGroups() cometChatGroups.set(listItemView: { group in @@ -563,51 +586,52 @@ cometChatGroups.set(listItemView: { group in }) ``` - +### Custom List Item - +Replace the default group cell with a custom view: -Demonstration +```swift +let groups = CometChatGroups() +groups.set(listItemView: { group in + let customView = CustomGroupCell() + customView.configure(with: group) + return customView +}) +``` -You can create a `CustomListItemView` as a custom `UIView`. Which we will inflate in `setListItemView()` - -```swift swift +```swift import UIKit import CometChatSDK -import CometChatUIKitSwift -class GroupCellView: UIView { - - // MARK: - Properties +class CustomGroupCell: UIView { private let avatarImageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false - imageView.contentMode = .scaleAspectFit - imageView.layer.cornerRadius = 20 // Circular avatar + imageView.contentMode = .scaleAspectFill + imageView.layer.cornerRadius = 20 imageView.clipsToBounds = true + imageView.backgroundColor = .systemGray5 return imageView }() private let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false - label.font = UIFont.systemFont(ofSize: 16, weight: .bold) - label.textColor = .black - label.numberOfLines = 1 + label.font = .systemFont(ofSize: 16, weight: .semibold) + label.textColor = .label return label }() - private let subtitleLabel: UILabel = { + private let membersLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false - label.font = UIFont.systemFont(ofSize: 14, weight: .regular) - label.textColor = .darkGray - label.numberOfLines = 1 + label.font = .systemFont(ofSize: 14) + label.textColor = .secondaryLabel return label }() @@ -615,17 +639,13 @@ class GroupCellView: UIView { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("JOIN", for: .normal) - button.setTitleColor(.systemBlue, for: .normal) - button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .bold) + button.titleLabel?.font = .systemFont(ofSize: 12, weight: .bold) button.layer.cornerRadius = 12 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.systemBlue.cgColor - button.clipsToBounds = true return button }() - // MARK: - Initializers - override init(frame: CGRect) { super.init(frame: frame) setupView() @@ -636,40 +656,26 @@ class GroupCellView: UIView { setupView() } - // MARK: - Setup - private func setupView() { - // Add subviews addSubview(avatarImageView) addSubview(titleLabel) - addSubview(subtitleLabel) + addSubview(membersLabel) addSubview(joinButton) - // Constraints for avatarImageView NSLayoutConstraint.activate([ avatarImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), avatarImageView.centerYAnchor.constraint(equalTo: centerYAnchor), avatarImageView.widthAnchor.constraint(equalToConstant: 40), - avatarImageView.heightAnchor.constraint(equalToConstant: 40) - ]) - - // Constraints for titleLabel - NSLayoutConstraint.activate([ + avatarImageView.heightAnchor.constraint(equalToConstant: 40), + titleLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 12), - titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8), - titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: joinButton.leadingAnchor, constant: -8) - ]) - - // Constraints for subtitleLabel - NSLayoutConstraint.activate([ - subtitleLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 12), - subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4), - subtitleLabel.trailingAnchor.constraint(lessThanOrEqualTo: joinButton.leadingAnchor, constant: -8), - subtitleLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8) - ]) - - // Constraints for joinButton - NSLayoutConstraint.activate([ + titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 12), + titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: joinButton.leadingAnchor, constant: -8), + + membersLabel.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: 12), + membersLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4), + membersLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -12), + joinButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), joinButton.centerYAnchor.constraint(equalTo: centerYAnchor), joinButton.widthAnchor.constraint(equalToConstant: 60), @@ -677,27 +683,32 @@ class GroupCellView: UIView { ]) } - // MARK: - Configuration - - func configure(avatar: UIImage?, title: String, subtitle: String, isJoined: Bool) { - avatarImageView.image = avatar - titleLabel.text = title - subtitleLabel.text = subtitle + func configure(with group: Group) { + titleLabel.text = group.name + membersLabel.text = "\(group.membersCount) members" + + if let iconURL = group.icon, let url = URL(string: iconURL) { + URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in + if let data = data, let image = UIImage(data: data) { + DispatchQueue.main.async { + self?.avatarImageView.image = image + } + } + }.resume() + } + + let isJoined = group.hasJoined joinButton.setTitle(isJoined ? "JOINED" : "JOIN", for: .normal) - joinButton.setTitleColor(isJoined ? .gray : .systemBlue, for: .normal) - joinButton.layer.borderColor = isJoined ? UIColor.gray.cgColor : UIColor.systemBlue.cgColor + joinButton.setTitleColor(isJoined ? .systemGray : .systemBlue, for: .normal) + joinButton.layer.borderColor = isJoined ? UIColor.systemGray.cgColor : UIColor.systemBlue.cgColor } } ``` -*** +### SetLeadingView -#### SetLeadingView +You can modify the leading view of a group cell using `.set(leadingView:)`. -You can modify the leading view of a group cell using .set(leadingView:). - - - ```swift cometChatGroups.set(leadingView: { group in let view = CustomLeadingView() @@ -705,20 +716,12 @@ cometChatGroups.set(leadingView: { group in }) ``` - - - - -Demonstration - -You can create a `CustomLeadingView` as a custom `UIView`. Which we will inflate in `setLeadingView()` +You can create a `CustomLeadingView` as a custom `UIView`. Which we will inflate in `setLeadingView()`: - - ```swift import UIKit @@ -758,23 +761,15 @@ class CustomLeadingView: UIView { addSubview(joinButton) iconImageView.translatesAutoresizingMaskIntoConstraints = false - joinButton.translatesAutoresizingMask + joinButton.translatesAutoresizingMaskIntoConstraints = false } } ``` - - - - -*** - -#### SetTitleView +### SetTitleView -You can customize the title view of a group cell using .set(titleView:). +You can customize the title view of a group cell using `.set(titleView:)`. - - ```swift cometChatGroups.set(titleView: { group in let view = CustomTitleView() @@ -782,22 +777,14 @@ cometChatGroups.set(titleView: { group in }) ``` - - - - -Demonstration - -You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()` +You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()`: - - ```swift - class CustomTitleView: UIView { +class CustomTitleView: UIView { private let titleLabel: UILabel = { let label = UILabel() @@ -865,18 +852,10 @@ You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate i } ``` - - - +### SetTrailView -*** +You can modify the trailing view of a group cell using `.set(trailView:)`. -#### SetTrailView - -You can modify the trailing view of a group cell using .set(trailView:). - - - ```swift cometChatGroups.set(trailView: { group in let view = CustomTrailView() @@ -884,22 +863,14 @@ cometChatGroups.set(trailView: { group in }) ``` - - - - -Demonstration - -You can create a `CustomTrailView` as a custom `UIView`. Which we will inflate in `setTrailView()` +You can create a `CustomTrailView` as a custom `UIView`. Which we will inflate in `setTrailView()`: - - ```swift - import UIKit +import UIKit class CustomTrailView: UIView { @@ -935,22 +906,12 @@ class CustomTrailView: UIView { ]) } } - - ``` - - - +### SetSubTitleView -*** +You can customize the subtitle view for each group item to meet your requirements: -#### SetSubTitleView - -You can customize the subtitle view for each group item to meet your requirements - - - ```swift cometChatGroup.set(subtitleView: { group in let view = CustomSubtitleView() @@ -958,22 +919,12 @@ cometChatGroup.set(subtitleView: { group in }) ``` - - - - -**Example** - -Demonstration - -You can seamlessly integrate this `CustomSubtitleView` UIView file into the `.set(subtitleView:)` method within CometChatGroups. +You can seamlessly integrate this `CustomSubtitleView` UIView file into the `.set(subtitleView:)` method within CometChatGroups: - - ```swift import UIKit @@ -993,36 +944,20 @@ class CustomSubtitleView: UILabel { } ``` - - - - -*** - -#### SetLoadingView +### SetLoadingView -You can set a custom loading view using .set(loadingView:). This method accepts a UIView to display while data is being fetched. +You can set a custom loading view using `.set(loadingView:)`. This method accepts a UIView to display while data is being fetched. - - ```swift let loadingIndicator = UIActivityIndicatorView(style: .medium) loadingIndicator.startAnimating() cometChatGroups.set(loadingView: loadingIndicator) ``` - +### SetErrorView - +You can customize the error view using `.set(errorView:)`. This method accepts a UIView that appears when an error occurs. -*** - -#### SetErrorView - -You can customize the error view using .set(errorView:). This method accepts a UIView that appears when an error occurs. - - - ```swift let errorLabel = UILabel() errorLabel.text = "Something went wrong!" @@ -1030,18 +965,10 @@ errorLabel.textColor = .red cometChatGroups.set(errorView: errorLabel) ``` - - - +### SetEmptyView -*** +You can customize the empty state view using `.set(emptyView:)`. This method accepts a UIView that appears when no groups are available. -#### SetEmptyView - -You can customize the empty state view using .set(emptyView:). This method accepts a UIView that appears when no groups are available. - - - ```swift let emptyLabel = UILabel() emptyLabel.text = "No groups found" @@ -1050,8 +977,65 @@ emptyLabel.textAlignment = .center cometChatGroups.set(emptyView: emptyLabel) ``` - +## Group Options + +Add custom swipe actions to group cells. + +### Set Options + +Replace default options: + +```swift +groups.set(options: { group in + let leaveOption = CometChatGroupOption( + id: "leave", + title: "Leave", + icon: UIImage(systemName: "arrow.right.square"), + backgroundColor: .systemRed + ) { group in + // Handle leave action + } + return [leaveOption] +}) +``` + +### Add Options + +Add options to existing ones: + +```swift +groups.add(options: { group in + let archiveOption = CometChatGroupOption( + id: "archive", + title: "Archive", + icon: UIImage(systemName: "archivebox"), + backgroundColor: .systemOrange + ) { group in + // Handle archive action + } + return [archiveOption] +}) +``` + +## Component Structure + +| Component | Description | +|-----------|-------------| +| [CometChatListBase](/ui-kit/ios/list-base) | Container with navigation bar and search | +| [CometChatListItem](/ui-kit/ios/list-item) | Individual group cell | + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| Groups not loading | Verify user is logged in and has proper permissions | +| Search not working | Check `searchRequestBuilder` configuration | +| Events not firing | Ensure listener is added before actions occur | +| Styling not applied | Apply styles before presenting the component | +| Custom views not showing | Return non-nil UIView from closure | - +## Related Components -*** +- [Group Members](/ui-kit/ios/group-members) - Display group member list +- [Conversations](/ui-kit/ios/conversations) - Display conversation list +- [Users](/ui-kit/ios/users) - Display user list diff --git a/ui-kit/ios/guide-ai-agent.mdx b/ui-kit/ios/guide-ai-agent.mdx index 01fc4ad08..1cd558bcc 100644 --- a/ui-kit/ios/guide-ai-agent.mdx +++ b/ui-kit/ios/guide-ai-agent.mdx @@ -1,27 +1,10 @@ --- title: "AI Agent Integration" sidebarTitle: "AI Agent Integration" +description: "Add AI-powered chat assistants to your iOS app" --- -Enable intelligent conversational AI capabilities in your iOS app using CometChat UIKit v5 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 offers 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. +Integrate AI agents into your iOS app to provide intelligent conversational experiences with chat history, contextual responses, and seamless handoffs. @@ -29,166 +12,524 @@ The AI Agent chat interface provides a familiar messaging experience enhanced wi ## Prerequisites -- **CometChat UIKit for iOS** installed via CocoaPods or Swift Package Manager -- CometChat initialized with `App ID`, `Region`, and `Auth Key` -- Message chat enabled in your CometChat app -- Navigation set up between message and user/group screens -- Internet permissions +Before implementing AI agents, ensure you have: -## Components +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- CometChat UIKit v5+ installed +- AI features enabled in your [CometChat Dashboard](https://app.cometchat.com) +- User logged in with `CometChatUIKit.login()` -| Component/Class | Role | -|------------------------------ |------------------------------------------------------| -| `CometChatMessageHeader` | Manages message interactions and state | -| `CometChatMessageList` | Displays a list of messages | -| `CometChatMessageComposer` | Composes and sends new messages | -| `CometChatAIAssistantChatHistory` | Displays previous AI conversation history | +## Overview ---- +The AI Agent integration provides: -## Integration Steps +- **Intelligent Responses** - Context-aware AI conversations +- **Chat History** - Browse and resume previous AI sessions +- **Streaming Responses** - Real-time message streaming +- **Custom Styling** - Match your app's design +- **Suggested Messages** - Quick-start prompts for users -### Step 1 - Screen Setup +## Basic Implementation -Create a screen for AI Assistant chat using `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer`. +Create a simple AI chat screen: - - ```swift import UIKit -import CometChatUIKit +import CometChatUIKitSwift +import CometChatSDK + +class AIAgentChatViewController: UIViewController { + + private var user: User? + private var messageHeader: CometChatMessageHeader! + private var messageList: CometChatMessageList! + private var messageComposer: CometChatMessageComposer! + + convenience init(user: User) { + self.init() + self.user = user + } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemBackground + setupUI() + } + + private func setupUI() { + guard let user = user else { return } + + // Message Header + messageHeader = CometChatMessageHeader() + messageHeader.set(user: user) + messageHeader.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(messageHeader) + + // Message List + messageList = CometChatMessageList() + messageList.set(user: user) + messageList.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(messageList) + + // Message Composer + messageComposer = CometChatMessageComposer() + messageComposer.set(user: user) + messageComposer.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(messageComposer) + + setupConstraints() + } + + private func setupConstraints() { + NSLayoutConstraint.activate([ + messageHeader.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + messageHeader.leadingAnchor.constraint(equalTo: view.leadingAnchor), + messageHeader.trailingAnchor.constraint(equalTo: view.trailingAnchor), + messageHeader.heightAnchor.constraint(equalToConstant: 60), + + messageList.topAnchor.constraint(equalTo: messageHeader.bottomAnchor), + messageList.leadingAnchor.constraint(equalTo: view.leadingAnchor), + messageList.trailingAnchor.constraint(equalTo: view.trailingAnchor), + messageList.bottomAnchor.constraint(equalTo: messageComposer.topAnchor), + + messageComposer.leadingAnchor.constraint(equalTo: view.leadingAnchor), + messageComposer.trailingAnchor.constraint(equalTo: view.trailingAnchor), + messageComposer.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) + ]) + } +} +``` -class AIAssistantChatViewController: UIViewController { +## Production Implementation - var user: User? - var group: Group? - var parentMessage: BaseMessage? - var isHistory: Bool = false +Complete AI agent chat with history, navigation, and error handling: +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ProductionAIAgentViewController: UIViewController { + + // MARK: - Properties + private var user: User? + private var group: Group? + private var parentMessage: BaseMessage? + private var isHistoryMode: Bool = false + + private var messageHeader: CometChatMessageHeader! + private var messageList: CometChatMessageList! + private var messageComposer: CometChatMessageComposer! + + // MARK: - Initialization + convenience init(user: User, parentMessage: BaseMessage? = nil, isHistory: Bool = false) { + self.init() + self.user = user + self.parentMessage = parentMessage + self.isHistoryMode = isHistory + } + + convenience init(group: Group, parentMessage: BaseMessage? = nil, isHistory: Bool = false) { + self.init() + self.group = group + self.parentMessage = parentMessage + self.isHistoryMode = isHistory + } + + // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() - setupUI() + view.backgroundColor = .systemBackground + setupMessageHeader() + setupMessageList() + setupMessageComposer() + setupConstraints() } - - func setupUI() { - let messageHeader = CometChatMessageHeader() - messageHeader.user = user - messageHeader.group = group - messageHeader.onBack = { [weak self] in - self?.navigationController?.popViewController(animated: true) + + // MARK: - Setup + private func setupMessageHeader() { + messageHeader = CometChatMessageHeader() + messageHeader.translatesAutoresizingMaskIntoConstraints = false + + if let user = user { + messageHeader.set(user: user) + } else if let group = group { + messageHeader.set(group: group) } - messageHeader.chatHistoryButtonClick = { [weak self] in + + // Back button handler + messageHeader.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) + }) + + // Chat history button handler + messageHeader.set(chatHistoryButtonClick: { [weak self] in self?.openChatHistory() - } + }) + view.addSubview(messageHeader) - - let messageList = CometChatMessageList() - messageList.user = user - messageList.group = group + } + + private func setupMessageList() { + messageList = CometChatMessageList() + messageList.translatesAutoresizingMaskIntoConstraints = false messageList.hideThreadView = true + + if let user = user { + messageList.set(user: user) + } else if let group = group { + messageList.set(group: group) + } + + // If resuming from history, set parent message + if let parentMessage = parentMessage { + messageList.set(parentMessage: parentMessage) + } + view.addSubview(messageList) - - let composer = CometChatMessageComposer() - composer.user = user - composer.group = group - view.addSubview(composer) } - - func openChatHistory() { - let chatHistoryVC = CometChatAIAssistantChatHistory() - chatHistoryVC.user = user - chatHistoryVC.group = group - chatHistoryVC.onNewChatButtonClicked = { - self.startNewChat() + + private func setupMessageComposer() { + messageComposer = CometChatMessageComposer() + messageComposer.translatesAutoresizingMaskIntoConstraints = false + + if let user = user { + messageComposer.set(user: user) + } else if let group = group { + messageComposer.set(group: group) } - chatHistoryVC.onMessageClicked = { [weak self] message in - guard let self = self else { return } - self.parentMessage = message - self.isHistory = true - self.navigationController?.pushViewController( - AIAssistantChatViewController(), - animated: true - ) + + // If resuming from history, set parent message + if let parentMessage = parentMessage { + messageComposer.set(parentMessage: parentMessage) } - chatHistoryVC.onClose = { - self.navigationController?.popViewController(animated: true) + + view.addSubview(messageComposer) + } + + private func setupConstraints() { + NSLayoutConstraint.activate([ + messageHeader.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + messageHeader.leadingAnchor.constraint(equalTo: view.leadingAnchor), + messageHeader.trailingAnchor.constraint(equalTo: view.trailingAnchor), + messageHeader.heightAnchor.constraint(equalToConstant: 60), + + messageList.topAnchor.constraint(equalTo: messageHeader.bottomAnchor), + messageList.leadingAnchor.constraint(equalTo: view.leadingAnchor), + messageList.trailingAnchor.constraint(equalTo: view.trailingAnchor), + messageList.bottomAnchor.constraint(equalTo: messageComposer.topAnchor), + + messageComposer.leadingAnchor.constraint(equalTo: view.leadingAnchor), + messageComposer.trailingAnchor.constraint(equalTo: view.trailingAnchor), + messageComposer.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) + ]) + } + + // MARK: - Chat History + private func openChatHistory() { + let chatHistoryVC = CometChatAIAssistantChatHistory() + + if let user = user { + chatHistoryVC.set(user: user) + } else if let group = group { + chatHistoryVC.set(group: group) } + + // Handle new chat button + chatHistoryVC.set(onNewChatButtonClicked: { [weak self] in + self?.startNewChat() + }) + + // Handle message selection to resume conversation + chatHistoryVC.set(onMessageClicked: { [weak self] message in + self?.resumeConversation(from: message) + }) + + // Handle close + chatHistoryVC.set(onClose: { [weak self] in + self?.navigationController?.popViewController(animated: true) + }) + navigationController?.pushViewController(chatHistoryVC, animated: true) } + + private func startNewChat() { + let newChatVC: ProductionAIAgentViewController + + if let user = user { + newChatVC = ProductionAIAgentViewController(user: user) + } else if let group = group { + newChatVC = ProductionAIAgentViewController(group: group) + } else { + return + } + + navigationController?.pushViewController(newChatVC, animated: true) + } + + private func resumeConversation(from message: BaseMessage) { + let resumeVC: ProductionAIAgentViewController + + if let user = user { + resumeVC = ProductionAIAgentViewController(user: user, parentMessage: message, isHistory: true) + } else if let group = group { + resumeVC = ProductionAIAgentViewController(group: group, parentMessage: message, isHistory: true) + } else { + return + } + + navigationController?.pushViewController(resumeVC, animated: true) + } +} +``` + +## Launching AI Agent Chat - func startNewChat() { - navigationController?.pushViewController( - AIAssistantChatViewController(), - animated: true - ) +Start an AI agent conversation from your app: + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ChatListViewController: UIViewController { + + func openAIAgentChat(agentUID: String) { + // Fetch the AI agent user + CometChat.getUser(UID: agentUID) { [weak self] user in + DispatchQueue.main.async { + // Check if user is an AI agent (role contains "agentic") + if user.role?.lowercased().contains("agentic") == true { + let aiChatVC = ProductionAIAgentViewController(user: user) + self?.navigationController?.pushViewController(aiChatVC, animated: true) + } else { + // Regular user chat + let messages = CometChatMessages() + messages.set(user: user) + self?.navigationController?.pushViewController(messages, animated: true) + } + } + } onError: { error in + print("Error fetching user: \(error?.errorDescription ?? "")") + } + } + + func detectAndOpenChat(for user: User) { + // Detect if user is an AI agent + let isAIAgent = user.role?.lowercased().contains("agentic") == true + + if isAIAgent { + let aiChatVC = ProductionAIAgentViewController(user: user) + navigationController?.pushViewController(aiChatVC, animated: true) + } else { + let messages = CometChatMessages() + messages.set(user: user) + navigationController?.pushViewController(messages, animated: true) + } } } ``` - +## Styling + +Customize the AI chat bubble appearance: + +```swift +import UIKit +import CometChatUIKitSwift + +class AIAgentStylingExample { + + func applyGlobalStyles() { + // Configure AI bubble style + let aiBubbleStyle = AiAssistantBubbleStyle() + aiBubbleStyle.backgroundColor = .clear + aiBubbleStyle.borderWidth = 1 + aiBubbleStyle.borderColor = .systemBlue + aiBubbleStyle.textColor = .label + aiBubbleStyle.textFont = UIFont.systemFont(ofSize: 14) + aiBubbleStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 12) + + // Apply globally + CometChatAiAssistantBubble.style = aiBubbleStyle + } + + func applyInstanceStyles() -> ProductionAIAgentViewController { + let aiChatVC = ProductionAIAgentViewController(user: User()) + + // Custom message list style + let messageListStyle = MessageListStyle() + messageListStyle.backgroundColor = UIColor.systemBackground + + // Custom composer style + let composerStyle = MessageComposerStyle() + composerStyle.backgroundColor = UIColor.secondarySystemBackground + composerStyle.borderColor = UIColor.separator + composerStyle.borderWidth = 1 + + return aiChatVC + } +} +``` - +### Style Properties +| Property | Description | +|----------|-------------| +| `backgroundColor` | Bubble background color | +| `borderWidth` | Bubble border width | +| `borderColor` | Bubble border color | +| `textColor` | Message text color | +| `textFont` | Message text font | +| `cornerRadius` | Bubble corner radius | -### Step 2 - Chat History Screen +## Customization Options -Create a screen for AI Assistant chat history using `CometChatAIAssistantChatHistory`. +### Empty State View -Features Implemented:: -- Browse their previous AI chat sessions. -- Resume a previous conversation (onMessageClicked). -- Start a new chat session (onNewChatButtonClicked). -- Close the chat history view (onClose). +Customize the view shown when there are no messages: -### Step 3 - Custom Styles +```swift +let emptyView = UIView() +let label = UILabel() +label.text = "Start a conversation with AI" +label.textAlignment = .center +label.textColor = .secondaryLabel +emptyView.addSubview(label) + +messageList.set(emptyStateView: emptyView) +``` -Define custom styles for AI chat bubbles and the composer using `CometChatAiAssistantBubbleStyle`. +### Streaming Speed +Adjust how fast AI responses stream: - - ```swift -import UIKit -import CometChatUIKit - -let aiBubbleStyle = AiAssistantBubbleStyle() -aiBubbleStyle.backgroundColor = .clear -aiBubbleStyle.border = Border(width: 1, color: .systemBlue) -aiBubbleStyle.textColor = UIColor(named: "TextPrimary") -aiBubbleStyle.textStyle = UIFont(name: "TimesNewRoman", size: 14) -CometChatAiAssistantBubble.style = aiBubbleStyle +// Configure streaming speed (characters per second) +messageList.set(streamingSpeed: 50) ``` - - +### Suggested Messages ---- +Provide quick-start prompts for users: -## Implementation Flow Summary +```swift +let suggestions = [ + "What can you help me with?", + "Tell me about your capabilities", + "How do I get started?" +] -| Step | Action | -|:-----|:-------------------------------------------------------------------------------| -| 1 | User selects AI agent from chat list | -| 2 | `AIAssistantChatViewController` launches | -| 3 | Parse User data and detect agent chat (Role must be `@agentic`) | -| 4 | Initialize UI with AI-specific styling | -| 5 | Configure chat history and navigation | -| 6 | Launch chat with AI agent | +messageComposer.set(suggestedMessages: suggestions) +``` ---- +### AI Assistant Tools -## Customization Options +Configure custom tools for the AI agent: -- **Custom AI Assistant Empty Chat View:** Customize using `emptyStateView`. -- **Streaming Speed:** Adjust AI response streaming speed with `streamingSpeed`. -- **AI Assistant Suggested Messages:** Set quick prompts using `suggestedMessages`. -- **AI Assistant Tools:** Set AI agent tools using `setAiAssistantTools` callback. +```swift +messageComposer.set(aiAssistantTools: { message in + // Return custom tools based on context + return [ + AITool(name: "search", description: "Search knowledge base"), + AITool(name: "calculate", description: "Perform calculations") + ] +}) +``` ---- +## Chat History Component + +The `CometChatAIAssistantChatHistory` component displays previous AI conversations: -## Feature Matrix +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ChatHistoryViewController: UIViewController { + + private var user: User? + + convenience init(user: User) { + self.init() + self.user = user + } + + override func viewDidLoad() { + super.viewDidLoad() + setupChatHistory() + } + + private func setupChatHistory() { + guard let user = user else { return } + + let chatHistory = CometChatAIAssistantChatHistory() + chatHistory.set(user: user) + + // New chat button + chatHistory.set(onNewChatButtonClicked: { [weak self] in + let newChat = ProductionAIAgentViewController(user: user) + self?.navigationController?.pushViewController(newChat, animated: true) + }) + + // Resume conversation + chatHistory.set(onMessageClicked: { [weak self] message in + let resumeChat = ProductionAIAgentViewController( + user: user, + parentMessage: message, + isHistory: true + ) + self?.navigationController?.pushViewController(resumeChat, animated: true) + }) + + // Close handler + chatHistory.set(onClose: { [weak self] in + self?.dismiss(animated: true) + }) + + addChild(chatHistory) + view.addSubview(chatHistory.view) + chatHistory.view.frame = view.bounds + chatHistory.didMove(toParent: self) + } +} +``` -| Feature | Implementation | UI Component | -|:-----------------------|:-------------------------------------------- |:---------------------- | -| AI Chat | `AIAssistantChatViewController` | Full chat screen | -| Chat History | `CometChatAIAssistantChatHistory` | Chat history screen | +## Implementation Flow + +| Step | Action | +|------|--------| +| 1 | User selects AI agent from chat list | +| 2 | Detect agent by checking user role for "agentic" | +| 3 | Launch `ProductionAIAgentViewController` | +| 4 | Configure header, message list, and composer | +| 5 | User sends message, AI responds with streaming | +| 6 | Access chat history via header button | + +## Components Reference + +| Component | Purpose | +|-----------|---------| +| `CometChatMessageHeader` | Navigation and chat history access | +| `CometChatMessageList` | Display messages with AI responses | +| `CometChatMessageComposer` | Send messages to AI agent | +| `CometChatAIAssistantChatHistory` | Browse previous AI conversations | +| `CometChatAiAssistantBubble` | AI message bubble styling | + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| AI not responding | Verify AI features are enabled in dashboard | +| Chat history empty | Ensure conversations are saved properly | +| Streaming not working | Check network connectivity | +| Styling not applied | Apply styles before presenting components | +| Agent not detected | Verify user role contains "agentic" | + +## Related Guides + +- [AI Features](/ui-kit/ios/ai-features) - Overview of AI capabilities +- [AI Assistant Chat History](/ui-kit/ios/ai-assistant-chat-history) - Chat history component +- [Message List](/ui-kit/ios/message-list) - Message display component +- [Message Header](/ui-kit/ios/message-header) - Message header component +- [Message Composer](/ui-kit/ios/message-composer) - Message composer component diff --git a/ui-kit/ios/guide-block-unblock-user.mdx b/ui-kit/ios/guide-block-unblock-user.mdx index 7920f5ed8..5d99c4cf4 100644 --- a/ui-kit/ios/guide-block-unblock-user.mdx +++ b/ui-kit/ios/guide-block-unblock-user.mdx @@ -1,178 +1,708 @@ --- -title: "Implementing Block/Unblock User in iOS with CometChat UIKit" +title: "Block/Unblock User" sidebarTitle: "Block/Unblock User" +description: "Implement user blocking and profile management in your iOS app" --- -Build a comprehensive user profile screen in your iOS app using CometChat’s UIKit for iOS, complete with avatar display, messaging, audio/video calls, and block/unblock actions. +Build a user profile screen with avatar display, messaging, audio/video calls, and block/unblock functionality using CometChat UIKit. -## Overview - -The `UserDetailsViewController` provides a detailed view of a CometChat user’s profile and key interaction options, including: - -- Displaying the user’s avatar, name, and online status. -- Initiating one-on-one chats. -- Starting audio or video calls. -- Blocking or unblocking users. -- Deleting the conversation with the user. + + + ## Prerequisites -- A UIKit-based iOS project. -- CometChat UIKit for iOS v5 installed via CocoaPods or Swift Package Manager. -- Valid CometChat **App ID**, **Region**, and **Auth Key**. -- User authenticated with `CometChat.login()` before presenting the details screen. +Before implementing this feature, ensure you have: -## Components +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- CometChat UIKit v5+ installed +- User logged in with `CometChatUIKit.login()` +- Navigation controller configured + +## Overview -| Component | Role | -|:----------------------------------|:--------------------------------------------------------------| -| `CometChatAvatar` | Displays user’s profile picture with customizable styling. | -| `CometChatMessagesViewController`| Opens the 1-on-1 chat interface when “Message” is tapped. | -| `CometChatCallButtons` | Initiates audio/video calls (`CometChat.startCall()`). | -| `CometChatUIKit.blockUser()` | Blocks the selected user and updates UI accordingly. | -| `CometChatUIKit.unblockUser()` | Unblocks a user if previously blocked. | +The user details screen provides: -## Integration Steps +- **Profile Display** - Avatar, name, and online status +- **Messaging** - Start one-on-one chats +- **Calling** - Audio and video call buttons +- **Block/Unblock** - Manage user relationships +- **Delete Conversation** - Remove chat history -### 1. Presenting the User Details Screen +## Basic Implementation -Initialize and push `UserDetailsViewController` with the selected user’s data. +Create a simple user details screen: ```swift import UIKit +import CometChatUIKitSwift import CometChatSDK -func showUserDetails(for user: User) { - let detailsVC = UserDetailsViewController(user: user) - navigationController?.pushViewController(detailsVC, animated: true) +class UserDetailsViewController: UIViewController { + + private var user: User? + + convenience init(user: User) { + self.init() + self.user = user + } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemBackground + setupUI() + } + + private func setupUI() { + guard let user = user else { return } + + // Avatar + let avatar = CometChatAvatar() + avatar.set(user: user) + avatar.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(avatar) + + // Name label + let nameLabel = UILabel() + nameLabel.text = user.name + nameLabel.font = .systemFont(ofSize: 24, weight: .bold) + nameLabel.textAlignment = .center + nameLabel.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(nameLabel) + + // Status label + let statusLabel = UILabel() + statusLabel.text = user.status == .online ? "Online" : "Offline" + statusLabel.textColor = user.status == .online ? .systemGreen : .secondaryLabel + statusLabel.font = .systemFont(ofSize: 14) + statusLabel.textAlignment = .center + statusLabel.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(statusLabel) + + // Message button + let messageButton = UIButton(type: .system) + messageButton.setTitle("Message", for: .normal) + messageButton.setImage(UIImage(systemName: "message.fill"), for: .normal) + messageButton.addTarget(self, action: #selector(openChat), for: .touchUpInside) + messageButton.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(messageButton) + + // Block button + let blockButton = UIButton(type: .system) + blockButton.setTitle("Block User", for: .normal) + blockButton.setTitleColor(.systemRed, for: .normal) + blockButton.addTarget(self, action: #selector(blockUser), for: .touchUpInside) + blockButton.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(blockButton) + + NSLayoutConstraint.activate([ + avatar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40), + avatar.centerXAnchor.constraint(equalTo: view.centerXAnchor), + avatar.widthAnchor.constraint(equalToConstant: 100), + avatar.heightAnchor.constraint(equalToConstant: 100), + + nameLabel.topAnchor.constraint(equalTo: avatar.bottomAnchor, constant: 16), + nameLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), + + statusLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8), + statusLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), + + messageButton.topAnchor.constraint(equalTo: statusLabel.bottomAnchor, constant: 32), + messageButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), + + blockButton.topAnchor.constraint(equalTo: messageButton.bottomAnchor, constant: 24), + blockButton.centerXAnchor.constraint(equalTo: view.centerXAnchor) + ]) + } + + @objc private func openChat() { + guard let user = user else { return } + let messages = CometChatMessages() + messages.set(user: user) + navigationController?.pushViewController(messages, animated: true) + } + + @objc private func blockUser() { + guard let user = user else { return } + CometChat.blockUsers([user.uid ?? ""]) { [weak self] _ in + DispatchQueue.main.async { + self?.showAlert(title: "Blocked", message: "\(user.name ?? "User") has been blocked") + } + } onError: { error in + print("Block error: \(error?.errorDescription ?? "")") + } + } + + private func showAlert(title: String, message: String) { + let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } } ``` -**File reference:** -[`UserDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/UserDetailsViewController.swift) +## Production Implementation -Ensures the details screen loads with the correct user context. +Complete user details screen with all features and event handling: -### 2. Configuring the UI +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK +#if canImport(CometChatCallsSDK) +import CometChatCallsSDK +#endif -Arrange avatar, labels, and action buttons on the view. +class ProductionUserDetailsViewController: UIViewController { + + // MARK: - Properties + private var user: User? + private var isBlocked: Bool = false + private let listenerID = "user-details-listener" + + // MARK: - UI Components + private let scrollView = UIScrollView() + private let contentView = UIView() + private let avatar = CometChatAvatar() + private let nameLabel = UILabel() + private let statusLabel = UILabel() + private let buttonStackView = UIStackView() + private let messageButton = UIButton(type: .system) + private let audioCallButton = UIButton(type: .system) + private let videoCallButton = UIButton(type: .system) + private let blockButton = UIButton(type: .system) + private let deleteButton = UIButton(type: .system) + + // MARK: - Initialization + convenience init(user: User) { + self.init() + self.user = user + } + + // MARK: - Lifecycle + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemBackground + setupUI() + configureWithUser() + checkBlockStatus() + addEventListeners() + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + setupNavigationBar() + } + + deinit { + removeEventListeners() + } -```swift -override public func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - setupLayout() - setupNavigationBar() - if let user = user { - updateUserStatus(user: user) + // MARK: - Setup + private func setupNavigationBar() { + title = "User Details" + navigationController?.navigationBar.prefersLargeTitles = false + } + + private func setupUI() { + // Scroll View + scrollView.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(scrollView) + + contentView.translatesAutoresizingMaskIntoConstraints = false + scrollView.addSubview(contentView) + + // Avatar + avatar.translatesAutoresizingMaskIntoConstraints = false + contentView.addSubview(avatar) + + // Name Label + nameLabel.font = .systemFont(ofSize: 24, weight: .bold) + nameLabel.textAlignment = .center + nameLabel.translatesAutoresizingMaskIntoConstraints = false + contentView.addSubview(nameLabel) + + // Status Label + statusLabel.font = .systemFont(ofSize: 14) + statusLabel.textAlignment = .center + statusLabel.translatesAutoresizingMaskIntoConstraints = false + contentView.addSubview(statusLabel) + + // Button Stack + buttonStackView.axis = .horizontal + buttonStackView.spacing = 24 + buttonStackView.distribution = .equalSpacing + buttonStackView.translatesAutoresizingMaskIntoConstraints = false + contentView.addSubview(buttonStackView) + + // Message Button + configureButton(messageButton, title: "Message", icon: "message.fill", action: #selector(openChat)) + buttonStackView.addArrangedSubview(messageButton) + + // Call Buttons (conditional) + #if canImport(CometChatCallsSDK) + configureButton(audioCallButton, title: "Audio", icon: "phone.fill", action: #selector(startAudioCall)) + configureButton(videoCallButton, title: "Video", icon: "video.fill", action: #selector(startVideoCall)) + buttonStackView.addArrangedSubview(audioCallButton) + buttonStackView.addArrangedSubview(videoCallButton) + #endif + + // Block Button + blockButton.setTitle("Block User", for: .normal) + blockButton.setTitleColor(.systemRed, for: .normal) + blockButton.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) + blockButton.addTarget(self, action: #selector(toggleBlock), for: .touchUpInside) + blockButton.translatesAutoresizingMaskIntoConstraints = false + contentView.addSubview(blockButton) + + // Delete Button + deleteButton.setTitle("Delete Conversation", for: .normal) + deleteButton.setTitleColor(.systemRed, for: .normal) + deleteButton.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium) + deleteButton.addTarget(self, action: #selector(deleteConversation), for: .touchUpInside) + deleteButton.translatesAutoresizingMaskIntoConstraints = false + contentView.addSubview(deleteButton) + + setupConstraints() + } + + private func configureButton(_ button: UIButton, title: String, icon: String, action: Selector) { + button.setTitle(title, for: .normal) + button.setImage(UIImage(systemName: icon), for: .normal) + button.titleLabel?.font = .systemFont(ofSize: 12) + button.tintColor = .systemBlue + button.configuration = .plain() + button.configuration?.imagePlacement = .top + button.configuration?.imagePadding = 8 + button.addTarget(self, action: action, for: .touchUpInside) + } + + private func setupConstraints() { + NSLayoutConstraint.activate([ + scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), + scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), + scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + + contentView.topAnchor.constraint(equalTo: scrollView.topAnchor), + contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), + contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), + contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), + contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), + + avatar.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 40), + avatar.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + avatar.widthAnchor.constraint(equalToConstant: 100), + avatar.heightAnchor.constraint(equalToConstant: 100), + + nameLabel.topAnchor.constraint(equalTo: avatar.bottomAnchor, constant: 16), + nameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20), + nameLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20), + + statusLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8), + statusLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + + buttonStackView.topAnchor.constraint(equalTo: statusLabel.bottomAnchor, constant: 32), + buttonStackView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + + blockButton.topAnchor.constraint(equalTo: buttonStackView.bottomAnchor, constant: 48), + blockButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + + deleteButton.topAnchor.constraint(equalTo: blockButton.bottomAnchor, constant: 16), + deleteButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), + deleteButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -40) + ]) + } + + // MARK: - Configuration + private func configureWithUser() { + guard let user = user else { return } + + avatar.set(user: user) + nameLabel.text = user.name + updateStatusLabel(user: user) + } + + private func updateStatusLabel(user: User) { + if isBlocked { + statusLabel.text = "Blocked" + statusLabel.textColor = .systemRed + } else { + statusLabel.text = user.status == .online ? "Online" : "Offline" + statusLabel.textColor = user.status == .online ? .systemGreen : .secondaryLabel + } + } + + private func checkBlockStatus() { + guard let uid = user?.uid else { return } + + let request = BlockedUserRequest.BlockedUserRequestBuilder() + .set(limit: 100) + .build() + + request.fetchNext { [weak self] blockedUsers in + let isBlocked = blockedUsers?.contains { $0.uid == uid } ?? false + DispatchQueue.main.async { + self?.isBlocked = isBlocked + self?.updateBlockButton() + self?.updateStatusLabel(user: self?.user ?? User()) + } + } onError: { error in + print("Error checking block status: \(error?.errorDescription ?? "")") + } + } + + private func updateBlockButton() { + let title = isBlocked ? "Unblock User" : "Block User" + blockButton.setTitle(title, for: .normal) + } + + // MARK: - Actions + @objc private func openChat() { + guard let user = user else { return } + + if isBlocked { + showAlert(title: "User Blocked", message: "Unblock this user to send messages") + return + } + + let messages = CometChatMessages() + messages.set(user: user) + navigationController?.pushViewController(messages, animated: true) + } + + #if canImport(CometChatCallsSDK) + @objc private func startAudioCall() { + guard let user = user else { return } + + if isBlocked { + showAlert(title: "User Blocked", message: "Unblock this user to make calls") + return + } + + let call = Call(receiverId: user.uid ?? "", callType: .audio, receiverType: .user) + CometChat.initiateCall(call: call) { call in + print("Audio call initiated: \(call?.sessionID ?? "")") + } onError: { [weak self] error in + self?.showAlert(title: "Call Failed", message: error?.errorDescription ?? "Unable to start call") + } + } + + @objc private func startVideoCall() { + guard let user = user else { return } + + if isBlocked { + showAlert(title: "User Blocked", message: "Unblock this user to make calls") + return + } + + let call = Call(receiverId: user.uid ?? "", callType: .video, receiverType: .user) + CometChat.initiateCall(call: call) { call in + print("Video call initiated: \(call?.sessionID ?? "")") + } onError: { [weak self] error in + self?.showAlert(title: "Call Failed", message: error?.errorDescription ?? "Unable to start call") + } + } + #endif + + @objc private func toggleBlock() { + if isBlocked { + unblockUser() + } else { + showBlockConfirmation() + } + } + + private func showBlockConfirmation() { + let alert = UIAlertController( + title: "Block User", + message: "Are you sure you want to block \(user?.name ?? "this user")? They won't be able to send you messages or call you.", + preferredStyle: .alert + ) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + alert.addAction(UIAlertAction(title: "Block", style: .destructive) { [weak self] _ in + self?.blockUser() + }) + + present(alert, animated: true) + } + + private func blockUser() { + guard let uid = user?.uid else { return } + + CometChat.blockUsers([uid]) { [weak self] blockedUsers in + DispatchQueue.main.async { + self?.isBlocked = true + self?.updateBlockButton() + self?.updateStatusLabel(user: self?.user ?? User()) + + // Emit event for other components + if let user = self?.user { + CometChatUserEvents.emitOnUserBlock(user: user) + } + } + } onError: { [weak self] error in + self?.showAlert(title: "Error", message: error?.errorDescription ?? "Failed to block user") + } + } + + private func unblockUser() { + guard let uid = user?.uid else { return } + + CometChat.unblockUsers([uid]) { [weak self] unblockedUsers in + DispatchQueue.main.async { + self?.isBlocked = false + self?.updateBlockButton() + self?.updateStatusLabel(user: self?.user ?? User()) + + // Emit event for other components + if let user = self?.user { + CometChatUserEvents.emitOnUserUnblock(user: user) + } + } + } onError: { [weak self] error in + self?.showAlert(title: "Error", message: error?.errorDescription ?? "Failed to unblock user") + } + } + + @objc private func deleteConversation() { + let alert = UIAlertController( + title: "Delete Conversation", + message: "Are you sure you want to delete this conversation? This action cannot be undone.", + preferredStyle: .alert + ) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in + self?.performDeleteConversation() + }) + + present(alert, animated: true) + } + + private func performDeleteConversation() { + guard let uid = user?.uid else { return } + + CometChat.deleteConversation(conversationWith: uid, conversationType: .user) { [weak self] _ in + DispatchQueue.main.async { + self?.showAlert(title: "Deleted", message: "Conversation has been deleted") + } + } onError: { [weak self] error in + self?.showAlert(title: "Error", message: error?.errorDescription ?? "Failed to delete conversation") + } + } + + private func showAlert(title: String, message: String) { + let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } + + // MARK: - Event Listeners + private func addEventListeners() { + CometChat.addUserListener(listenerID, self) + CometChatUserEvents.addListener(listenerID, self) + } + + private func removeEventListeners() { + CometChat.removeUserListener(listenerID) + CometChatUserEvents.removeListener(listenerID) } } -``` -**File reference:** -[`UserDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/UserDetailsViewController.swift) +// MARK: - CometChatUserDelegate +extension ProductionUserDetailsViewController: CometChatUserDelegate { + + func onUserOnline(user: User) { + guard user.uid == self.user?.uid else { return } + DispatchQueue.main.async { + self.user = user + self.updateStatusLabel(user: user) + } + } + + func onUserOffline(user: User) { + guard user.uid == self.user?.uid else { return } + DispatchQueue.main.async { + self.user = user + self.updateStatusLabel(user: user) + } + } +} -Applies theme-based styling and updates status label on appearance. +// MARK: - CometChatUserEventListener +extension ProductionUserDetailsViewController: CometChatUserEventListener { + + func ccUserBlocked(user: User) { + guard user.uid == self.user?.uid else { return } + DispatchQueue.main.async { + self.isBlocked = true + self.updateBlockButton() + self.updateStatusLabel(user: user) + } + } + + func ccUserUnblocked(user: User) { + guard user.uid == self.user?.uid else { return } + DispatchQueue.main.async { + self.isBlocked = false + self.updateBlockButton() + self.updateStatusLabel(user: user) + } + } +} +``` -### 3. Enabling Call Buttons +## Launching User Details -Add audio and video call buttons if calls SDK is available. +Open the user details screen from your app: ```swift -#if canImport(CometChatCallsSDK) -buttonContainerStackView.addArrangedSubview(audioCallButton) -buttonContainerStackView.addArrangedSubview(videoCallButton) -#endif -``` - -**File reference:** -[`UserDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/UserDetailsViewController.swift) +import UIKit +import CometChatSDK -Conditionally shows call options based on SDK availability. +class UsersListViewController: UIViewController { + + func showUserDetails(for user: User) { + let detailsVC = ProductionUserDetailsViewController(user: user) + navigationController?.pushViewController(detailsVC, animated: true) + } + + // From a users list + func openFromUsersList() { + let users = CometChatUsers() + users.set(onItemClick: { [weak self] user, _ in + self?.showUserDetails(for: user) + }) + navigationController?.pushViewController(users, animated: true) + } + + // From a conversation + func openFromConversation(_ conversation: Conversation) { + if let user = conversation.conversationWith as? User { + showUserDetails(for: user) + } + } +} +``` -### 4. Block/Unblock and Delete Actions +## Block/Unblock API Reference -Provide block/unblock and delete conversation functionality. +### Block Users ```swift -@objc func showBlockAlert() { - // Toggle block/unblock logic with CometChat.blockUsers / unblockUsers +// Block single user +CometChat.blockUsers(["user-uid"]) { blockedUsers in + print("Blocked \(blockedUsers?.count ?? 0) users") +} onError: { error in + print("Error: \(error?.errorDescription ?? "")") } -@objc func showDeleteAlert() { - // Confirm and call CometChat.deleteConversation() +// Block multiple users +CometChat.blockUsers(["user1", "user2", "user3"]) { blockedUsers in + print("Blocked users: \(blockedUsers?.map { $0.uid ?? "" } ?? [])") +} onError: { error in + print("Error: \(error?.errorDescription ?? "")") } ``` -**File reference:** -[`UserDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/UserDetailsViewController.swift) - -Manages user relationships and conversation lifecycle. - -### 5. Listening for User Events - -Update UI in response to status, block, and unblock events. +### Unblock Users ```swift -func connect() { - CometChat.addUserListener(listenerID, self) - CometChatUserEvents.addListener(listenerID, self) +// Unblock single user +CometChat.unblockUsers(["user-uid"]) { unblockedUsers in + print("Unblocked \(unblockedUsers?.count ?? 0) users") +} onError: { error in + print("Error: \(error?.errorDescription ?? "")") } -func disconnect() { - CometChat.removeUserListener(listenerID) - CometChatUserEvents.removeListener(listenerID) +// Unblock multiple users +CometChat.unblockUsers(["user1", "user2"]) { unblockedUsers in + print("Unblocked users: \(unblockedUsers?.map { $0.uid ?? "" } ?? [])") +} onError: { error in + print("Error: \(error?.errorDescription ?? "")") } +``` + +### Fetch Blocked Users -extension UserDetailsViewController: CometChatUserEventListener, CometChatUserDelegate { - func onUserOnline(user: User) { updateUserStatus(user: user) } - func onUserOffline(user: User) { updateUserStatus(user: user) } - func ccUserBlocked(user: User) { statusLabel.isHidden = true } - func ccUserUnblocked(user: User) { statusLabel.isHidden = false; updateUserStatus(user: user) } +```swift +let request = BlockedUserRequest.BlockedUserRequestBuilder() + .set(limit: 50) + .set(direction: .blockedByMe) // or .hasBlockedMe, .both + .build() + +request.fetchNext { blockedUsers in + for user in blockedUsers ?? [] { + print("Blocked: \(user.name ?? "")") + } +} onError: { error in + print("Error: \(error?.errorDescription ?? "")") } ``` -**File reference:** -[`UserDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/UserDetailsViewController.swift) +## Styling -Keeps profile status and block state in sync with real-time events. +Customize the avatar appearance: -## Customization Options +```swift +let avatarStyle = AvatarStyle() +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 50) +avatarStyle.borderWidth = 2 +avatarStyle.borderColor = .systemBlue +avatarStyle.backgroundColor = .systemGray5 + +avatar.set(style: avatarStyle) +``` -- **Avatar Styling:** Use `CometChatAvatarStyle` to adjust shape and border. -- **Button Assets:** Replace default icons with custom images. -- **Localization:** Override button titles and alerts with localized strings. -- **Theming:** Leverage `CometChatTheme` and `CometChatTypography` for fonts and colors. +## Components Reference -## Filtering & Edge Cases +| Component | Purpose | +|-----------|---------| +| `CometChatAvatar` | Display user profile picture | +| `CometChatMessages` | Open chat interface | +| `CometChat.blockUsers()` | Block users | +| `CometChat.unblockUsers()` | Unblock users | +| `CometChat.deleteConversation()` | Delete chat history | +| `CometChat.initiateCall()` | Start audio/video calls | -- Hide block/unblock controls for the logged-in user. -- Disable call buttons if calling is disabled in settings. -- Handle missing or partially loaded user data with fallback UI. +## Edge Cases + +- **Self-blocking**: Hide block controls when viewing your own profile +- **Already blocked**: Check block status before showing chat/call options +- **Call SDK unavailable**: Conditionally show call buttons with `#if canImport(CometChatCallsSDK)` +- **Missing user data**: Show placeholder UI for incomplete profiles ## Error Handling -- **Fetch Failures:** Show error label or dismiss the view. -- **Block/Unblock Errors:** Present retry alert on API failure. -- **Call Failures:** Alert user on call initiation error or permission denial. - -## Feature Matrix - -| Feature | Component / Method | -|:-------------------------|:---------------------------------------------| -| Display user details | `CometChatAvatar`, `UILabel` | -| Open chat | `CometChatMessagesViewController(user:)` | -| Audio/video call | `CometChat.startCall()` via Call Buttons | -| Block user | `CometChatUIKit.blockUser(uid:)` | -| Unblock user | `CometChatUIKit.unblockUser(uid:)` | -| Delete conversation | `CometChat.deleteConversation()` | - - - - Try the complete sample app for User Details: - [GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) +| Error | Solution | +|-------|----------| +| Block failed | Show retry option, check network | +| Unblock failed | Verify user was previously blocked | +| Call initiation failed | Check permissions and call SDK setup | +| Delete conversation failed | Verify conversation exists | + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| Status not updating | Verify event listeners are added | +| Block state incorrect | Fetch blocked users list on load | +| Call buttons missing | Import CometChatCallsSDK | +| Avatar not loading | Check user has valid avatar URL | + +## Related Components + +- [Users](/ui-kit/ios/users) - Display user list +- [Conversations](/ui-kit/ios/conversations) - Display conversation list +- [Message List](/ui-kit/ios/message-list) - Message display component + + + + Complete implementation example - - Explore CometChat UIKit iOS repository: - [GitHub → UIKit v5](https://github.com/cometchat/cometchat-uikit-ios/tree/v5) + + CometChat UIKit iOS repository - \ No newline at end of file + From 6b21e6d8b1887e499a3b6db71df4343d0887fd7e Mon Sep 17 00:00:00 2001 From: Anshuman-cometchat Date: Thu, 12 Feb 2026 15:24:05 +0530 Subject: [PATCH 006/106] added code snippets and made it agentic friendly --- ui-kit/flutter/ai-features.mdx | 63 +- ui-kit/flutter/call-features.mdx | 118 +++- ui-kit/flutter/core-features.mdx | 185 ++++-- ui-kit/flutter/events.mdx | 159 +++-- ui-kit/flutter/extensions.mdx | 107 +++- ui-kit/flutter/flutter-conversation.mdx | 294 ++++++++- ui-kit/flutter/flutter-one-to-one-chat.mdx | 530 ++++++++++++++- ui-kit/flutter/flutter-tab-based-chat.mdx | 604 ++++++++++++++++-- ui-kit/flutter/getting-started.mdx | 573 ++++++++++++----- ui-kit/flutter/guide-block-unblock-user.mdx | 73 ++- ui-kit/flutter/guide-call-log-details.mdx | 70 +- ui-kit/flutter/guide-group-chat.mdx | 76 ++- ui-kit/flutter/guide-message-agentic-flow.mdx | 70 +- ui-kit/flutter/guide-message-privately.mdx | 75 ++- ui-kit/flutter/guide-new-chat.mdx | 77 ++- ui-kit/flutter/guide-overview.mdx | 47 +- ui-kit/flutter/guide-threaded-messages.mdx | 74 ++- ui-kit/flutter/overview.mdx | 140 +++- 18 files changed, 2813 insertions(+), 522 deletions(-) diff --git a/ui-kit/flutter/ai-features.mdx b/ui-kit/flutter/ai-features.mdx index 18e1637c9..8ffcac57f 100644 --- a/ui-kit/flutter/ai-features.mdx +++ b/ui-kit/flutter/ai-features.mdx @@ -1,7 +1,43 @@ --- -title: "AI" +title: "AI Features" +description: "Enhance user interaction with AI-powered conversation starters, smart replies, and conversation summaries in your Flutter app" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Enable AI features in UIKitSettings +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..aiFeature = [ + AISmartRepliesExtension(), + AIConversationStarterExtension(), + AIAssistBotExtension(), + AIConversationSummaryExtension() + ] +).build(); + +// Initialize with AI features +CometChatUIKit.init(uiKitSettings: uiKitSettings); +``` + +**Key AI Extensions:** +- `AISmartRepliesExtension` → Smart reply suggestions +- `AIConversationStarterExtension` → Conversation starters +- `AIAssistBotExtension` → AI assistant bot +- `AIConversationSummaryExtension` → Conversation summaries + +**Components:** +- Conversation Starters → Auto-displayed in `CometChatMessageList` ([Docs](/ui-kit/flutter/message-list)) +- Smart Replies → Available in `CometChatMessageComposer` action sheet ([Docs](/ui-kit/flutter/message-composer)) +- Conversation Summary → Available in `CometChatMessageComposer` action sheet ([Docs](/ui-kit/flutter/message-composer)) + +Activate features from [CometChat Dashboard](https://app.cometchat.com) → Extensions → AI + + ## Overview CometChat's AI capabilities greatly enhance user interaction and engagement in your application. Let's understand how the Flutter UI Kit achieves these features. @@ -10,6 +46,10 @@ CometChat's AI capabilities greatly enhance user interaction and engagement in y + +**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [Dashboard](https://app.cometchat.com) + + *** ## Usage @@ -67,8 +107,27 @@ The Conversation Summary feature provides concise summaries of long 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 [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/flutter/message-composer) Widget of UI Kits. +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/flutter/message-composer) Widget of UI Kits. + +--- + +## Next Steps + + + + Display and manage conversation messages with AI-powered starters + + + Compose messages with smart replies and AI assistance + + + Learn more about AI features and configuration + + + Explore other extensions to enhance your chat experience + + diff --git a/ui-kit/flutter/call-features.mdx b/ui-kit/flutter/call-features.mdx index 12559e904..2322a5c28 100644 --- a/ui-kit/flutter/call-features.mdx +++ b/ui-kit/flutter/call-features.mdx @@ -1,11 +1,53 @@ --- -title: "Call" +title: "Call Features" +description: "Integrate one-on-one and group audio/video calling capabilities into your Flutter app with CometChat UI Kit" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; + +// Enable calling features in UIKitSettings +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "APP_ID" + ..authKey = "AUTH_KEY" + ..region = "REGION" + ..callingExtension = CometChatCallingExtension() +).build(); + +// Initialize with calling support +CometChatUIKit.init(uiKitSettings: uiKitSettings); + +// Set navigation key for incoming calls +CometChatUsersWithMessages(key: CallNavigationContext.navigatorKey) + +// Add call listener +CometChat.addCallListener(listenerId, this); +``` + +**Key Calling Components:** +- `CometChatCallButtons` → [Docs](/ui-kit/flutter/call-buttons) +- `CometChatIncomingCall` → [Docs](/ui-kit/flutter/incoming-call) +- `CometChatOutgoingCall` → [Docs](/ui-kit/flutter/outgoing-call) +- `CometChatCallLogs` → [Docs](/ui-kit/flutter/call-logs) +- `CometChatCallingExtension` → Calling extension +- `CallNavigationContext` → Navigation context for calls + +**Requirements:** `cometchat_calls_uikit` package, minSdkVersion 24 (Android), iOS 12+ + + ## Overview CometChat's Calls feature is an advanced functionality that 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 Flutter UI Kit. + +**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) + + ## 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/flutter/getting-started) guide. This guide will walk you through a step-by-step process of integrating our UI Kit into your Flutter project. @@ -24,9 +66,7 @@ Add the following dependency to your `pubspec.yaml` file: dependencies: cometchat_calls_uikit: ^5.0.12 ``` - - *** @@ -47,17 +87,11 @@ defaultConfig { versionName flutterVersionName } ``` - - - -If you want to use the Flutter UI Kit or enable calling support within it, you'll need to: - -1. Set the `minSdkVersion` to 24 in your `android/app/build.gradle` file. - +If you want to use the Flutter UI Kit or enable calling support within it, you'll need to set the `minSdkVersion` to 24 in your `android/app/build.gradle` file. *** @@ -73,9 +107,7 @@ In your Podfile located at `ios/Podfile`, update the minimum iOS version that yo ```xml platform :ios, '12.0' ``` - - *** @@ -94,22 +126,24 @@ Example UIKitSettings uiKitSettings = (UIKitSettingsBuilder() ..subscriptionType = CometChatSubscriptionType.allUsers ..autoEstablishSocketConnection = true - ..region = "REGION"//Replace with your App Region - ..appId = "APP_ID" //Replace with your App ID - ..authKey = "AUTH_KEY" //Replace with your app Auth Key - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array you want to disable all extensions - ..callingExtension = CometChatCallingExtension() //Added this to Enable calling feature in the UI Kit + ..region = "REGION" // Replace with your App Region + ..appId = "APP_ID" // Replace with your App ID + ..authKey = "AUTH_KEY" // Replace with your app Auth Key + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension() // Enable calling feature ).build(); -CometChatUIKit.init(uiKitSettings: uiKitSettings,onSuccess: (successMessage) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +CometChatUIKit.init( + uiKitSettings: uiKitSettings, + onSuccess: (successMessage) { + // TODO("Not yet implemented") + }, + onError: (e) { + // TODO("Not yet implemented") + } +); ``` - - To allow launching of Incoming Call screen from any widget whenever a call is received provide set key: CallNavigationContext.navigatorKey in the top most widget of your project (the widget that appears first of your app launch). @@ -118,14 +152,19 @@ To allow launching of Incoming Call screen from any widget whenever a call is re ```dart CometChatUIKit.login(uid, onSuccess: (s) { - Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatUsersWithMessages(key: CallNavigationContext.navigatorKey))); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatUsersWithMessages( + key: CallNavigationContext.navigatorKey + ) + ) + ); }, onError: (e) { // TODO("Not yet implemented") }); ``` - - After adding this dependency, the Flutter UI Kit will automatically detect it and activate the calling features. Now, your application supports both audio and video calling. You will see [CallButtons](/ui-kit/flutter/call-buttons) widget rendered in [MessageHeader](/ui-kit/flutter/message-header) Widget. @@ -147,13 +186,13 @@ class _YourClassNameState extends State with CallListener { @override void initState() { super.initState(); - CometChat.addCallListener(listenerId, this); //Add listener + CometChat.addCallListener(listenerId, this); // Add listener } @override void dispose() { super.dispose(); - CometChat.removeCallListener(listenerId); //Remove listener + CometChat.removeCallListener(listenerId); // Remove listener } @override @@ -193,9 +232,7 @@ class _YourClassNameState extends State with CallListener { } } ``` - - *** @@ -229,3 +266,22 @@ Importantly, the Outgoing Call widget is smartly designed to transition automati + +--- + +## Next Steps + + + + Add audio and video call buttons to your chat interface + + + Handle and display incoming call screens + + + Manage outgoing call screens and transitions + + + Display call history and records + + diff --git a/ui-kit/flutter/core-features.mdx b/ui-kit/flutter/core-features.mdx index 5d91b8c1f..fc991048d 100644 --- a/ui-kit/flutter/core-features.mdx +++ b/ui-kit/flutter/core-features.mdx @@ -1,13 +1,35 @@ --- -title: "Core" +title: "Core Features" +sidebarTitle: "Core" +description: "Comprehensive guide to CometChat's core messaging features including instant messaging, media sharing, read receipts, and more" --- -## Overview +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +Key components for core features: +- **Instant Messaging** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) +- **Media Sharing** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) +- **Read Receipts** → [Conversations](/ui-kit/flutter/conversations) | [MessageList](/ui-kit/flutter/message-list) +- **Typing Indicators** → [Conversations](/ui-kit/flutter/conversations) | [MessageHeader](/ui-kit/flutter/message-header) +- **User Presence** → [Conversations](/ui-kit/flutter/conversations) | [Users](/ui-kit/flutter/users) +- **Reactions** → [MessageList](/ui-kit/flutter/message-list) +- **Mentions** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) +- **Threaded Messages** → [Threaded Messages](/ui-kit/flutter/threaded-messages-header) +- **Group Chat** → [Groups](/ui-kit/flutter/groups) + The UI Kit comprises a variety of widgets, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. + +**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [REST API](https://api-explorer.cometchat.com) + + Here's how different UI Kit widgets work together to achieve CometChat's Core features: +*** + ## Instant Messaging At the heart of CometChat's functionality is the ability to support real-time text messaging. Users can send and receive instant messages, fostering quick and efficient communication. @@ -16,10 +38,12 @@ At the heart of CometChat's functionality is the ability to support real-time te -| Widgets | Functionality | -| -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a Widget that enables users to write and send a variety of messages. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders a list of messages sent and messages received using [TextBubble](/ui-kit/flutter/message-bubble-styling#text-bubble). | +| Widgets | Functionality | +| --- | --- | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a Widget that enables users to write and send a variety of messages. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders a list of messages sent and messages received using [TextBubble](/ui-kit/flutter/message-bubble-styling#text-bubble). | + +*** ## Media Sharing @@ -29,10 +53,12 @@ Beyond text, CometChat allows users to share various media types within their co -| Widgets | Functionality | -| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a Widget that has ActionSheet, ActionSheet is a menu that appears over the context of the app, providing multiple options for sharing media files. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different Media Message bubbles like [Image Bubble](/ui-kit/flutter/message-bubble-styling-styling#image-bubble), [File Bubble](/ui-kit/flutter/message-bubble-styling-styling#file-bubble), [Audio Bubble](/ui-kit/flutter/message-bubble-styling-styling#audio-bubble) [Video Bubble](/ui-kit/flutter/message-bubble-styling#video-bubble) | +| Widgets | Functionality | +| --- | --- | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a Widget that has ActionSheet, ActionSheet is a menu that appears over the context of the app, providing multiple options for sharing media files. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different Media Message bubbles like [Image Bubble](/ui-kit/flutter/message-bubble-styling#image-bubble), [File Bubble](/ui-kit/flutter/message-bubble-styling#file-bubble), [Audio Bubble](/ui-kit/flutter/message-bubble-styling#audio-bubble), [Video Bubble](/ui-kit/flutter/message-bubble-styling#video-bubble) | + +*** ## Read Receipts @@ -42,11 +68,12 @@ CometChat's Read Receipts feature provides visibility into the message status, l -| Widgets | Functionality | -| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversation item also displays the delivery status of the last message providing users with real-time updates on the status of their messages. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different types of Message bubbles, Read Recept status is an integral part of all message bubbles, no matter the type, and provides real-time updates about the status of the message. | -| [MessageInformation](/ui-kit/flutter/message-information) | [MessageInformation](/ui-kit/flutter/message-information) widget provides transparency into the status of each sent message, giving the sender insights into whether their message has been delivered and read. | +| Widgets | Functionality | +| --- | --- | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversation item also displays the delivery status of the last message providing users with real-time updates on the status of their messages. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different types of Message bubbles, Read Receipt status is an integral part of all message bubbles, no matter the type, and provides real-time updates about the status of the message. | + +*** ## Mark As Unread @@ -56,10 +83,12 @@ Mark as Unread feature allows users to manually mark messages as unread, helping -| Widgets | Functionality | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/flutter/message-list#functionality) | [Message List](/ui-kit/flutter/message-list#functionality) provides the "Mark as unread" option in message actions and supports starting from the first unread message when enabled. | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) widget listens to conversation updates and reflects the updated unread count in real-time. | +| Widgets | Functionality | +| --- | --- | +| [Message List](/ui-kit/flutter/message-list) | [Message List](/ui-kit/flutter/message-list) provides the "Mark as unread" option in message actions and supports starting from the first unread message when enabled. | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) widget listens to conversation updates and reflects the updated unread count in real-time. | + +*** ## Typing Indicator @@ -69,11 +98,13 @@ The Typing Indicator feature in CometChat shows when a user is typing a response -| Widgets | Functionality | -| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversations item also shows real-time typing status indicators. This means that if a user in a one-on-one chat or a participant in a group chat is currently typing a message | +| Widgets | Functionality | +| --- | --- | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversations item also shows real-time typing status indicators. This means that if a user in a one-on-one chat or a participant in a group chat is currently typing a message | | [Message Header](/ui-kit/flutter/message-header) | [Message Header](/ui-kit/flutter/message-header) that renders details of User or Groups in ToolBar. The MessageHeader also handles the Typing Indicator functionality. When a user or a member in a group is typing, the MessageHeader dynamically updates to display a 'typing...' status in real-time. | +*** + ## User Presence CometChat's User Presence feature allows users to see whether their contacts are online, offline. This helps users know the best time to initiate a conversation and sets expectations about response times. @@ -82,12 +113,14 @@ CometChat's User Presence feature allows users to see whether their contacts are -| Widgets | Functionality | -| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversations item also shows user presence information. | +| Widgets | Functionality | +| --- | --- | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) is a Widget that renders Conversations item List, Conversations item also shows user presence information. | | [Message Header](/ui-kit/flutter/message-header) | [Message Header](/ui-kit/flutter/message-header) that renders details of User or Groups in ToolBar. The MessageHeader also handles user Presence information. | -| [Users](/ui-kit/flutter/users) | [Users](/ui-kit/flutter/users) renders list of users available in your app.It also responsible to render users Presence information. | -| [Group Members](/ui-kit/flutter/group-members) | [Group Members](/ui-kit/flutter/group-members) renders list of users available in the group. The Group Members widget also handles user Presence information. | +| [Users](/ui-kit/flutter/users) | [Users](/ui-kit/flutter/users) renders list of users available in your app. It also responsible to render users Presence information. | +| [Group Members](/ui-kit/flutter/group-members) | [Group Members](/ui-kit/flutter/group-members) renders list of users available in the group. The Group Members widget also handles user Presence information. | + +*** ## Reactions @@ -101,10 +134,12 @@ In the example, tapping on this element (depicted as "+2" in the provided image) -| Widgets | Functionality | -| ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Widgets | Functionality | +| --- | --- | | [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a Widget that renders different types of Message bubbles, Irrespective of the type of message bubble, Reactions are an integral part and offer a more engaging, expressive way for users to respond to messages. | +*** + ## Mentions Mentions is a robust feature provided by CometChat that enhances the interactivity and clarity of group or 1-1 chats by allowing users to directly address or refer to specific individuals in a conversation. The feature also supports group mentions like @all, enabling users to quickly notify all members in a group chat simultaneously. @@ -113,38 +148,45 @@ Mentions is a robust feature provided by CometChat that enhances the interactivi -| Widgets | Functionality | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) widget provides an enhanced user experience by integrating the Mentions feature. This means that from the conversation list itself, users can see where they or someone else have been specifically mentioned. | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer)is a widget that allows users to craft and send various types of messages, including the usage of the Mentions feature for direct addressing within the conversation. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a widget that displays a list of sent and received messages. It also supports the rendering of Mentions, enhancing the readability and interactivity of conversations. | +| Widgets | Functionality | +| --- | --- | +| [Conversations](/ui-kit/flutter/conversations) | [Conversations](/ui-kit/flutter/conversations) widget provides an enhanced user experience by integrating the Mentions feature. This means that from the conversation list itself, users can see where they or someone else have been specifically mentioned. | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) is a widget that allows users to craft and send various types of messages, including the usage of the Mentions feature for direct addressing within the conversation. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) is a widget that displays a list of sent and received messages. It also supports the rendering of Mentions, enhancing the readability and interactivity of conversations. | + +*** ## Quoted Reply -Quoted Reply is a robust feature provided by CometChat that enables users to quickly reply to specific messages by selecting the “Reply” option from a message’s action menu. This enhances context, keeps conversations organized, and improves overall chat experience in both 1-1 and group chats. +Quoted Reply is a robust feature provided by CometChat that enables users to quickly reply to specific messages by selecting the "Reply" option from a message's action menu. This enhances context, keeps conversations organized, and improves overall chat experience in both 1-1 and group chats. -| Widgets | Functionality | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) supports replying to messages via the “Reply” option. Users can select “Reply” on a message to open the composer with the quoted reply pre-filled, maintaining context. | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer)works seamlessly with Quoted Message by showing the quoted reply above the input field, letting users compose their response in proper context. | +| Widgets | Functionality | +| --- | --- | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) supports replying to messages via the "Reply" option. Users can select "Reply" on a message to open the composer with the quoted reply pre-filled, maintaining context. | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) works seamlessly with Quoted Message by showing the quoted reply above the input field, letting users compose their response in proper context. | + +*** ## Conversation and Advanced Search Conversation and Advanced Search is a powerful feature provided by CometChat that 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. + -| Widgets | Functionality | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [Search](/ui-kit/flutter/message-header) | [Search](/ui-kit/flutter/message-header) 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. | -| [Message Header](/ui-kit/flutter/message-header) | [Message Header](/ui-kit/flutter/message-header) shows the search button in the chat header, allowing users to search within a conversation. | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) shows the selected message when clicked from search results and highlights it in the message list. | -| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) displays the search input. | +| Widgets | Functionality | +| --- | --- | +| [Search](/ui-kit/flutter/search) | [Search](/ui-kit/flutter/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. | +| [Message Header](/ui-kit/flutter/message-header) | [Message Header](/ui-kit/flutter/message-header) shows the search button in the chat header, allowing users to search within a conversation. | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) shows the selected message when clicked from search results and highlights it in the message list. | +| [MessageComposer](/ui-kit/flutter/message-composer) | [MessageComposer](/ui-kit/flutter/message-composer) displays the search input. | + +*** ## Moderation @@ -158,12 +200,14 @@ CometChat's Message Moderation feature helps maintain a safe and respectful chat Learn more about setting up moderation rules and managing content in the [Moderation](/moderation/overview) documentation. -| Widgets | Functionality | -| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Widgets | Functionality | +| --- | --- | | [Message List](/ui-kit/flutter/message-list) | [Message List](/ui-kit/flutter/message-list) automatically handles moderated messages, displaying blocked content appropriately based on your moderation settings. | After implementing moderation rules, users can report messages they find inappropriate or harmful. As a next step, you can enable the **[Report Message](#report-message)** feature to allow users to flag messages for review by moderators. +*** + ## Report Message The Report Message feature allows users to report inappropriate or harmful messages within the chat. Users can choose from predefined reasons and provide additional remarks for detailed context. This feature helps maintain a safe and respectful chat environment. @@ -173,12 +217,14 @@ Learn more about how flagged messages are handled, reviewed, and moderated in th - + -| Components | Functionality | -| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Message List](/ui-kit/flutter/message-list) | [Message List](/ui-kit/flutter/message-list) provides the "Report Message" option in the message actions menu, allowing users to initiate the reporting process for inappropriate messages. | +| Widgets | Functionality | +| --- | --- | +| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) provides the "Report Message" option in the message actions menu, allowing users to initiate the reporting process for inappropriate messages. | + +*** ## Threaded Conversations @@ -188,21 +234,11 @@ The Threaded Conversations feature enables users to respond directly to a specif -| Widgets | Functionality | -| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| Widgets | Functionality | +| --- | --- | | [Threaded Messages](/ui-kit/flutter/threaded-messages-header) | [Threaded Messages](/ui-kit/flutter/threaded-messages-header) that displays all replies made to a particular message in a conversation. | -## Report Message - -The Report Message feature allows users to report inappropriate or harmful messages within the chat. Users can choose from predefined reasons and provide additional remarks for detailed context. This feature helps maintain a safe and respectful chat environment. - - - - - -| Widgets | Functionality | -| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [MessageList](/ui-kit/flutter/message-list) | [MessageList](/ui-kit/flutter/message-list) provides the “Report Message” option in the message actions menu, allowing users to initiate the reporting process for inappropriate messages. | +*** ## Group Chat @@ -213,3 +249,24 @@ CometChat facilitates Group Chats, allowing users to have conversations with mul For a comprehensive understanding and guide on implementing and using the Groups feature in CometChat, you should refer to our detailed guide on [Groups](/ui-kit/flutter/groups). + +*** + +## Next Steps + + + + Learn how to send text, media, and custom messages + + + Display and manage messages with real-time updates + + + Show conversation lists with typing indicators and receipts + + + Create and manage group conversations + + + +*** diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 7e059a76b..7d7f857d1 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -1,17 +1,47 @@ --- title: "Events" +description: "Listen to and handle real-time events for users, groups, conversations, messages, calls, and UI interactions in Flutter UI Kit" --- -## Overview +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Add event listener +CometChatMessageEvents.addMessagesListener("LISTENER_ID", this); + +// Remove event listener +CometChatMessageEvents.removeMessagesListener("LISTENER_ID"); + +// Implement listener methods +@override +void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { + // Handle message sent event +} +``` + +**Available Event Types:** +- **User Events** → Block/Unblock users +- **Group Events** → Create, delete, join, leave groups +- **Conversation Events** → Delete conversations +- **Message Events** → Send, edit, delete, receive messages +- **Call Events** → Outgoing, accepted, rejected, ended calls +- **UI Events** → Show/hide panels, active chat changes + Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. Both Components and Composite Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. -### User Events +*** + +## User Events `CometChatUserEvents` emit events when the logged-in user executes actions on another user. This class provides methods to add and remove listeners for user events, as well as methods to handle specific user actions such as blocking and unblocking users. +**Available Events:** + 1. `ccUserBlocked`: Triggered when the logged-in user blocks another user. 2. `ccUserUnblocked`: Triggered when the logged-in user unblocks another user. @@ -61,18 +91,16 @@ class _UserEventsExampleState extends State with CometChatUse } } ``` - - *** -### Group Events +## Group Events `CometChatGroupEvents` Emits events when the logged-in user performs actions related to groups. This class provides methods to listen to various group-related events and handle them accordingly. -Following are all the group events +**Available Events:** 1. `ccGroupCreated`: Triggered when the logged-in user creates a group. 2. `ccGroupDeleted`: Triggered when the logged-in user deletes a group. @@ -85,8 +113,6 @@ Following are all the group events 9. `ccGroupMemberAdded`: Triggered when the logged-in user adds new members to the group. 10. `ccOwnershipChanged`: Triggered when the logged-in user transfers the ownership of their group to some other member. -To listen to group events - ```dart @@ -165,30 +191,27 @@ class _GroupEventsExampleState extends State with CometChatG @override void ccOwnershipChanged(Group group, GroupMember newOwner) { - + // TODO("Not yet implemented") } @override Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - *** -### Conversation Events +## Conversation Events -The `CometChatConversationEvents` component emits events when the logged-in user performs actions related to conversations. This allows for the UI to be updated accordingly. Below are the events emitted by the Conversation Component: +The `CometChatConversationEvents` component emits events when the logged-in user performs actions related to conversations. This allows for the UI to be updated accordingly. -1. `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. +**Available Events:** -To listen to conversation events and handle them in your application, you can use the following code snippets: +1. `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. @@ -229,19 +252,18 @@ class _ConversationEventsExampleState extends State w Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - *** -### Message Events +## Message Events + +`CometChatMessageEvents` emits events when various actions are performed on messages within the application. These events facilitate updating the UI accordingly. -`CometChatMessageEvents` emits events when various actions are performed on messages within the application. These events facilitate updating the UI accordingly. Below are the events emitted by the MessageEvents component: +**Available Events:** 1. `ccMessageSent`: Triggered whenever a logged-in user sends any message. It can have two states: `inProgress` and `sent`. 2. `ccMessageEdited`: Triggered whenever a logged-in user edits any message from the list of messages. It can have two states: `inProgress` and `sent`. @@ -267,8 +289,6 @@ class _ConversationEventsExampleState extends State w 22. `onMessageReactionAdded`: Triggered when a reaction is added to a message. 23. `onMessageReactionRemoved`: Triggered when a reaction is removed from a message. -To listen to message events and handle them in your application, you can use the following code snippets: - ```dart @@ -296,7 +316,7 @@ class _MessageEventsExampleState extends State with CometC void dispose() { super.dispose(); - CometChatConversationEvents.removeConversationListListener(listenerID); // Remove the listener + CometChatMessageEvents.removeMessagesListener(listenerID); // Remove the listener } @override @@ -407,7 +427,7 @@ class _MessageEventsExampleState extends State with CometC @override void onMessageReactionRemoved(ReactionEvent reactionEvent) { - // TODO("Not yet implemented") + // TODO("Not yet implemented") } @override @@ -416,17 +436,17 @@ class _MessageEventsExampleState extends State with CometC } } ``` - - *** -### Call Events +## Call Events `CometChatCallEvents` emits events related to calls within the application. This class provides methods to listen to call-related events and handle them accordingly. +**Available Events:** + 1. `ccOutgoingCall`: Triggered when the logged-in user initiates an outgoing call. 2. `ccCallAccepted`: Triggered when a call is accepted. 3. `ccCallRejected`: Triggered when a call is rejected. @@ -488,26 +508,22 @@ class _CallEventsExampleState extends State with CometChatCal } } ``` - - *** -### UI Events +## UI Events `CometChatUIEvents` emits events related to UI components within the CometChat UI. This class provides methods to listen to UI-related events and handle them accordingly. -Following are the UI events +**Available Events:** 1. `showPanel`: Triggered to show an additional UI panel with custom elements. 2. `hidePanel`: Triggered to hide a previously shown UI panel. 3. `ccActiveChatChanged`: Triggered when the active chat changes, providing information about the current message, user, and group. 4. `ccOpenChat`: Triggered to open a chat with a specific user or group. -To listen to UI events and handle them in your application, you can use the following code snippet: - ```dart @@ -574,9 +590,80 @@ class _UIEventsExampleState extends State with CometChatUIEvent } } ``` - - *** + +## Best Practices + + + + Always remove event listeners in the `dispose()` method to prevent memory leaks: + + + + ```dart + @override + void dispose() { + super.dispose(); + CometChatMessageEvents.removeMessagesListener(listenerID); + } + ``` + + + + + + Use unique listener IDs for each widget to avoid conflicts: + + + + ```dart + String listenerID = "message_list_${widget.key}"; + ``` + + + + + + Keep event handlers lightweight and avoid heavy operations: + + + + ```dart + @override + void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { + if (messageStatus == MessageStatus.sent) { + // Update UI efficiently + setState(() { + // Minimal state update + }); + } + } + ``` + + + + + +*** + +## Next Steps + + + + Learn how to display and manage messages with events + + + Handle conversation events and updates + + + Manage group events and member actions + + + Explore available methods for UI Kit operations + + + +*** diff --git a/ui-kit/flutter/extensions.mdx b/ui-kit/flutter/extensions.mdx index 0e4c88e7c..24d3cc1d9 100644 --- a/ui-kit/flutter/extensions.mdx +++ b/ui-kit/flutter/extensions.mdx @@ -1,16 +1,48 @@ --- title: "Extensions" +description: "Enhance your chat with built-in extensions including stickers, polls, collaborative tools, message translation, and link previews" --- -## Overview +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** -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. +```dart +// Enable extensions during initialization +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() +).build(); + +await CometChatUIKit.init(uiKitSettings: uiKitSettings); +``` + +**Built-in Extensions:** +- **Stickers** → Express emotions with pre-designed stickers +- **Polls** → Create polls for group discussions +- **Collaborative Whiteboard** → Real-time drawing and brainstorming +- **Collaborative Document** → Shared document editing +- **Message Translation** → Translate messages to local locale +- **Link Preview** → Show URL summaries with thumbnails +- **Thumbnail Generation** → Auto-generate image previews + +**Enable from:** [CometChat Dashboard](https://app.cometchat.com) → Extensions + + +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. + + +**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [Dashboard](https://app.cometchat.com) + 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 the extension features will only be available if they are supported by CometChat UI Kit. -CometChat’s UI Kit offers built-in support for 12 powerful 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 widgets of your application, providing a richer and more engaging experience for your users. +CometChat's UI Kit offers built-in support for 12 powerful 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 widgets of your application, providing a richer and more engaging experience for your users. + +*** ## Built-in Extensions @@ -26,6 +58,8 @@ Once you have successfully activated the [Sticker Extension](/fundamentals/stick +*** + ### 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). @@ -36,6 +70,8 @@ Once you have successfully activated the [Polls Extension](/fundamentals/polls) +*** + ### 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](/fundamentals/collaborative-whiteboard). @@ -46,6 +82,8 @@ Once you have successfully activated the [Collaborative Whiteboard Extension](/f +*** + ### 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](/fundamentals/collaborative-document). @@ -56,6 +94,8 @@ Once you have successfully activated the [Collaborative Document Extension](/fun +*** + ### 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). @@ -66,6 +106,8 @@ Once you have successfully activated the [Message Translation Extension](/fundam +*** + ### 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). @@ -76,6 +118,8 @@ Once you have successfully activated the [Link Preview Extension](/fundamentals/ +*** + ### 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). @@ -85,3 +129,60 @@ Once you have successfully activated the [Thumbnail Generation Extension](/funda + +*** + +## Enabling Extensions + +To enable extensions in your Flutter app, configure them during initialization: + + + +```dart +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..authKey = "YOUR_AUTH_KEY" + ..subscriptionType = CometChatSubscriptionType.allUsers + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Enable all default extensions +).build(); + +await CometChatUIKit.init(uiKitSettings: uiKitSettings); +``` + + + +To disable all extensions, pass an empty array: + + + +```dart +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..extensions = [] // Disable all extensions +).build(); +``` + + + +*** + +## Next Steps + + + + Learn how extensions integrate with the message composer + + + See how extensions enhance message display + + + Explore all available extensions in detail + + + Enable extensions from your CometChat Dashboard + + + +*** diff --git a/ui-kit/flutter/flutter-conversation.mdx b/ui-kit/flutter/flutter-conversation.mdx index 6a198673c..965ae8489 100644 --- a/ui-kit/flutter/flutter-conversation.mdx +++ b/ui-kit/flutter/flutter-conversation.mdx @@ -1,7 +1,50 @@ --- title: "Conversation List + Message View" +sidebarTitle: "Conversation + Message" +description: "Build a two-panel chat interface with conversation list and message view using Flutter UI Kit widgets" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Show conversations with navigation to messages +CometChatConversations( + showBackButton: true, + onItemTap: (conversation) { + final target = conversation.conversationWith; + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => MessagesScreen( + user: target is User ? target : null, + group: target is Group ? target : null, + ), + ), + ); + }, +) + +// Messages screen with header, list, and composer +Scaffold( + appBar: CometChatMessageHeader(user: user, group: group), + body: Column( + children: [ + Expanded(child: CometChatMessageList(user: user, group: group)), + CometChatMessageComposer(user: user, group: group), + ], + ), +) +``` + +**Key Components:** +- **Conversations** → [CometChatConversations](/ui-kit/flutter/conversations) +- **Message List** → [CometChatMessageList](/ui-kit/flutter/message-list) +- **Message Composer** → [CometChatMessageComposer](/ui-kit/flutter/message-composer) +- **Message Header** → [CometChatMessageHeader](/ui-kit/flutter/message-header) + + The **Conversation List + Message View** layout provides a seamless **two-panel chat interface**, commonly seen in modern messaging apps like **WhatsApp Web**, **Slack**, and **Microsoft Teams**. This layout allows users to switch between conversations while keeping the active chat open, delivering a **smooth, real-time messaging experience**. @@ -12,43 +55,71 @@ This layout allows users to switch between conversations while keeping the activ *** +## **How It Works** + +This implementation uses Flutter's navigation system to create a mobile-friendly chat experience: + +1. **Conversation List Screen** – Displays all recent conversations using `CometChatConversations` +2. **Navigation** – Tapping a conversation pushes the message screen onto the navigation stack +3. **Message Screen** – Shows the full chat interface with header, message list, and composer +4. **Back Navigation** – Users can return to the conversation list using the back button + +*** + +## **Implementation** + ### **Step 1: Render the Conversation Component** The `CometChatConversations` widget displays all conversations related to the currently logged-in user. Follow the steps below to render this component: + + ```dart main.dart - @override - Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: CometChatConversations( - showBackButton: true, - onItemTap: (conversation) { - - final target = conversation.conversationWith; - - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => MessagesScreen( - user: target is User ? target : null, - group: target is Group ? target : null, - ), +@override +Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: CometChatConversations( + showBackButton: true, + onItemTap: (conversation) { + final target = conversation.conversationWith; + + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => MessagesScreen( + user: target is User ? target : null, + group: target is Group ? target : null, ), - ); - }, - ), + ), + ); + }, ), - ); - } + ), + ); +} ``` + + + +**Key Properties:** + +| Property | Type | Description | +| --- | --- | --- | +| `showBackButton` | bool | Shows/hides the back button in the app bar | +| `onItemTap` | Function | Callback when a conversation is tapped | +| `conversationWith` | User or Group | The target entity (user or group) for the conversation | + +*** -#### **Full Example: main.dart** +### **Full Example: main.dart** + + ```dart main.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; //Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling import 'messages_screen.dart'; import 'cometchat_config.dart'; @@ -80,8 +151,8 @@ class Home extends StatelessWidget { ..appId = CometChatConfig.appId ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions + ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling await CometChatUIKit.init(uiKitSettings: settings.build()); await CometChatUIKit.login( @@ -131,7 +202,6 @@ class ConversationsPage extends StatelessWidget { child: CometChatConversations( showBackButton: true, onItemTap: (conversation) { - final target = conversation.conversationWith; Navigator.push( @@ -150,19 +220,25 @@ class ConversationsPage extends StatelessWidget { } } ``` + + + +*** ### **Step 2: Render the Messages Component** To create a complete messaging view, include the following components in `messages_screen.dart`: -* [Message Header](/ui-kit/flutter/message-header) -* [Message List](/ui-kit/flutter/message-list) -* [Message Composer](/ui-kit/flutter/message-composer) +* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions +* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation +* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages + + ```dart messages_screen.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; @@ -205,6 +281,16 @@ class _MessagesScreenState extends State { } } ``` + + + +**Component Breakdown:** + +| Component | Purpose | Key Features | +| --- | --- | --- | +| `CometChatMessageHeader` | Shows conversation title, avatar, and actions | User/group info, back button, call buttons | +| `CometChatMessageList` | Displays messages in chronological order | Real-time updates, reactions, replies | +| `CometChatMessageComposer` | Input field for composing messages | Text, media, attachments, emojis | *** @@ -212,7 +298,7 @@ class _MessagesScreenState extends State { Use the following command to run the app on a connected device or emulator: -``` +```bash flutter run ``` @@ -220,10 +306,150 @@ This will launch the app and display the **Conversation List**. Tapping a conver *** -## **Next Steps** +## **Customization Options** + +### **Conversation List Customization** + + + +```dart +CometChatConversations( + title: "My Chats", + showBackButton: false, + hideSearch: false, + onItemTap: (conversation) { + // Custom navigation logic + }, + onItemLongPress: (conversation) { + // Show options menu + }, + conversationsStyle: ConversationsStyle( + background: Colors.white, + titleStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + ), +) +``` + + + +### **Message Screen Customization** + + + +```dart +CometChatMessageList( + user: user, + group: group, + hideMessageComposer: false, + hideMessageHeader: false, + messageListStyle: MessageListStyle( + background: Colors.grey[100], + ), +) +``` + + + +For complete customization options, see: +* [Conversations Customization](/ui-kit/flutter/conversations) +* [Message List Customization](/ui-kit/flutter/message-list) +* [Message Composer Customization](/ui-kit/flutter/message-composer) +* [Theming Guide](/ui-kit/flutter/theme-introduction) + +*** -### **Enhance the User Experience** +## **Common Use Cases** + + + + + + ```dart + CometChatConversations( + conversationsRequestBuilder: ConversationsRequestBuilder() + ..conversationType = CometChatConversationType.user // or .group + ..limit = 30, + ) + ``` + + + + + + + + ```dart + CometChatConversations( + onItemLongPress: (conversation) { + showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Options'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + title: Text('Delete Conversation'), + onTap: () { + // Delete conversation logic + }, + ), + ], + ), + ), + ); + }, + ) + ``` + + + + + + + + ```dart + Navigator.push( + context, + PageRouteBuilder( + pageBuilder: (context, animation, secondaryAnimation) => MessagesScreen( + user: target is User ? target : null, + group: target is Group ? target : null, + ), + transitionsBuilder: (context, animation, secondaryAnimation, child) { + return SlideTransition( + position: Tween( + begin: const Offset(1.0, 0.0), + end: Offset.zero, + ).animate(animation), + child: child, + ); + }, + ), + ); + ``` + + + + + +*** + +## **Next Steps** -* **[Advanced Customizations](/ui-kit/flutter/theme-introduction)** – Personalize the chat UI to align with your brand. + + + Learn about all conversation list customization options + + + Explore message list, header, and composer features + + + Customize colors, fonts, and styles to match your brand + + + Handle real-time events and user interactions + + *** diff --git a/ui-kit/flutter/flutter-one-to-one-chat.mdx b/ui-kit/flutter/flutter-one-to-one-chat.mdx index 36a22d780..136095916 100644 --- a/ui-kit/flutter/flutter-one-to-one-chat.mdx +++ b/ui-kit/flutter/flutter-one-to-one-chat.mdx @@ -1,8 +1,54 @@ --- title: "Building A One To One/Group Chat Experience" sidebarTitle: "One To One/Group Chat" +description: "Create a focused direct messaging interface for one-to-one or group conversations using Flutter UI Kit" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Fetch a user and show messages directly +Future fetchCometChatUser(String uid) async { + final completer = Completer(); + CometChat.getUser( + uid, + onSuccess: (user) => completer.complete(user), + onError: (error) => completer.completeError(error), + ); + return completer.future; +} + +// Show messages screen directly +FutureBuilder( + future: fetchCometChatUser("cometchat-uid-2"), + builder: (context, snapshot) { + if (snapshot.hasData) { + return MessagesScreen(user: snapshot.data!); + } + return CircularProgressIndicator(); + }, +) + +// Messages screen +Scaffold( + appBar: CometChatMessageHeader(user: user, group: group), + body: Column( + children: [ + Expanded(child: CometChatMessageList(user: user, group: group)), + CometChatMessageComposer(user: user, group: group), + ], + ), +) +``` + +**Key Components:** +- **Message List** → [CometChatMessageList](/ui-kit/flutter/message-list) +- **Message Composer** → [CometChatMessageComposer](/ui-kit/flutter/message-composer) +- **Message Header** → [CometChatMessageHeader](/ui-kit/flutter/message-header) + + The **One-to-One Chat** feature provides a streamlined **direct messaging interface**, making it ideal for **support chats, dating apps, and private messaging platforms**. This setup eliminates distractions by focusing solely on a **dedicated chat window**. @@ -11,40 +57,79 @@ The **One-to-One Chat** feature provides a streamlined **direct messaging interf *** +## **How It Works** + +This implementation bypasses the conversation list and opens directly into a chat: + +1. **Fetch User/Group** – Retrieve the target user or group using their UID/GUID +2. **Direct Navigation** – Launch directly into the message screen +3. **Focused Experience** – No conversation list, just the active chat +4. **Ideal for Context** – Perfect for support tickets, notifications, or deep links + +*** + +## **Use Cases** + +* **Customer Support** – Direct users to agent chat from help center +* **Dating Apps** – Open chat after a match +* **Notifications** – Deep link from push notification to specific chat +* **Onboarding** – Guide new users through a welcome chat +* **Contextual Messaging** – Start chat from user profile or product page + +*** + +## **Implementation** + ### **Step 1: Render the Message View** -The `CometChatConversations` widget displays all conversations related to the currently logged-in user. Follow the steps below to render this component: +The `CometChatMessageList` widget displays all messages for a specific user or group. Follow the steps below to render this component: + + ```dart main.dart - @override - Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: FutureBuilder( - future: fetchCometChatUser("cometchat-uid-2"), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return const Center(child: CircularProgressIndicator()); - } else if (snapshot.hasError) { - return Center(child: Text("Error: ${snapshot.error}")); - } else if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } else { - return const Center(child: Text("User not found")); - } - }, - ), +@override +Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: FutureBuilder( + future: fetchCometChatUser("cometchat-uid-2"), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Center(child: CircularProgressIndicator()); + } else if (snapshot.hasError) { + return Center(child: Text("Error: ${snapshot.error}")); + } else if (snapshot.hasData) { + return MessagesScreen(user: snapshot.data!); + } else { + return const Center(child: Text("User not found")); + } + }, ), - ); - } + ), + ); +} ``` + + + +**Key Concepts:** -#### **Full Example: main.dart** +| Concept | Description | +| --- | --- | +| `fetchCometChatUser()` | Async function to retrieve user by UID | +| `FutureBuilder` | Widget that builds based on async operation state | +| `MessagesScreen` | Custom widget containing message components | +*** + +### **Full Example: main.dart** + + + ```dart main.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; //Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling import 'messages_screen.dart'; import 'cometchat_config.dart'; @@ -78,8 +163,8 @@ class Home extends StatelessWidget { ..appId = CometChatConfig.appId ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions + ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling await CometChatUIKit.init(uiKitSettings: settings.build()); await CometChatUIKit.login( @@ -155,19 +240,25 @@ class MessagesPage extends StatelessWidget { } } ``` + + + +*** ### **Step 2: Render the Messages Component** To create a complete messaging view, include the following components in `messages_screen.dart`: -* [Message Header](/ui-kit/flutter/message-header) -* [Message List](/ui-kit/flutter/message-list) -* [Message Composer](/ui-kit/flutter/message-composer) +* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions +* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation +* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages + + ```dart messages_screen.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; @@ -210,6 +301,16 @@ class _MessagesScreenState extends State { } } ``` + + + +**Component Breakdown:** + +| Component | Purpose | Key Features | +| --- | --- | --- | +| `CometChatMessageHeader` | Shows conversation title, avatar, and actions | User/group info, back button, call buttons | +| `CometChatMessageList` | Displays messages in chronological order | Real-time updates, reactions, replies | +| `CometChatMessageComposer` | Input field for composing messages | Text, media, attachments, emojis | *** @@ -217,7 +318,7 @@ class _MessagesScreenState extends State { Use the following command to run the app on a connected device or emulator: -``` +```bash flutter run ``` @@ -225,10 +326,375 @@ This will launch the app, and you should see the one-to-one chat interface with *** -## **Next Steps** +## **Variations** + +### **For Group Chat** + +To open a group chat instead of a one-to-one chat, fetch a group instead of a user: + + + +```dart +Future fetchCometChatGroup(String guid) async { + final completer = Completer(); + CometChat.getGroup( + guid, + onSuccess: (group) => completer.complete(group), + onError: (error) => completer.completeError(error), + ); + return completer.future; +} -### **Enhance the User Experience** +// In your widget +FutureBuilder( + future: fetchCometChatGroup("your-group-guid"), + builder: (context, snapshot) { + if (snapshot.hasData) { + return MessagesScreen(group: snapshot.data!); + } + return CircularProgressIndicator(); + }, +) +``` + + + +### **From Route Parameters** + +Pass user/group ID through navigation: + + + +```dart +// Navigate with parameters +Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChatScreen(userId: "cometchat-uid-2"), + ), +); + +// ChatScreen widget +class ChatScreen extends StatelessWidget { + final String userId; + + const ChatScreen({Key? key, required this.userId}) : super(key: key); + + Future fetchUser() async { + final completer = Completer(); + CometChat.getUser( + userId, + onSuccess: (user) => completer.complete(user), + onError: (error) => completer.completeError(error), + ); + return completer.future; + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: fetchUser(), + builder: (context, snapshot) { + if (snapshot.hasData) { + return MessagesScreen(user: snapshot.data!); + } + return Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + }, + ); + } +} +``` + + + +### **From Deep Link** + +Handle deep links to open specific chats: + + + +```dart +// In your main app +MaterialApp( + onGenerateRoute: (settings) { + if (settings.name == '/chat') { + final args = settings.arguments as Map; + return MaterialPageRoute( + builder: (_) => ChatScreen( + userId: args['userId'], + groupId: args['groupId'], + ), + ); + } + return null; + }, +) + +// Navigate from deep link +Navigator.pushNamed( + context, + '/chat', + arguments: {'userId': 'cometchat-uid-2'}, +); +``` + + + +*** + +## **Customization Options** + +### **Hide Header or Composer** + + + +```dart +MessagesScreen( + user: user, + hideMessageHeader: true, // Hide the header + hideMessageComposer: false, // Show the composer +) +``` + + + +### **Custom Message Actions** + + + +```dart +CometChatMessageList( + user: user, + onMessageTap: (message) { + // Handle message tap + }, + onMessageLongPress: (message) { + // Show options menu + }, +) +``` + + + +### **Styling** + + + +```dart +CometChatMessageList( + user: user, + messageListStyle: MessageListStyle( + background: Colors.grey[100], + loadingIconTint: Colors.blue, + ), +) +``` + + + +For complete customization options, see: +* [Message List Customization](/ui-kit/flutter/message-list) +* [Message Header Customization](/ui-kit/flutter/message-header) +* [Message Composer Customization](/ui-kit/flutter/message-composer) +* [Theming Guide](/ui-kit/flutter/theme-introduction) + +*** + +## **Common Use Cases** + + + + + + ```dart + // From support ticket screen + ElevatedButton( + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChatScreen( + userId: ticket.assignedAgentId, + ), + ), + ); + }, + child: Text('Chat with Support'), + ) + ``` + + + + + + + + ```dart + // From user profile screen + IconButton( + icon: Icon(Icons.message), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => ChatScreen(userId: profile.userId), + ), + ); + }, + ) + ``` + + + + + + + + ```dart + // Handle notification tap + void handleNotificationTap(Map data) { + final userId = data['senderId']; + Navigator.pushNamed( + context, + '/chat', + arguments: {'userId': userId}, + ); + } + ``` + + + + + + + + ```dart + CometChatMessageComposer( + user: user, + text: "Hello! I need help with...", // Pre-filled text + ) + ``` + + + + + +*** + +## **Best Practices** + + + + Always handle errors when fetching users or groups: + + + + ```dart + FutureBuilder( + future: fetchCometChatUser(userId), + builder: (context, snapshot) { + if (snapshot.hasError) { + return Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.error, size: 48, color: Colors.red), + SizedBox(height: 16), + Text('Failed to load chat'), + ElevatedButton( + onPressed: () => setState(() {}), // Retry + child: Text('Retry'), + ), + ], + ), + ), + ); + } + // ... rest of builder + }, + ) + ``` + + + + + + Provide clear loading indicators: + + + + ```dart + if (snapshot.connectionState == ConnectionState.waiting) { + return Scaffold( + body: Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text('Loading chat...'), + ], + ), + ), + ); + } + ``` + + + + + + Cache fetched users to avoid repeated API calls: + + + + ```dart + class UserCache { + static final Map _cache = {}; + + static Future getUser(String uid) async { + if (_cache.containsKey(uid)) { + return _cache[uid]!; + } + + final completer = Completer(); + CometChat.getUser( + uid, + onSuccess: (user) { + _cache[uid] = user; + completer.complete(user); + }, + onError: (error) => completer.completeError(error), + ); + return completer.future; + } + } + ``` + + + + + +*** + +## **Next Steps** -* **[Advanced Customizations](/ui-kit/flutter/theme-introduction)** – Personalize the chat UI to align with your brand. + + + Explore message list, header, and composer features + + + Add a conversation list for multi-chat support + + + Customize colors, fonts, and styles to match your brand + + + Handle real-time events and user interactions + + *** diff --git a/ui-kit/flutter/flutter-tab-based-chat.mdx b/ui-kit/flutter/flutter-tab-based-chat.mdx index cc2abe662..5959a206b 100644 --- a/ui-kit/flutter/flutter-tab-based-chat.mdx +++ b/ui-kit/flutter/flutter-tab-based-chat.mdx @@ -1,9 +1,49 @@ --- title: "Building A Messaging UI With Tabs, Sidebar, And Message View" sidebarTitle: "Tab Based Chat Experience" +description: "Create a multi-tab chat interface with conversations, calls, users, and groups using Flutter bottom navigation" --- -This guide walks you through creating a **tab-based messaging UI** using **React** and **CometChat UIKit**. The UI will include different sections for **Chats, Calls, Users, and Groups**, allowing seamless navigation. +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Tab-based UI with bottom navigation +Scaffold( + body: PageView( + controller: _pageController, + children: [ + CometChatConversations(), + CometChatCallLogs(), + CometChatUsers(), + CometChatGroups(), + ], + ), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _selectedIndex, + onTap: (index) { + setState(() => _selectedIndex = index); + _pageController.jumpToPage(index); + }, + items: [ + BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Chat"), + BottomNavigationBarItem(icon: Icon(Icons.call), label: "Calls"), + BottomNavigationBarItem(icon: Icon(Icons.person), label: "Users"), + BottomNavigationBarItem(icon: Icon(Icons.group), label: "Groups"), + ], + ), +) +``` + +**Key Components:** +- **Conversations** → [CometChatConversations](/ui-kit/flutter/conversations) +- **Call Logs** → [CometChatCallLogs](/ui-kit/flutter/call-logs) +- **Users** → [CometChatUsers](/ui-kit/flutter/users) +- **Groups** → [CometChatGroups](/ui-kit/flutter/groups) + + +This guide walks you through creating a **tab-based messaging UI** using **Flutter** and **CometChat UIKit**. The UI will include different sections for **Chats, Calls, Users, and Groups**, allowing seamless navigation. *** @@ -15,50 +55,123 @@ This guide walks you through creating a **tab-based messaging UI** using **React This layout consists of: -1. **Sidebar (Conversation List)** – Displays recent conversations with active users and groups. -2. **Message View** – Shows the selected chat with real-time messages. -3. **Message Input Box** – Allows users to send messages seamlessly. +1. **Bottom Navigation Bar** – Tabs for switching between Chats, Calls, Users, and Groups +2. **Page View** – Displays the selected tab's content +3. **Conversation List** – Shows recent conversations with active users and groups +4. **Message View** – Opens when a conversation is tapped + +*** + +## **How It Works** + +This implementation uses Flutter's `BottomNavigationBar` and `PageView` to create a tabbed interface: + +1. **Bottom Navigation** – Provides quick access to different sections +2. **Page View** – Swipeable pages for each tab +3. **State Management** – Syncs selected tab with page view +4. **Navigation** – Tapping a conversation opens the message screen *** +## **Use Cases** + +* **All-in-One Chat Apps** – Complete messaging solution with multiple features +* **Business Messengers** – Professional communication with organized sections +* **Social Platforms** – Community chat with user discovery +* **Support Apps** – Help desk with call logs and user management +* **Team Collaboration** – Internal communication with group management + +*** + +## **Implementation** + ### **Step 1: Render the Tab Component** -The `CometChatConversations` widget displays all conversations related to the currently logged-in user. Follow the steps below to render this component: +The tab-based UI uses `BottomNavigationBar` for navigation and `PageView` for content display: + + ```dart main.dart - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - ), - body: SafeArea( - child: Column( - children: [ - Expanded( - child: CometChatMessageList( - user: widget.user, - group: widget.group, +@override +Widget build(BuildContext context) { + return Scaffold( + body: PageView( + controller: _pageController, + onPageChanged: (index) { + setState(() { + _selectedIndex = index; + }); + }, + children: [ + CometChatConversations( + showBackButton: false, + onItemTap: (conversation) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => MessagesScreen( + user: conversation.conversationWith is User + ? conversation.conversationWith as User + : null, + group: conversation.conversationWith is Group + ? conversation.conversationWith as Group + : null, + ), ), - ), - CometChatMessageComposer( - user: widget.user, - group: widget.group, - ), - ], + ); + }, ), - ), - ); - } + CometChatCallLogs(), + CometChatUsers(), + CometChatGroups(), + ], + ), + bottomNavigationBar: BottomNavigationBar( + currentIndex: _selectedIndex, + onTap: _onItemTapped, + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.chat), + label: "Chat", + ), + BottomNavigationBarItem( + icon: Icon(Icons.call), + label: "Calls", + ), + BottomNavigationBarItem( + icon: Icon(Icons.person), + label: "Users", + ), + BottomNavigationBarItem( + icon: Icon(Icons.group), + label: "Groups", + ), + ], + ), + ); +} ``` + + + +**Key Components:** -#### **Full Example: main.dart** +| Component | Purpose | Key Features | +| --- | --- | --- | +| `PageView` | Container for swipeable pages | Smooth transitions, gesture support | +| `BottomNavigationBar` | Tab navigation | Icon + label, active state | +| `PageController` | Controls page view | Jump to page, animate transitions | + +*** +### **Full Example: main.dart** + + + ```dart main.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; //Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling import 'messages_screen.dart'; import 'cometchat_config.dart'; @@ -90,8 +203,8 @@ class Home extends StatelessWidget { ..appId = CometChatConfig.appId ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions + ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling await CometChatUIKit.init(uiKitSettings: settings.build()); await CometChatUIKit.login( @@ -149,6 +262,12 @@ class _TabsScreenState extends State { _pageController.jumpToPage(index); } + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -179,13 +298,34 @@ class _TabsScreenState extends State { }, ), CometChatCallLogs(), - CometChatUsers(), - CometChatGroups(), + CometChatUsers( + onItemTap: (user) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => MessagesScreen(user: user), + ), + ); + }, + ), + CometChatGroups( + onItemTap: (group) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => MessagesScreen(group: group), + ), + ); + }, + ), ], ), bottomNavigationBar: BottomNavigationBar( + type: BottomNavigationBarType.fixed, currentIndex: _selectedIndex, onTap: _onItemTapped, + selectedItemColor: Colors.deepPurple, + unselectedItemColor: Colors.grey, items: const [ BottomNavigationBarItem( icon: Icon(Icons.chat), @@ -209,19 +349,25 @@ class _TabsScreenState extends State { } } ``` + + + +*** ### **Step 2: Render the Messages Component** To create a complete messaging view, include the following components in `messages_screen.dart`: -* [Message Header](/ui-kit/flutter/message-header) -* [Message List](/ui-kit/flutter/message-list) -* [Message Composer](/ui-kit/flutter/message-composer) +* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions +* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation +* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages + + ```dart messages_screen.dart import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; @@ -264,6 +410,8 @@ class _MessagesScreenState extends State { } } ``` + + *** @@ -271,7 +419,7 @@ class _MessagesScreenState extends State { Use the following command to run the app on a connected device or emulator: -``` +```bash flutter run ``` @@ -279,10 +427,384 @@ This will launch the app, and you should see the tab-based chat experience with *** -## **Next Steps** +## **Tab Descriptions** + +### **1. Chat Tab** + +Displays recent conversations with users and groups: + +* **CometChatConversations** – Shows conversation list +* **Real-time updates** – New messages appear instantly +* **Unread counts** – Badge showing unread message count +* **Last message preview** – Shows snippet of last message +* **Tap to open** – Navigate to full message view + +### **2. Calls Tab** + +Shows call history and logs: + +* **CometChatCallLogs** – Displays all call records +* **Call types** – Audio and video calls +* **Call status** – Missed, incoming, outgoing +* **Tap to call back** – Initiate new call from history +* **Call duration** – Shows length of completed calls + +### **3. Users Tab** + +Browse and search all users: + +* **CometChatUsers** – Lists all available users +* **Search functionality** – Find users by name +* **User status** – Online/offline indicators +* **Tap to chat** – Start conversation with any user +* **User avatars** – Profile pictures + +### **4. Groups Tab** + +Manage and join groups: + +* **CometChatGroups** – Shows all groups +* **Group types** – Public, private, password-protected +* **Member count** – Number of participants +* **Join groups** – Request to join or join directly +* **Tap to chat** – Open group conversation + +*** + +## **Customization Options** + +### **Custom Tab Icons** + + + +```dart +BottomNavigationBar( + items: const [ + BottomNavigationBarItem( + icon: Icon(Icons.forum), + activeIcon: Icon(Icons.forum, size: 28), + label: "Chats", + ), + BottomNavigationBarItem( + icon: Icon(Icons.phone), + activeIcon: Icon(Icons.phone, size: 28), + label: "Calls", + ), + // ... more tabs + ], +) +``` + + + +### **Custom Tab Colors** + + + +```dart +BottomNavigationBar( + selectedItemColor: Colors.blue, + unselectedItemColor: Colors.grey, + backgroundColor: Colors.white, + elevation: 8, + // ... items +) +``` + + + +### **Disable Swipe Between Tabs** + + + +```dart +PageView( + controller: _pageController, + physics: NeverScrollableScrollPhysics(), // Disable swipe + children: [ + // ... pages + ], +) +``` + + + +### **Add More Tabs** + + + +```dart +// Add a Settings tab +children: [ + CometChatConversations(), + CometChatCallLogs(), + CometChatUsers(), + CometChatGroups(), + SettingsScreen(), // New tab +], + +items: [ + // ... existing items + BottomNavigationBarItem( + icon: Icon(Icons.settings), + label: "Settings", + ), +], +``` + + + +### **Custom Tab Styling** + + + +```dart +CometChatConversations( + title: "My Chats", + conversationsStyle: ConversationsStyle( + background: Colors.white, + titleStyle: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), +) +``` + + + +For complete customization options, see: +* [Conversations Customization](/ui-kit/flutter/conversations) +* [Call Logs Customization](/ui-kit/flutter/call-logs) +* [Users Customization](/ui-kit/flutter/users) +* [Groups Customization](/ui-kit/flutter/groups) +* [Theming Guide](/ui-kit/flutter/theme-introduction) + +*** + +## **Common Use Cases** + + + + + + ```dart + BottomNavigationBarItem( + icon: Stack( + children: [ + Icon(Icons.chat), + if (unreadCount > 0) + Positioned( + right: 0, + top: 0, + child: Container( + padding: EdgeInsets.all(2), + decoration: BoxDecoration( + color: Colors.red, + borderRadius: BorderRadius.circular(10), + ), + constraints: BoxConstraints( + minWidth: 16, + minHeight: 16, + ), + child: Text( + '$unreadCount', + style: TextStyle( + color: Colors.white, + fontSize: 10, + ), + textAlign: TextAlign.center, + ), + ), + ), + ], + ), + label: "Chat", + ) + ``` + + + + + + + + ```dart + // Save selected tab to shared preferences + void _onItemTapped(int index) async { + setState(() => _selectedIndex = index); + _pageController.jumpToPage(index); + + final prefs = await SharedPreferences.getInstance(); + await prefs.setInt('selected_tab', index); + } + + // Load selected tab on init + @override + void initState() { + super.initState(); + _loadSelectedTab(); + } + + Future _loadSelectedTab() async { + final prefs = await SharedPreferences.getInstance(); + final savedIndex = prefs.getInt('selected_tab') ?? 0; + setState(() => _selectedIndex = savedIndex); + _pageController.jumpToPage(savedIndex); + } + ``` + + + + + + + + ```dart + void _onItemTapped(int index) { + setState(() => _selectedIndex = index); + _pageController.animateToPage( + index, + duration: Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + } + ``` + + + + + + + + ```dart + @override + Widget build(BuildContext context) { + return WillPopScope( + onWillPop: () async { + if (_selectedIndex != 0) { + // Go back to first tab instead of exiting + _onItemTapped(0); + return false; + } + return true; // Allow exit + }, + child: Scaffold( + // ... rest of widget + ), + ); + } + ``` + + + + + +*** + +## **Best Practices** + + + + Always dispose of controllers to prevent memory leaks: + + + + ```dart + @override + void dispose() { + _pageController.dispose(); + super.dispose(); + } + ``` + + + + + + For 4+ tabs, use fixed type to prevent shifting: + + + + ```dart + BottomNavigationBar( + type: BottomNavigationBarType.fixed, // Prevents label shifting + // ... rest of properties + ) + ``` + + + + + + Load tab content only when needed: + + + + ```dart + PageView( + controller: _pageController, + children: [ + _selectedIndex == 0 ? CometChatConversations() : SizedBox(), + _selectedIndex == 1 ? CometChatCallLogs() : SizedBox(), + _selectedIndex == 2 ? CometChatUsers() : SizedBox(), + _selectedIndex == 3 ? CometChatGroups() : SizedBox(), + ], + ) + ``` + + + + + + Refresh tab content when switching: + + + + ```dart + void _onItemTapped(int index) { + setState(() => _selectedIndex = index); + _pageController.jumpToPage(index); + + // Refresh current tab + _refreshTab(index); + } + + void _refreshTab(int index) { + // Implement refresh logic for each tab + switch (index) { + case 0: + // Refresh conversations + break; + case 1: + // Refresh call logs + break; + // ... etc + } + } + ``` + + + + -### **Enhance the User Experience** +*** + +## **Next Steps** -* **[Advanced Customizations](/ui-kit/flutter/theme-introduction)** – Personalize the chat UI to align with your brand. + + + Customize the conversation list appearance and behavior + + + Configure call history and calling features + + + Manage user lists and group memberships + + + Customize colors, fonts, and styles to match your brand + + *** diff --git a/ui-kit/flutter/getting-started.mdx b/ui-kit/flutter/getting-started.mdx index d919825e9..1b53fde4e 100644 --- a/ui-kit/flutter/getting-started.mdx +++ b/ui-kit/flutter/getting-started.mdx @@ -1,48 +1,127 @@ --- title: "Getting Started With CometChat Flutter UI Kit" sidebarTitle: "Getting Started" +description: "Install and configure CometChat Flutter UI Kit with step-by-step setup, initialization, and authentication guide" --- -CometChat UI Kit for Flutter is a package of pre-assembled UI elements crafted to streamline the creation of an in-app chat equipped with essential messaging functionalities. Our UI Kit presents options for light and dark themes, diverse fonts, colors, and extra customization capabilities. +{/* TL;DR for Agents and Quick Reference */} + +**Quick Setup Reference** + +```bash +# Install +flutter pub add cometchat_chat_uikit +flutter pub add cometchat_calls_uikit # Optional: for calling + +# Initialize (run once at app start) +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..authKey = "YOUR_AUTH_KEY" + ..subscriptionType = CometChatSubscriptionType.allUsers + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension() +).build(); +await CometChatUIKit.init(uiKitSettings: uiKitSettings); + +# Login (after init) +await CometChatUIKit.login("cometchat-uid-1"); +``` -CometChat UI Kit supports both one-to-one and group conversations. Follow the guide below to initiate conversations from scratch using CometChat Flutter UI Kit. +**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 -{/* - - */} +**Integration Paths:** +- **Conversation List + Message** → [flutter-conversation](/ui-kit/flutter/flutter-conversation) +- **One-to-One Chat** → [flutter-one-to-one-chat](/ui-kit/flutter/flutter-one-to-one-chat) +- **Tab-Based Chat** → [flutter-tab-based-chat](/ui-kit/flutter/flutter-tab-based-chat) + + +The **CometChat UI Kit for Flutter** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI widgets**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. + +With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat Flutter UI Kit. -## Prerequisites +*** + +## **Prerequisites** + +Before installing the **CometChat UI Kit for Flutter**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: + +* **User Management** +* **Group Chat & Messaging** +* **Voice & Video Calling** +* **Real-time Notifications** + + + +To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: + +1. **App ID** +2. **Auth Key** +3. **Region** + +Ensure you have these details ready before proceeding with the installation and configuration. + + + +*** + +## **Register & Set Up CometChat** + +Follow these steps to **register on CometChat** and **set up your development environment**. + +### **Step 1: Register on CometChat** + +To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. + +🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** + +### **Step 2: Get Your Application Keys** -Before installing the **UI Kit**, you need to create a CometChat application on the CometChat Dashboard, which includes all the necessary data for a chat service, such as users, groups, calls, and messages. You will require the `App ID`, `AuthKey`, and `Region` of your CometChat application when initializing the SDK. +After registering, create a **new app** and retrieve your **authentication details**: -**i. Register on CometChat** +1. Navigate to the **QuickStart** or **API & Auth Keys** section. -* You need to register on the **CometChat Dashboard** first. [Click here to sign up](https://app.cometchat.com/login). +2. Note down the following keys: -**ii. Get Your Application Keys** + * **App ID** + * **Auth Key** + * **Region** -* Create a **new app** -* Head over to the **QuickStart** or **API & Auth Keys section** and note the **App ID**, **Auth Key**, and **Region**. + -> Each CometChat application can be integrated with a single client app. Within the same application, users can communicate with each other across all platforms, whether they are on mobile devices or on the web. +Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **iOS, Android, and web**. -**iii. Platform & IDE Setup** + -* Flutter installed on your system. -* Android Studio or VS Code with configured Flutter/Dart plugins. -* Xcode & Pod (CocoaPods) for iOS -* An iOS device or emulator with iOS 12.0 or above. -* Android device or emulator with Android version 5.0 or above. +### **Step 3: Set Up Your Development Environment** -## Getting Started +Ensure your system meets the following **prerequisites** before proceeding with integration. -### **Step 1: Create Flutter application project** +**System Requirements:** -To get started, create a new flutter application project. +* **Flutter** installed on your system (Flutter 3.0 or higher recommended) +* **Android Studio** or **VS Code** with configured Flutter/Dart plugins +* **Xcode & CocoaPods** for iOS development +* An **iOS device or simulator** with iOS 12.0 or above +* An **Android device or emulator** with Android version 5.0 (API level 21) or above + +*** + +## **Getting Started** + +### **Step 1: Create Flutter Application Project** + +To get started, create a new Flutter application project: + +```bash +flutter create my_chat_app +cd my_chat_app +``` *** @@ -53,46 +132,57 @@ To get started, create a new flutter application project. To use this UI Kit in your Flutter project, you'll need to add the following dependency to the dependencies section of your `pubspec.yaml` file: ```yaml pubspec.yaml +dependencies: + flutter: + sdk: flutter + cometchat_chat_uikit: ^5.2.8 - cometchat_calls_uikit: ^5.0.12 #Optional: Include if you're using Audio/Video Calling + cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling ``` -Final `pubspec.yaml` +**Final `pubspec.yaml` Example:** ```yaml pubspec.yaml - name: getting_started - description: "A new Flutter project." +name: my_chat_app +description: "A Flutter chat application using CometChat UI Kit" - publish_to: 'none' # Remove this line if you wish to publish to pub.dev +publish_to: 'none' - version: 1.0.0+1 +version: 1.0.0+1 - environment: - sdk: ^3.5.3 +environment: + sdk: ^3.5.3 - dependencies: - flutter: - sdk: flutter +dependencies: + flutter: + sdk: flutter - cometchat_chat_uikit: ^5.2.8 - cometchat_calls_uikit: ^5.0.12 #Optional: Include if you're using Audio/Video Calling - cupertino_icons: ^1.0.8 + cometchat_chat_uikit: ^5.2.8 + cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling + cupertino_icons: ^1.0.8 - dev_dependencies: - flutter_test: - sdk: flutter +dev_dependencies: + flutter_test: + sdk: flutter - flutter_lints: ^4.0.0 + flutter_lints: ^4.0.0 - flutter: - uses-material-design: true +flutter: + uses-material-design: true +``` + +After updating `pubspec.yaml`, run: + +```bash +flutter pub get ``` *** **2. Android App Setup** -To ensure compatibility with the CometChat Calling UI Kit and its dependencies, your Flutter project must target a minimum SDK version of **24 or higher**.\ +To ensure compatibility with the CometChat Calling UI Kit and its dependencies, your Flutter project must target a minimum SDK version of **24 or higher**. + Update the `minSdkVersion` in your Android project configuration, located at `android/app/build.gradle`: ```gradle build.gradle @@ -108,20 +198,34 @@ android { **3. Update iOS Podfile** -In your Podfile (located at ios/Podfile), update the minimum iOS version your project supports to 12.0: +In your Podfile (located at `ios/Podfile`), update the minimum iOS version your project supports to 12.0: ```ruby Podfile platform :ios, '12.0' ``` +After updating, run: + +```bash +cd ios +pod install +cd .. +``` + *** -4. Import CometChat UIKit In your Dart code, import the CometChat UIKit package to access its features. Add the following import statement to your main.dart file: +**4. Import CometChat UIKit** + +In your Dart code, import the CometChat UIKit package to access its features. Add the following import statement to your `main.dart` file: + + ```dart main.dart - import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; //Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling ``` + + *** @@ -129,64 +233,153 @@ platform :ios, '12.0' Before using any features from the CometChat UI Kit, initialize it with your app credentials. -1. **Import & Configure UIKit Settings** You can store your app credentials (App ID, Auth Key, Region) in a dedicated configuration file and load them dynamically in your app. - - **Example Configuration File:** - - ```dart cometchat_config.dart - class CometChatConfig { - static const String appId = "APP_ID"; // Replace with your App ID - static const String region = "REGION"; // Replace with your App Region - static const String authKey = "AUTH_KEY"; // Replace with your Auth Key - } - ``` - - **Initialization Code:** - - ```dart main.dart - import 'cometchat_config.dart'; - - UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..region = CometChatConfig.region - ..appId = CometChatConfig.appId - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling - ).build(); - - CometChatUIKit.init( - uiKitSettings: uiKitSettings, - onSuccess: (successMessage) async { - debugPrint('CometChat Initialized'); - // You can now log in the user - }, - onError: (error) { - debugPrint('CometChat Initialization error'); - }, - ); - ``` - - > Store your CometChat credentials in a config file to simplify environment management and avoid hardcoding. + + +You must call `CometChatUIKit.init()` before rendering any UI Kit widgets or calling any SDK methods. Initialization must complete before login. + + + +**1. Import & Configure UIKit Settings** + +You can store your app credentials (App ID, Auth Key, Region) in a dedicated configuration file and load them dynamically in your app. + +**Example Configuration File:** + + + +```dart cometchat_config.dart +class CometChatConfig { + static const String appId = "APP_ID"; // Replace with your App ID + static const String region = "REGION"; // Replace with your App Region + static const String authKey = "AUTH_KEY"; // Replace with your Auth Key +} +``` + + + +**Initialization Code:** + + + +```dart main.dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional +import 'cometchat_config.dart'; + +void main() { + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'CometChat UI Kit', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + home: const Home(), + ); + } +} + +class Home extends StatelessWidget { + const Home({super.key}); + + Future _initializeAndLogin() async { + final settings = UIKitSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..autoEstablishSocketConnection = true + ..appId = CometChatConfig.appId + ..region = CometChatConfig.region + ..authKey = CometChatConfig.authKey + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions + ..callingExtension = CometChatCallingExtension(); // Optional: Include if using Audio/Video Calling + + await CometChatUIKit.init( + uiKitSettings: settings.build(), + onSuccess: (successMessage) { + debugPrint('✅ CometChat Initialized'); + }, + onError: (error) { + debugPrint('❌ CometChat Initialization error: $error'); + }, + ); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _initializeAndLogin(), + builder: (ctx, snap) { + if (snap.connectionState != ConnectionState.done) { + return const Scaffold( + body: SafeArea( + child: Center(child: CircularProgressIndicator()), + ), + ); + } + if (snap.hasError) { + return Scaffold( + body: SafeArea( + child: Center( + child: Text( + 'Error starting app:\n${snap.error}', + textAlign: TextAlign.center, + ), + ), + ), + ); + } + return const LoginScreen(); // Navigate to your login screen + }, + ); + } +} +``` + + + + + +Store your CometChat credentials in a config file to simplify environment management and avoid hardcoding sensitive information. + + + + + +**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. + + *** ### **Step 4: Login to UI Kit** -Once the UI Kit is initialized, authenticate your user using the `login()` method. You’ll receive a `User` object upon success. +Once the UI Kit is initialized, authenticate your user using the `login()` method. You'll receive a `User` object upon success. + + ```dart main.dart CometChatUIKit.login( - "cometchat-uid-1", // Replace with a valid UID + "cometchat-uid-1", // Replace with a valid UID onSuccess: (user) { - debugPrint('CometChat LoggedIn success'); + debugPrint('✅ CometChat LoggedIn success: ${user.name}'); + // Navigate to your chat screen }, onError: (error) { - debugPrint('CometChat LoggedIn error'); + debugPrint('❌ CometChat LoggedIn error: $error'); }, ); ``` + + + +**Test Users:** You can test using any of the following pre-generated users: @@ -196,47 +389,99 @@ You can test using any of the following pre-generated users: * `cometchat-uid-4` * `cometchat-uid-5` -> For more information, refer to the documentation on [Init](/ui-kit/flutter/methods#init) and [Login](/ui-kit/flutter/methods#login-using-auth-key). + + +For more information, refer to the documentation on [Init](/ui-kit/flutter/methods#init) and [Login](/ui-kit/flutter/methods#login-using-auth-key). -#### **Example: Initialization and Login Combined** + +**Example: Initialization and Login Combined** + + + ```dart main.dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; import 'cometchat_config.dart'; -void main() { - UIKitSettings uiKitSettings = (UIKitSettingsBuilder() +void main() => runApp(const MyApp()); + +class MyApp extends StatelessWidget { + const MyApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'CometChat UI Kit', + theme: ThemeData( + colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), + useMaterial3: true, + ), + home: const Home(), + ); + } +} + +class Home extends StatelessWidget { + const Home({super.key}); + + Future _initializeAndLogin() async { + final settings = UIKitSettingsBuilder() ..subscriptionType = CometChatSubscriptionType.allUsers ..autoEstablishSocketConnection = true - ..region = CometChatConfig.region ..appId = CometChatConfig.appId + ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() //Replace this with empty array, if you want to disable all extensions - ..callingExtension = CometChatCallingExtension(); //Optional: Include if you're using Audio/Video Calling - ).build(); - - CometChatUIKit.init( - uiKitSettings: uiKitSettings, - onSuccess: (successMessage) async { - debugPrint('CometChat Initialized'); - - CometChatUIKit.login( - "cometchat-uid-1", - onSuccess: (user) { - debugPrint('CometChat LoggedIn success'); - }, - onError: (error) { - debugPrint('CometChat LoggedIn error'); - }, - ); - }, - onError: (error) { - debugPrint('CometChat Initialization error'); - }, - ); + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension(); + + await CometChatUIKit.init(uiKitSettings: settings.build()); + await CometChatUIKit.login( + 'cometchat-uid-1', + onSuccess: (_) => debugPrint('✅ Login Successful'), + onError: (err) => throw Exception('Login Failed: $err'), + ); + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _initializeAndLogin(), + builder: (ctx, snap) { + if (snap.connectionState != ConnectionState.done) { + return const Scaffold( + body: SafeArea( + child: Center(child: CircularProgressIndicator()), + ), + ); + } + if (snap.hasError) { + return Scaffold( + body: SafeArea( + child: Center( + child: Text( + 'Error starting app:\n${snap.error}', + textAlign: TextAlign.center, + ), + ), + ), + ); + } + return const ConversationsPage(); // Your main chat screen + }, + ); + } } ``` + + + + -> Extract credentials into a separate file (`cometchat_config.dart`) for better maintainability. +Extract credentials into a separate file (`cometchat_config.dart`) for better maintainability. + + *** @@ -252,12 +497,12 @@ Integrate a conversation view that suits your application's **UX requirements**. **Highlights:** -* **Compact Layout** – Uses `Navigator.push()` for mobile-first navigation. -* **One-to-One & Group Chats** – Built-in support for private and group conversations. -* **Real-Time Messaging** – Message list and view auto-refresh with CometChat events. -* **State Persistence** – Session-aware updates across screens and app restarts. -* **Mobile-First UI** – Optimized widgets that adapt to different screen sizes. -* **Extremely Customizable** – Modify styles, themes, and components easily. +* **Compact Layout** – Uses `Navigator.push()` for mobile-first navigation +* **One-to-One & Group Chats** – Built-in support for private and group conversations +* **Real-Time Messaging** – Message list and view auto-refresh with CometChat events +* **State Persistence** – Session-aware updates across screens and app restarts +* **Mobile-First UI** – Optimized widgets that adapt to different screen sizes +* **Extremely Customizable** – Modify styles, themes, and components easily @@ -265,9 +510,9 @@ Integrate a conversation view that suits your application's **UX requirements**. **Use When:** -* You want a **clean navigation experience** for multiple chat sessions. -* Your Flutter app supports **both direct and group messaging**. -* You prefer a **stack-based routing approach** using `Navigator`. +* You want a **clean navigation experience** for multiple chat sessions +* Your Flutter app supports **both direct and group messaging** +* You prefer a **stack-based routing approach** using `Navigator` [Integrate Conversation List + Message View](./flutter-conversation) @@ -279,11 +524,11 @@ Integrate a conversation view that suits your application's **UX requirements**. **Highlights:** -* **Single Screen Chat** – Use `CometChatMessages` widget with preselected user/group. -* **No Conversation List** – Start with just the message screen. -* **Ideal for support & contextual chat** – Ticket-based or user-to-agent communication. -* **Simplified Routing** – Pass user/group as route argument. -* **Real-Time Communication** – Auto-updates messages and statuses. +* **Single Screen Chat** – Use `CometChatMessageList` widget with preselected user/group +* **No Conversation List** – Start with just the message screen +* **Ideal for support & contextual chat** – Ticket-based or user-to-agent communication +* **Simplified Routing** – Pass user/group as route argument +* **Real-Time Communication** – Auto-updates messages and statuses @@ -291,9 +536,9 @@ Integrate a conversation view that suits your application's **UX requirements**. **Use When:** -* Your chat starts **from a specific user or group ID**. -* You want a **clean, focused chat interface**. -* Use case involves **support, onboarding, or one-time messages**. +* Your chat starts **from a specific user or group ID** +* You want a **clean, focused chat interface** +* Use case involves **support, onboarding, or one-time messages** [Integrate One-to-One / Group Chat](./flutter-one-to-one-chat) @@ -305,11 +550,11 @@ Integrate a conversation view that suits your application's **UX requirements**. **Highlights:** -* **Tab Navigation** – Use `BottomNavigationBar` to switch between core features. -* **Independent Screens** – Chats, Calls, Users, and Settings in dedicated widgets. -* **No Sidebar** – True mobile layout using bottom tabs, ideal for smaller devices. -* **Scalable** – Add new tabs like Profile, Notifications, or Help later. -* **Seamless UX** – Syncs chat state across tabs with minimal boilerplate. +* **Tab Navigation** – Use `BottomNavigationBar` to switch between core features +* **Independent Screens** – Chats, Calls, Users, and Settings in dedicated widgets +* **No Sidebar** – True mobile layout using bottom tabs, ideal for smaller devices +* **Scalable** – Add new tabs like Profile, Notifications, or Help later +* **Seamless UX** – Syncs chat state across tabs with minimal boilerplate @@ -317,9 +562,9 @@ Integrate a conversation view that suits your application's **UX requirements**. **Use When:** -* You need a **full-featured chat solution** in one UI. -* Your users require **structured navigation** between modules. -* Use cases like **support apps, business messengers, or social platforms**. +* You need a **full-featured chat solution** in one UI +* Your users require **structured navigation** between modules +* Use cases like **support apps, business messengers, or social platforms** [Integrate Tab-Based Chat](./flutter-tab-based-chat) @@ -327,31 +572,39 @@ Integrate a conversation view that suits your application's **UX requirements**. ## **Build Your Own Chat Experience** -**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app’s design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. +**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app's design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. **Recommended for:** -* Apps that require **a fully customized chat experience**. -* Developers who want to **extend functionalities and modify UI components**. -* Businesses integrating chat seamlessly into **existing platforms**. +* Apps that require **a fully customized chat experience** +* Developers who want to **extend functionalities and modify UI components** +* Businesses integrating chat seamlessly into **existing platforms** **Key Areas to Explore:** -* **[Flutter Sample App](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app)** – Fully functional sample applications to accelerate your development. -* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities. -* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design. -* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding. -* **[Build Your Own UI](/sdk/flutter/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience. +* **[Flutter Sample App](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app)** – Fully functional sample applications to accelerate your development +* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities +* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design +* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding +* **[Build Your Own UI](/sdk/flutter/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience *** ## **Next Steps** -Now that you’ve selected your **chat experience**, proceed to the **integration guide**: - -* **[Integrate Conversation List + Message](/ui-kit/flutter/flutter-conversation)** -* **[Integrate One-to-One Chat](/ui-kit/flutter/flutter-one-to-one-chat)** -* **[Integrate Tab-Based Chat](/ui-kit/flutter/flutter-tab-based-chat)** -* **[Advanced Customizations](/ui-kit/flutter/theme-introduction)** + + + Two-panel layout with conversation list and message view + + + Direct messaging interface for focused conversations + + + Multi-tab experience with chats, calls, users, and groups + + + Adjust colors, fonts, and styles to match your brand + + *** diff --git a/ui-kit/flutter/guide-block-unblock-user.mdx b/ui-kit/flutter/guide-block-unblock-user.mdx index 125c6185f..5a7eed5c4 100644 --- a/ui-kit/flutter/guide-block-unblock-user.mdx +++ b/ui-kit/flutter/guide-block-unblock-user.mdx @@ -1,8 +1,48 @@ --- title: "Implementing Block/Unblock User in Flutter with CometChat UIKit" sidebarTitle: "Block/Unblock User" +description: "Enable users to block and unblock other users for privacy and spam control" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Block a user +await CometChatUIKit.blockUsers([user.uid]); + +// Unblock a user +await CometChatUIKit.unblockUsers([user.uid]); + +// Navigate to user info screen +Navigator.push( + context, + MaterialPageRoute( + builder: (_) => CometChatUserInfo(user: tappedUser), + ), +); + +// Check block status +if (user.blockedByMe) { + // Show unblock button +} else { + // Show block button +} +``` + +**Key Components & Methods:** +- `CometChatUIKit.blockUsers()` → SDK method to block users +- `CometChatUIKit.unblockUsers()` → SDK method to unblock users +- `CometChatUserInfo` → User profile screen +- `User.blockedByMe` → Block status property (SDK) + +**Sample Implementation:** [user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) + + + Enable users to block and unblock other users in your Flutter chat app by integrating CometChat’s `blockUsers` and `unblockUsers` methods with a simple UI. ## Overview @@ -125,22 +165,19 @@ This guide covers only user-to-user blocking. For group moderation (ban or remov | Unblock User | [sample_app/lib/user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | `CometChatUIKit.unblockUsers([...])` | | Group Management | [sample_app/lib/group_info/cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | Group-related actions (not blocking) | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Display and manage user lists + + + View messages with blocked user handling + + + Learn about group moderation features + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/guide-call-log-details.mdx b/ui-kit/flutter/guide-call-log-details.mdx index 14ee8bc67..e7393ed16 100644 --- a/ui-kit/flutter/guide-call-log-details.mdx +++ b/ui-kit/flutter/guide-call-log-details.mdx @@ -1,8 +1,45 @@ --- title: "Managing & Viewing Call Logs in Your Flutter Chat App" sidebarTitle: "Call Logs" +description: "Display call history and detailed call information in your Flutter chat app" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Display call logs list +CometChatCallLogs( + onItemClick: (callLog) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatCallLogDetails(callLog: callLog), + ), + ); + }, +); + +// Show call log details +CometChatCallLogDetails( + callLog: callLog, +); +``` + +**Key Components:** +- `CometChatCallLogs` → [Docs](/ui-kit/flutter/call-logs) +- `CometChatCallLogDetails` → Call details screen +- `CallLog` → Call log data model (SDK) + +**Sample Implementation:** [call_log_details/cometchat_call_log_details.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) + +**Requirements:** Call functionality enabled in CometChat dashboard, microphone/camera permissions + + + Learn how to integrate and customize CometChat’s `CometChatCallLogs` and `CometChatCallLogDetails` components to display call history and detailed call information in your Flutter chat app. ## Overview @@ -116,22 +153,19 @@ CometChatCallLogDetails( | Display call logs | `CometChatCallLogs` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | | Show call details | `CometChatCallLogDetails(callLog)` | [`call_log_details/cometchat_call_log_details.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Learn more about the Call Logs component + + + Explore all calling capabilities + + + Add call buttons to your chat interface + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/guide-group-chat.mdx b/ui-kit/flutter/guide-group-chat.mdx index 958fdd469..cdc640522 100644 --- a/ui-kit/flutter/guide-group-chat.mdx +++ b/ui-kit/flutter/guide-group-chat.mdx @@ -1,8 +1,55 @@ --- title: "Managing Groups in Flutter UI Kit" sidebarTitle: "Groups" +description: "Create groups, manage members, assign roles, and transfer ownership in your Flutter chat app" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Create a group +await CometChat.createGroup( + group: Group( + guid: groupId, + name: groupName, + type: groupType, + password: groupPassword, + ), +); + +// Join a group +await CometChat.joinGroup(guid: groupId, groupType: groupType, password: password); + +// Add members +CometChatAddMembers(group: group); + +// Ban/unban members +CometChatBannedMembers(group: group); + +// Change member scope +CometChatChangeScope(group: group, user: user); + +// Transfer ownership +CometChatTransferOwnership(group: group); +``` + +**Key Components:** +- `CometChatGroups` → [Docs](/ui-kit/flutter/groups) +- `CometChatCreateGroup` → Group creation UI +- `CometChatGroupInfo` → Group info screen +- `CometChatAddMembers` → Add members UI +- `CometChatBannedMembers` → Banned members management +- `CometChatTransferOwnership` → Ownership transfer UI +- `JoinProtectedGroupUtils` → Password group join utility (sample app) + +**Sample Implementation:** [group_info/cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) + + + Learn how to create groups, join public/password groups, manage members, ban users, update roles, and transfer group ownership using CometChat UIKit for Flutter. ## Overview @@ -203,18 +250,19 @@ CometChatTransferOwnership( | Change scope | `CometChatChangeScope` | `group_info/cometchat_group_info.dart` | | Transfer ownership | `CometChatTransferOwnership` | `transfer_ownership/cometchat_transfer_ownership.dart` | -## Next Steps & Further Reading - - - -Explore the working implementation in our official sample app. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - -Get the full UI Kit source for deeper customization. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - +## Next Steps + + + + Learn more about the Groups component + + + Display and manage group members + + + View group conversations + + + Explore other implementation guides + diff --git a/ui-kit/flutter/guide-message-agentic-flow.mdx b/ui-kit/flutter/guide-message-agentic-flow.mdx index acbb37885..545f64be1 100644 --- a/ui-kit/flutter/guide-message-agentic-flow.mdx +++ b/ui-kit/flutter/guide-message-agentic-flow.mdx @@ -1,8 +1,57 @@ --- title: "AI Agent Integration" sidebarTitle: "AI Agent Integration" +description: "Integrate AI agents with chat history, contextual responses, and seamless handoffs in your Flutter app" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Check if user is an AI agent +bool isUserAgentic() { + return widget.user?.role == AIConstants.aiRole; +} + +// AI Assistant chat screen +AIAssistantChatScreen( + user: aiUser, + group: group, + parentMessage: message, + isHistory: true, +); + +// AI chat history +CometChatAIAssistantChatHistory( + user: widget.user, + group: widget.group, + onNewChatButtonClicked: () => onNewChatClicked(true), + onMessageClicked: (message) => navigateToThread(message), +); + +// Custom AI bubble styling +CometChatAiAssistantBubbleStyle( + backgroundColor: Colors.transparent, + border: Border.all(color: Colors.blueAccent), + textColor: Color(0xFF141414), +); +``` + +**Key Components:** +- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) +- `CometChatMessageComposer` → [Docs](/ui-kit/flutter/message-composer) +- `CometChatMessageHeader` → [Docs](/ui-kit/flutter/message-header) +- `CometChatAIAssistantChatHistory` → [Docs](/ui-kit/flutter/ai-assistant-chat-history) +- `CometChatAiAssistantBubbleStyle` → AI bubble styling +- `AIConstants.aiRole` → AI role constant + +**Sample Implementation:** Custom AI Assistant chat screen (see guide for full implementation) + + + Enable intelligent conversational AI capabilities in your Android app using CometChat UIKit v5 with AI Agent integration: - **AI Assistant Chat History** @@ -396,4 +445,23 @@ class MyApp extends StatelessWidget { | Feature | Implementation | UI Component | |:-----------------------|:-------------------------------------------- |:------------------------| | AI Chat | `AIAssistantChatScreen` | Full chat screen | -| Chat History | `CometChatAIAssistantChatHistory` | Chat history screen | \ No newline at end of file +| Chat History | `CometChatAIAssistantChatHistory` | Chat history screen | + +--- + +## Next Steps + + + + Explore all AI-powered features + + + Learn about message display and management + + + Compose messages with AI assistance + + + Explore other implementation guides + + \ No newline at end of file diff --git a/ui-kit/flutter/guide-message-privately.mdx b/ui-kit/flutter/guide-message-privately.mdx index ed8f83321..245dbbf32 100644 --- a/ui-kit/flutter/guide-message-privately.mdx +++ b/ui-kit/flutter/guide-message-privately.mdx @@ -1,8 +1,50 @@ --- title: "Message a User Privately from a Group Chat" sidebarTitle: "Message Privately" +description: "Initiate private one-on-one chats with group members directly from group chat" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Navigate to user info from group chat +IconButton( + icon: Icon(Icons.info_outline), + onPressed: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatUserInfo(user: user), + ), + ); + }, +); + +// Start private chat with user +ElevatedButton( + onPressed: () { + PageManager().navigateToMessages( + context: context, + user: user, + ); + }, + child: Text('Message'), +); +``` + +**Key Components:** +- `CometChatUserInfo` → User profile screen +- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) +- `PageManager` → Navigation utility (sample app) + +**Sample Implementation:** [user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) + + + Learn how to initiate a private one-on-one chat with a group member directly from a group chat screen. ## Overview @@ -103,22 +145,19 @@ ElevatedButton( | Message user | `PageManager.navigateToMessages` | [`lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | | Access from group | Avatar/IconButton | [`lib/messages.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Display and manage group lists + + + View and manage group members + + + Display messages in private chats + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/guide-new-chat.mdx b/ui-kit/flutter/guide-new-chat.mdx index 8ec4b682f..c337f3fce 100644 --- a/ui-kit/flutter/guide-new-chat.mdx +++ b/ui-kit/flutter/guide-new-chat.mdx @@ -1,8 +1,52 @@ --- title: "New Chat / Create Conversation in Your Flutter Chat App" sidebarTitle: "New Chat" +description: "Enable users to start one-on-one or group chats with a searchable contact list" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Add avatar menu with "Create Conversation" option +PopupMenuButton( + icon: CometChatAvatar( + image: CometChatUIKit.loggedInUser?.avatar, + name: CometChatUIKit.loggedInUser?.name, + ), + itemBuilder: (context) => [ + PopupMenuItem(value: '/Create', child: Text("Create Conversation")), + ], + onSelected: (value) { + if (value == '/Create') { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => CometChatContacts()), + ); + } + }, +); + +// Handle user/group selection +CometChatUsers( + onItemTap: (context, user) => PageManager.navigateToMessages(context: context, user: user), +); +``` + +**Key Components:** +- `CometChatAvatar` → Avatar display widget +- `CometChatContacts` → Contact selection screen +- `CometChatUsers` → [Docs](/ui-kit/flutter/users) +- `CometChatGroups` → [Docs](/ui-kit/flutter/groups) +- `CometChatContactsController` → Tab switching controller (sample app) + +**Sample Implementation:** [contacts/cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) + + + Enable users to start one-on-one or group chats by integrating CometChat’s avatar menu and `CometChatContacts` screen, providing a seamless flow from the dashboard to a conversation. ## Overview @@ -146,22 +190,19 @@ void _onItemTap({required BuildContext context, User? user, Group? group}) { | Handle selection | `_onItemTap` | [`page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | | Navigate to chat | `PageManager.navigateToMessages` | [`page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Display and search user lists + + + Display and manage group lists + + + View and manage conversation history + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/guide-overview.mdx b/ui-kit/flutter/guide-overview.mdx index 609ddfba0..896324117 100644 --- a/ui-kit/flutter/guide-overview.mdx +++ b/ui-kit/flutter/guide-overview.mdx @@ -1,8 +1,30 @@ --- -title: "Overview" +title: "Guides Overview" sidebarTitle: "Overview" +description: "Task-oriented feature guides for implementing specific capabilities in the Flutter UI Kit" --- -> This page indexes focused, task‑oriented feature guides for the Flutter UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UI kit components. + +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +Available implementation guides for Flutter UI Kit: + +**Feature Guides:** +- [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) → `CometChatThreadedMessageList` +- [Block/Unblock User](/ui-kit/flutter/guide-block-unblock-user) → `CometChatUIKit.blockUsers()` +- [New Chat](/ui-kit/flutter/guide-new-chat) → `CometChatContacts` +- [Message Privately](/ui-kit/flutter/guide-message-privately) → `CometChatUserInfo` +- [Group Management](/ui-kit/flutter/guide-group-chat) → `CometChatGroups` +- [Call Log Details](/ui-kit/flutter/guide-call-log-details) → `CometChatCallLogs` +- [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) → `CometChatAIAssistantChatHistory` + +**Sample App:** [GitHub Repository](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) + +Each guide provides end-to-end implementation with code examples and component references. + + +This page indexes focused, task‑oriented feature guides for the Flutter UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UI kit components. ## When to Use These Guides @@ -18,6 +40,25 @@ Use these after finishing [Getting Started](/ui-kit/flutter/getting-started) and | [Message Privately](/ui-kit/flutter/guide-message-privately) | Start a direct 1:1 chat from a profile or list; optionally send an initial message to surface the conversation. | | [New Chat](/ui-kit/flutter/guide-new-chat) | Offer a unified discovery screen for users & groups and launch new chats quickly. | | [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) | Enable threaded replies: open parent message context, browse replies, and compose within a focused thread. | -| [Call Log Details](/ui-kit/flutter/guide-call-log-details) | Provide a post‑call details screen with metadata, participants, history, and recordings for audit & support. | +| [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) | Integrate AI agents with chat history, contextual responses, and seamless handoffs. | Need another guide? Request one via the [Developer Community](http://community.cometchat.com/) or Support. + +--- + +## Next Steps + + + + Set up the Flutter UI Kit in your project + + + Explore all available UI components + + + Learn about core chat features + + + View complete working examples + + diff --git a/ui-kit/flutter/guide-threaded-messages.mdx b/ui-kit/flutter/guide-threaded-messages.mdx index 7e140d86a..510f2dc63 100644 --- a/ui-kit/flutter/guide-threaded-messages.mdx +++ b/ui-kit/flutter/guide-threaded-messages.mdx @@ -1,8 +1,49 @@ --- title: "Threaded Messages" sidebarTitle: "Threaded Messages" +description: "Enable threaded replies in your Flutter chat app with focused sub-conversations" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Enable thread replies in message list +CometChatMessageList( + onThreadRepliesClick: (BaseMessage message) { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => CometChatThread(parentMessage: message), + ), + ); + }, +); + +// Display threaded messages +CometChatThreadedMessageList( + parentMessageId: parentMessage.id, +); + +// Send threaded reply +CometChatMessageComposer( + parentMessageId: parentMessage.id, +); +``` + +**Key Components:** +- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) +- `CometChatThreadedMessageList` → Displays threaded messages +- `CometChatMessageComposer` → [Docs](/ui-kit/flutter/message-composer) +- `CometChatThreadedHeader` → [Docs](/ui-kit/flutter/threaded-messages-header) + +**Sample Implementation:** [thread_screen/cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) + + + Enhance your Flutter chat app with threaded messaging by integrating CometChat’s `CometChatThreadedMessageList` and `CometChatMessageList` components to reply to messages in threads and view focused sub-conversations seamlessly. ## Overview @@ -153,22 +194,19 @@ Ensures only relevant threaded messages are shown. | Send threaded message | `CometChatMessageComposer(parentMessageId)` | | Fetch thread replies | `MessagesRequestBuilder.setParentMessageId` | -## Next Steps & Further Reading - - - - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - - - - - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) - - +## Next Steps + + + + Display and manage conversation messages + + + Compose and send messages with threading support + + + Display thread context and parent message + + + Explore other implementation guides + \ No newline at end of file diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index e1d04635d..ea11a9337 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -1,8 +1,39 @@ --- title: "CometChat UI Kit For Flutter" sidebarTitle: "Overview" +description: "Prebuilt Flutter widgets for chat, calling, and messaging with modular, customizable components for iOS and Android" --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```dart +// Install +flutter pub add cometchat_chat_uikit + +// Initialize (run once at app start) +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..appId = "YOUR_APP_ID" + ..region = "YOUR_REGION" + ..subscriptionType = CometChatSubscriptionType.allUsers +).build(); +CometChatUIKit.init(uiKitSettings: uiKitSettings); + +// Login +CometChatUIKit.login("UID"); + +// Show conversations +CometChatConversations() + +// Show messages +CometChatMessageList(user: user) // or group: group +``` + +**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 + + The **CometChat UI Kit** for Flutter is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI widgets** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. *** @@ -60,12 +91,91 @@ To begin, please follow the [Getting Started](/ui-kit/flutter/getting-started) g *** -## **Next Steps for Developers** +## **Key Features** + +### **Comprehensive Widget Library** + +The UI Kit includes a complete set of widgets for building chat experiences: + +* **CometChatConversations** – Display recent conversations with users and groups +* **CometChatMessageList** – Full-featured messaging interface with real-time updates +* **CometChatMessageComposer** – Input field for sending text, media, and attachments +* **CometChatMessageHeader** – Conversation header with user/group info and actions +* **CometChatUsers** – Browse and search users +* **CometChatGroups** – Manage and join groups +* **CometChatGroupMembers** – View and manage group participants +* **Calling Components** – Voice and video calling widgets + +### **Built-in Chat Logic** + +Each widget comes with integrated CometChat SDK functionality: + +* Real-time message delivery and updates +* Typing indicators and read receipts +* User presence and status +* Message reactions and threading +* File and media sharing +* Push notifications support + +### **Extensive Customization** + +Tailor the UI to match your brand: + +* **Theming** – Customize colors, fonts, and spacing +* **Styling** – Override default styles for any component +* **Templates** – Create custom message bubble layouts +* **Formatters** – Add mentions, shortcuts, and URL previews +* **Configurations** – Control feature availability and behavior + +*** + +## **Architecture** + +The CometChat UI Kit for Flutter is built on top of the [CometChat Flutter SDK](/sdk/flutter/overview) and follows a modular architecture: + +``` +Your Flutter App + ↓ +CometChat UI Kit (Widgets) + ↓ +CometChat Flutter SDK (Core Chat Logic) + ↓ +CometChat Platform +``` + +This layered approach means: + +* **Widgets handle UI** – Rendering, user interactions, animations +* **SDK handles logic** – Message delivery, real-time events, data management +* **Platform handles infrastructure** – Scalability, reliability, security + +*** + +## **Supported Platforms** + +The Flutter UI Kit works seamlessly across: -1. **Learn the Basics** – [Key Concepts](/fundamentals/key-concepts). -2. **Follow the Setup Guide** – [Flutter Integration Guide](/ui-kit/flutter/getting-started) -3. **Customize UI** – Adjust styles, themes, and widgets. -4. **Test & Deploy** – Run tests and launch your chat app. +* **iOS** – iPhone and iPad (iOS 12.0+) +* **Android** – Phones and tablets (API level 21+) + +*** + +## **Next Steps** + + + + Install the UI Kit and build your first chat screen + + + Understand CometChat's core concepts and terminology + + + Explore all available widgets and their capabilities + + + Customize colors, fonts, and styles to match your brand + + *** @@ -73,27 +183,35 @@ To begin, please follow the [Getting Started](/ui-kit/flutter/getting-started) g Explore these essential resources to gain a deeper understanding of **CometChat UI Kits** and streamline your integration process. - - + + Fully functional sample applications to accelerate your development. -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) +View on GitHub - + Access the complete UI Kit source code on GitHub. -[View on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) +View on GitHub + + + + + +UI design resources for customization and prototyping. + +View on Figma *** -## **💡 Need Help?** +## **Need Help?** If you need assistance, check out: From ae7404bfd11481fdfdd5b7327d15154242146d6a Mon Sep 17 00:00:00 2001 From: Anshuman-cometchat Date: Thu, 12 Feb 2026 16:01:17 +0530 Subject: [PATCH 007/106] fix : removed code snippet --- ui-kit/flutter/extensions.mdx | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/ui-kit/flutter/extensions.mdx b/ui-kit/flutter/extensions.mdx index 24d3cc1d9..6a8a01c01 100644 --- a/ui-kit/flutter/extensions.mdx +++ b/ui-kit/flutter/extensions.mdx @@ -152,19 +152,6 @@ await CometChatUIKit.init(uiKitSettings: uiKitSettings); -To disable all extensions, pass an empty array: - - - -```dart -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "YOUR_APP_ID" - ..region = "YOUR_REGION" - ..extensions = [] // Disable all extensions -).build(); -``` - - *** From 5e2161b1e77d483bd5a55acbb3900534727176e5 Mon Sep 17 00:00:00 2001 From: Aditya Date: Thu, 12 Feb 2026 16:11:55 +0530 Subject: [PATCH 008/106] modified block/unblock , call-log guide, group-chat guide, group-ownership-guide --- ui-kit/ios/guide-block-unblock-user.mdx | 4 - ui-kit/ios/guide-call-log-details.mdx | 262 +++++++++----- ui-kit/ios/guide-group-chat.mdx | 390 ++++++++++++++++----- ui-kit/ios/guide-group-ownership.mdx | 448 ++++++++++++++++++------ 4 files changed, 812 insertions(+), 292 deletions(-) diff --git a/ui-kit/ios/guide-block-unblock-user.mdx b/ui-kit/ios/guide-block-unblock-user.mdx index 5d99c4cf4..5827a39f8 100644 --- a/ui-kit/ios/guide-block-unblock-user.mdx +++ b/ui-kit/ios/guide-block-unblock-user.mdx @@ -6,10 +6,6 @@ description: "Implement user blocking and profile management in your iOS app" Build a user profile screen with avatar display, messaging, audio/video calls, and block/unblock functionality using CometChat UIKit. - - - - ## Prerequisites Before implementing this feature, ensure you have: diff --git a/ui-kit/ios/guide-call-log-details.mdx b/ui-kit/ios/guide-call-log-details.mdx index 89cd141c0..77bf8c52f 100644 --- a/ui-kit/ios/guide-call-log-details.mdx +++ b/ui-kit/ios/guide-call-log-details.mdx @@ -1,145 +1,241 @@ --- -title: "CometChat UIKit iOS — Call Log Details" +title: "Call Log Details" sidebarTitle: "Call Log Details" +description: "Display call history, participants, and recordings in your iOS app" --- -Learn how to integrate and customize CometChat’s call log components to display call history, participant details, and call recordings in your iOS UIKit chat app. +Learn how to integrate and customize CometChat's call log components to display call history, participant details, and call recordings in your iOS app. ## Overview -The `CallLogDetailsVC` module provides a tabbed interface to view details of past calls: +The `CallLogDetailsVC` module provides a tabbed interface for viewing details of past calls: -- **History:** Chronological join/leave events. -- **Participants:** Users who joined the call. -- **Recordings:** Links to cloud-hosted call recordings. +- **History** — Chronological join/leave events with timestamps +- **Participants** — Users who joined the call +- **Recordings** — Links to cloud-hosted call recordings -This ensures transparency and auditability for both users and admins. +This ensures transparency and auditability for both users and administrators. ## Prerequisites -- A UIKit-based iOS project. -- **CometChatSDK**, **CometChatCallsSDK**, and **CometChatUIKitSwift** integrated. -- Active internet connection. -- A valid, logged-in CometChat user. +Before implementing call log details, ensure you have: + +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- CometChat UIKit v5+ installed +- CometChatCallsSDK integrated +- User logged in with `CometChatUIKit.login()` +- Active internet connection ## Components -| Component | Role | -|-----------------------------|----------------------------------------------------------------------------------------| -| `CallLogDetailsVC` | Main container with segmented control and page view. | -| `CallLogParticipantsVC` | Displays a list of users who participated in the call. | -| `CallLogHistoryVC` | Shows join/leave history entries with timestamps and statuses. | -| `CallLogRecordingsVC` | Lists call recordings with playback actions. | -| `CallLogDetailsHeaderView` | Header view showing call metadata (title, status, duration). | -| `CallLogUserCell` | UITableViewCell for participants, history, and recordings entries. | -| `CallLogDetailsModel` | Data model formatting participants, history, and recordings data. | -| `CallLogViewModel` | Fetches and distributes call log data to the UI components. | +| Component | Description | +|-----------|-------------| +| `CallLogDetailsVC` | Main container with segmented control and page view | +| `CallLogParticipantsVC` | Displays a list of users who participated in the call | +| `CallLogHistoryVC` | Shows join/leave history entries with timestamps and statuses | +| `CallLogRecordingsVC` | Lists call recordings with playback actions | +| `CallLogDetailsHeaderView` | Header view showing call metadata (title, status, duration) | +| `CallLogUserCell` | UITableViewCell for participants, history, and recordings entries | +| `CallLogDetailsModel` | Data model formatting participants, history, and recordings data | +| `CallLogViewModel` | Fetches and distributes call log data to the UI components | ## Integration Steps -### 1. Present Call Log Details Screen +### Step 1: Present Call Log Details Screen -Show the call log interface for a selected call. +Show the call log interface for a selected call: ```swift -let detailsVC = CallLogDetailsVC(call: call) -navigationController?.pushViewController(detailsVC, animated: true) +import UIKit +import CometChatSDK +import CometChatCallsSDK + +class CallLogsViewController: UIViewController { + + func showCallDetails(for call: CallLog) { + // Initialize the call log details view controller + let detailsVC = CallLogDetailsVC(call: call) + + // Push onto navigation stack + navigationController?.pushViewController(detailsVC, animated: true) + } +} ``` -**File reference:** -[`CallLogDetailsVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/CallLogDetailsVC.swift) +This bundles history, participants, and recordings into a single UI flow. -Bundles history, participants, and recordings into a single UI flow. +**File reference:** [`CallLogDetailsVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/CallLogDetailsVC.swift) -### 2. Display Participants List +### Step 2: Display Participants List -Populate the participants tab with the call’s members. +Populate the participants tab with the call's members: ```swift -participantsTableView.reloadData() +import UIKit +import CometChatSDK + +class CallLogParticipantsVC: UIViewController { + + var participants: [Participant] = [] + @IBOutlet weak var participantsTableView: UITableView! + + func loadParticipants() { + // Fetch participants from call log data + // ... + + // Reload table view to display participants + participantsTableView.reloadData() + } +} ``` -**File reference:** -[`CallLogParticipantsVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20Participants/CallLogParticipantsVC.swift) +This provides an audit trail of who was present in the call. -Audits who was present in the call. +**File reference:** [`CallLogParticipantsVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20Participants/CallLogParticipantsVC.swift) -### 3. Show Call History +### Step 3: Show Call History -Render join/leave activities in chronological order. +Render join/leave activities in chronological order: ```swift -history.append(CallHistoryEntry(...)) -tableView.reloadData() +import UIKit + +class CallLogHistoryVC: UIViewController { + + var history: [CallHistoryEntry] = [] + @IBOutlet weak var tableView: UITableView! + + func addHistoryEntry(user: String, action: String, timestamp: Date) { + // Create and append new history entry + let entry = CallHistoryEntry(user: user, action: action, timestamp: timestamp) + history.append(entry) + + // Refresh the table view + tableView.reloadData() + } +} ``` -**File references:** -- [`CallHistoyTVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20History%20/CallHistoyTVC.swift) -- [`CallLogHistoryVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20History%20/CallLogHistoryVC.swift) +This tracks user join/leave times for transparency. -Tracks user join/leave times for transparency. +**File references:** +- [`CallHistoyTVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20History%20/CallHistoyTVC.swift) +- [`CallLogHistoryVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20History%20/CallLogHistoryVC.swift) -### 4. List and Play Recordings +### Step 4: List and Play Recordings -Provide playback links for any recorded calls. +Provide playback links for any recorded calls: ```swift -UIApplication.shared.open(url) +import UIKit + +class CallLogRecordingsVC: UIViewController { + + func playRecording(url: URL) { + // Open recording URL in default browser/player + UIApplication.shared.open(url) + } +} ``` -**File references:** -- [`CallLogRecordingsVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20Recording%20/CallLogRecordingsVC.swift) -- [`CallRecordingTVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20Recording%20/CallRecordingTVC.swift) +This enables administrators and users to review call content (if recording is enabled). -Enables admins and users to review call content (if recording enabled). +**File references:** +- [`CallLogRecordingsVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20Recording%20/CallLogRecordingsVC.swift) +- [`CallRecordingTVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details/Call%20Recording%20/CallRecordingTVC.swift) ## Customization Options -- **Styling:** Customize colors, fonts, and spacing via `CometChatTheme`, `CometChatTypography`, and `CometChatSpacing` in `CallLogUserCell` and `CallLogDetailsHeaderView`. -- **Filters:** Use `CallLogViewModel` to filter by call type (incoming, outgoing, missed). -- **Empty States:** Implement an `EmptyStateView` in `CallLogHistoryVC` for no-history scenarios. +### Styling -## Filtering & Edge Cases +Customize colors, fonts, and spacing using CometChat's theming system: -- **No Call Logs:** Show a custom empty state instead of a blank table. -- **Pagination:** Add lazy loading in `scrollViewDidScroll` of `CallLogHistoryVC` to fetch more entries. -- **Blocked Users:** In `CallLogParticipantsVC`, disable profile navigation if the user is blocked. +```swift +import CometChatUIKitSwift -## Error Handling +// Apply custom theme to call log components +let theme = CometChatTheme() +theme.palette.primary = UIColor.systemBlue -- **Network/API Errors:** Display `UIAlertController` on fetch failures; expose error via `CallLogViewModel` delegate. -- **Retry Mechanism:** Add pull-to-refresh or a retry button in `CallLogDetailsVC`. -- **Recording Unavailable:** Gracefully disable playback links if URL is missing. +// Apply typography +let typography = CometChatTypography() +typography.heading = UIFont.systemFont(ofSize: 18, weight: .bold) -## Optional Notes +// Apply spacing +let spacing = CometChatSpacing() +spacing.padding = 16 +``` -- **Group Calls vs 1:1 Calls:** Customize `CallLogParticipantsVC` display based on call type and participant roles. -- **Metadata Display:** Use `CallLogDetailsHeaderView` to show titles, call duration, and status icons. +### Filters -## Feature Matrix +Use `CallLogViewModel` to filter by call type: + +```swift +// Filter by call type +viewModel.filterByType(.incoming) // Show only incoming calls +viewModel.filterByType(.outgoing) // Show only outgoing calls +viewModel.filterByType(.missed) // Show only missed calls +``` + +### Empty States + +Implement an `EmptyStateView` in `CallLogHistoryVC` for no-history scenarios: + +```swift +func showEmptyState() { + let emptyView = UILabel() + emptyView.text = "No call history available" + emptyView.textAlignment = .center + emptyView.textColor = .secondaryLabel + tableView.backgroundView = emptyView +} +``` -| Feature | Component / Method | File(s) | -|:-----------------------------|:----------------------------------|:--------------------------------------------------------------------------------------------------| -| Show call log details screen | `CallLogDetailsVC(call:)` | `CallLogDetailsVC.swift` | -| Display participants | `CallLogParticipantsVC` | `CallLogParticipantsVC.swift` | -| Display history entries | `CallLogHistoryVC` | `CallHistoyTVC.swift`, `CallLogHistoryVC.swift` | -| List recordings | `CallLogRecordingsVC` | `CallLogRecordingsVC.swift`, `CallRecordingTVC.swift` | -| Header metadata | `CallLogDetailsHeaderView` | `CallLogDetailsHeaderView.swift` | -| Data handling | `CallLogDetailsModel` | `CallLogDetailsModel.swift` | -| Data fetching & distribution | `CallLogViewModel` | `CallLogViewModel.swift` | +## Edge Cases - +| Scenario | Handling | +|----------|----------| +| No call logs | Show a custom empty state instead of a blank table | +| Large history | Add lazy loading in `scrollViewDidScroll` to fetch more entries | +| Blocked users | Disable profile navigation in `CallLogParticipantsVC` if the user is blocked | +| Missing recording URL | Gracefully disable playback links | - -Explore a full sample implementation: -[GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) +## Error Handling - +| Error Type | Solution | +|------------|----------| +| Network/API errors | Display `UIAlertController` on fetch failures; expose error via `CallLogViewModel` delegate | +| Retry mechanism | Add pull-to-refresh or a retry button in `CallLogDetailsVC` | +| Recording unavailable | Gracefully disable playback links if URL is missing | - -Review the call log components in the UIKit library: -[GitHub → Call Log Components](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp/View%20Controllers/CometChat%20Components/Call%20Log%20Details) +## Additional Notes - +- **Group Calls vs 1:1 Calls** — Customize `CallLogParticipantsVC` display based on call type and participant roles +- **Metadata Display** — Use `CallLogDetailsHeaderView` to show titles, call duration, and status icons + +## Feature Matrix - \ No newline at end of file +| Feature | Component / Method | File(s) | +|---------|-------------------|---------| +| Show call log details screen | `CallLogDetailsVC(call:)` | `CallLogDetailsVC.swift` | +| Display participants | `CallLogParticipantsVC` | `CallLogParticipantsVC.swift` | +| Display history entries | `CallLogHistoryVC` | `CallHistoyTVC.swift`, `CallLogHistoryVC.swift` | +| List recordings | `CallLogRecordingsVC` | `CallLogRecordingsVC.swift`, `CallRecordingTVC.swift` | +| Header metadata | `CallLogDetailsHeaderView` | `CallLogDetailsHeaderView.swift` | +| Data handling | `CallLogDetailsModel` | `CallLogDetailsModel.swift` | +| Data fetching & distribution | `CallLogViewModel` | `CallLogViewModel.swift` | + +## Related Components + +- [Call Logs](/ui-kit/ios/call-logs) - Display call log list +- [Call Features](/ui-kit/ios/call-features) - Overview of calling capabilities +- [Ongoing Call](/ui-kit/ios/ongoing-call) - Active call interface + + + + Explore a full sample implementation + + + Review the call log components in the UIKit library + + diff --git a/ui-kit/ios/guide-group-chat.mdx b/ui-kit/ios/guide-group-chat.mdx index dd71cfe6d..4d26f85ab 100644 --- a/ui-kit/ios/guide-group-chat.mdx +++ b/ui-kit/ios/guide-group-chat.mdx @@ -1,6 +1,7 @@ --- title: "Group Details" sidebarTitle: "Group Details" +description: "Display and manage group information in your iOS app" --- Provide a detailed view for CometChat groups in your iOS app, enabling users to see group info, join/leave, manage members, and respond to real-time group events. @@ -9,113 +10,230 @@ Provide a detailed view for CometChat groups in your iOS app, enabling users to `GroupDetailsViewController` displays comprehensive group information and actions: -- **Group Info:** Name, icon, description, and member count. -- **Actions:** Join/Leave/Delete group. -- **Member Management:** View members, add members, view banned members. -- **Real-Time Updates:** Reflects joins, leaves, bans, and ownership changes. +- **Group Info** — Name, icon, description, and member count +- **Actions** — Join, leave, or delete group +- **Member Management** — View members, add members, view banned members +- **Real-Time Updates** — Reflects joins, leaves, bans, and ownership changes ## Prerequisites -- A UIKit-based iOS project. -- CometChat UIKit for iOS v5 installed via CocoaPods or Swift Package Manager. -- Valid CometChat **App ID**, **Region**, and **Auth Key**. -- User logged in with `CometChat.login()`. -- Navigation stack (`UINavigationController`) configured. +Before implementing group details, ensure you have: + +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- CometChat UIKit v5+ installed via CocoaPods or Swift Package Manager +- Valid CometChat App ID, Region, and Auth Key +- User logged in with `CometChatUIKit.login()` +- Navigation controller (`UINavigationController`) configured ## Components -| Component | Role | -|:------------------------------|:----------------------------------------------------------------| -| `CometChatGroup` | Renders group avatar, name, and metadata. | -| `GroupActionView` | Custom view for action buttons (view/add/banned members). | -| `CometChatMessagesViewController` | Opens group chat interface when “Chat” is tapped. | -| `CometChat.joinGroup()` | Joins public or password-protected groups. | -| `CometChat.leaveGroup()` | Leaves the current group. | -| `CometChat.deleteGroup()` | Deletes and exits the group (owners only). | -| `CometChatGroupMembers` | Lists current group members. | -| `CometChatGroupDelegate` | Receives real-time group events. | +| Component | Description | +|-----------|-------------| +| `CometChatGroup` | Renders group avatar, name, and metadata | +| `GroupActionView` | Custom view for action buttons (view/add/banned members) | +| `CometChatMessagesViewController` | Opens group chat interface when "Chat" is tapped | +| `CometChat.joinGroup()` | Joins public or password-protected groups | +| `CometChat.leaveGroup()` | Leaves the current group | +| `CometChat.deleteGroup()` | Deletes and exits the group (owners only) | +| `CometChatGroupMembers` | Lists current group members | +| `CometChatGroupDelegate` | Receives real-time group events | ## Integration Steps -### 1. Presenting the Group Details Screen +### Step 1: Present the Group Details Screen -Push `GroupDetailsViewController` for a selected group. +Push `GroupDetailsViewController` for a selected group: ```swift import UIKit import CometChatSDK -func showGroupDetails(for group: Group) { - let detailsVC = GroupDetailsViewController() - detailsVC.group = group - navigationController?.pushViewController(detailsVC, animated: true) +class GroupListViewController: UIViewController { + + func showGroupDetails(for group: Group) { + // Initialize the group details view controller + let detailsVC = GroupDetailsViewController() + detailsVC.group = group + + // Push onto navigation stack + navigationController?.pushViewController(detailsVC, animated: true) + } } ``` -**File reference:** -[`HomeScreenViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/HomeScreenViewController.swift) +This initializes and presents the details UI with the correct group context. -Initializes and presents the details UI with the correct group context. +**File reference:** [`HomeScreenViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/HomeScreenViewController.swift) -### 2. Setting Up the UI +### Step 2: Set Up the UI -Configure scroll view, header, and action views. +Configure scroll view, header, and action views: ```swift -override public func viewDidLoad() { - super.viewDidLoad() - connect() - view.backgroundColor = CometChatTheme.backgroundColor01 - setupScrollView() - setupLayout() - addButtonActions() +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class GroupDetailsViewController: UIViewController { + + var group: Group? + + override public func viewDidLoad() { + super.viewDidLoad() + + // Connect to group event listeners + connect() + + // Apply theme + view.backgroundColor = CometChatTheme.backgroundColor01 + + // Set up UI components + setupScrollView() + setupLayout() + addButtonActions() + } + + private func setupScrollView() { + // Configure scroll view for content + } + + private func setupLayout() { + // Arrange header, info, and action views + } } ``` -**File reference:** -[`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) +This lays out the UI components and registers for group events. -Lays out the UI components and registers for group events. +**File reference:** [`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) -### 3. Enabling Group Action Buttons +### Step 3: Enable Group Action Buttons -Wire up view/add/banned members actions. +Wire up view/add/banned members actions: ```swift +// Action views for member management +private let viewMembersView = GroupActionView() +private let addMembersView = GroupActionView() +private let bannedMembersView = GroupActionView() + public func addButtonActions() { - viewMembersView.onActionButtonTapped = { self.viewMembers() } - addMembersView.onActionButtonTapped = { self.addMembers() } - bannedMembersView.onActionButtonTapped = { self.banMembers() } + // View current group members + viewMembersView.onActionButtonTapped = { [weak self] in + self?.viewMembers() + } + + // Add new members to the group + addMembersView.onActionButtonTapped = { [weak self] in + self?.addMembers() + } + + // View banned members + bannedMembersView.onActionButtonTapped = { [weak self] in + self?.banMembers() + } +} + +private func viewMembers() { + guard let group = group else { return } + let membersVC = CometChatGroupMembers() + membersVC.set(group: group) + navigationController?.pushViewController(membersVC, animated: true) +} + +private func addMembers() { + // Present add members interface +} + +private func banMembers() { + // Present banned members list } ``` -**File reference:** -[`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) +This enables user interaction for member management. -Enables user interaction for member management. +**File reference:** [`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) -### 4. Handling Leave and Delete Actions +### Step 4: Handle Leave and Delete Actions -Provide ownership-aware leave/delete flows. +Provide ownership-aware leave/delete flows: ```swift -@objc func showLeaveGroupAlert() { /* ownership transfer or leave logic */ } +@objc func showLeaveGroupAlert() { + guard let group = group else { return } + + let alert = UIAlertController( + title: "Leave Group", + message: "Are you sure you want to leave this group?", + preferredStyle: .alert + ) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + alert.addAction(UIAlertAction(title: "Leave", style: .destructive) { [weak self] _ in + self?.leaveGroup() + }) + + present(alert, animated: true) +} + +@objc func showDeleteGroupAlert() { + guard let group = group else { return } + + let alert = UIAlertController( + title: "Delete Group", + message: "Are you sure you want to delete this group? This action cannot be undone.", + preferredStyle: .alert + ) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in + self?.deleteGroup() + }) + + present(alert, animated: true) +} + +private func leaveGroup() { + guard let guid = group?.guid else { return } + + CometChat.leaveGroup(GUID: guid) { [weak self] _ in + DispatchQueue.main.async { + self?.navigationController?.popToRootViewController(animated: true) + } + } onError: { error in + print("Leave group error: \(error?.errorDescription ?? "")") + } +} -@objc func showDeleteGroupAlert() { /* deleteGroup and pop to Home */ } +private func deleteGroup() { + guard let guid = group?.guid else { return } + + CometChat.deleteGroup(GUID: guid) { [weak self] _ in + DispatchQueue.main.async { + self?.navigationController?.popToRootViewController(animated: true) + } + } onError: { error in + print("Delete group error: \(error?.errorDescription ?? "")") + } +} ``` -**File reference:** -[`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) +This manages group exit, with transfer prompt for owners. -Manages group exit, with transfer prompt for owners. +**File reference:** [`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) -### 5. Listening for Group Events +### Step 5: Listen for Group Events -Update UI on member joins, leaves, bans, and ownership changes. +Update UI on member joins, leaves, bans, and ownership changes: ```swift +private let listenerId = "group-details-listener" + func connect() { + // Add SDK group listener CometChat.addGroupListener(listenerId, self) + + // Add UIKit group events listener CometChatGroupEvents.addListener(listenerId, self) } @@ -124,57 +242,141 @@ func disconnect() { CometChatGroupEvents.removeListener(listenerId) } -extension GroupDetailsViewController: CometChatGroupDelegate, CometChatGroupEventListener { - func onGroupMemberJoined(_ action: ActionMessage, user: User, group: Group) { updateGroupInfo(group) } - func onGroupMemberLeft(_ action: ActionMessage, user: User, group: Group) { /* hide UI if self-left */ } - // other event methods... +deinit { + disconnect() +} +``` + +```swift +// MARK: - CometChatGroupDelegate +extension GroupDetailsViewController: CometChatGroupDelegate { + + func onGroupMemberJoined(action: ActionMessage, joinedUser: User, joinedGroup: Group) { + updateGroupInfo(joinedGroup) + } + + func onGroupMemberLeft(action: ActionMessage, leftUser: User, leftGroup: Group) { + // Hide UI if current user left + if leftUser.uid == CometChat.getLoggedInUser()?.uid { + navigationController?.popViewController(animated: true) + } else { + updateGroupInfo(leftGroup) + } + } + + func onGroupMemberKicked(action: ActionMessage, kickedUser: User, kickedBy: User, kickedFrom: Group) { + updateGroupInfo(kickedFrom) + } + + func onGroupMemberBanned(action: ActionMessage, bannedUser: User, bannedBy: User, bannedFrom: Group) { + updateGroupInfo(bannedFrom) + } + + func onGroupMemberUnbanned(action: ActionMessage, unbannedUser: User, unbannedBy: User, unbannedFrom: Group) { + updateGroupInfo(unbannedFrom) + } + + func onGroupMemberScopeChanged(action: ActionMessage, scopeChangeduser: User, scopeChangedBy: User, scopeChangedTo: String, scopeChangedFrom: String, group: Group) { + updateGroupInfo(group) + } + + func onMemberAddedToGroup(action: ActionMessage, addedBy: User, addedUser: User, addedTo: Group) { + updateGroupInfo(addedTo) + } +} + +// MARK: - CometChatGroupEventListener +extension GroupDetailsViewController: CometChatGroupEventListener { + + func onOwnershipChange(group: Group?, member: GroupMember?) { + if let group = group { + updateGroupInfo(group) + } + } +} + +private func updateGroupInfo(_ group: Group) { + self.group = group + // Refresh UI with updated group data } ``` -**File reference:** -[`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift#L200-L245) +This keeps the group details in sync with back-end events. -Keeps the group details in sync with back-end events. +**File reference:** [`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift#L200-L245) ## Customization Options -- **Header Styling:** Use `CometChatTheme` to customize fonts, colors, and borders. -- **Button Labels:** Localize or rebrand action texts. -- **Avatar Placeholder:** Provide fallback initials or default images. +### Header Styling + +Use `CometChatTheme` to customize fonts, colors, and borders: + +```swift +// Apply custom theme +CometChatTheme.palette.primary = UIColor.systemBlue +CometChatTheme.typography.heading = UIFont.systemFont(ofSize: 20, weight: .bold) +``` + +### Button Labels + +Localize or rebrand action texts: + +```swift +viewMembersView.setTitle("View Members", for: .normal) +addMembersView.setTitle("Add Members", for: .normal) +bannedMembersView.setTitle("Banned Members", for: .normal) +``` + +### Avatar Placeholder + +Provide fallback initials or default images: + +```swift +avatarView.set(name: group.name) +avatarView.set(image: UIImage(named: "default_group_avatar")) +``` -## Filtering & Edge Cases +## Edge Cases -- **Private/Protected Groups:** Prompt for a password before joining. -- **Already a Member:** Hide or disable Join button. -- **Empty Group:** Show an empty state when no members. -- **Owner Restrictions:** Disable Delete for non-owners. +| Scenario | Handling | +|----------|----------| +| Private/Protected groups | Prompt for a password before joining | +| Already a member | Hide or disable Join button | +| Empty group | Show an empty state when no members | +| Owner restrictions | Disable Delete for non-owners | ## Error Handling -- **Join Failures:** Show alert on network or permission errors. -- **Leave/Delete Errors:** Display retry prompt on API failure. -- **Event Errors:** Log and notify user if group events fail. +| Error Type | Solution | +|------------|----------| +| Join failures | Show alert on network or permission errors | +| Leave/Delete errors | Display retry prompt on API failure | +| Event errors | Log and notify user if group events fail | ## Feature Matrix -| Feature | Component / Method | File(s) | -|:-----------------------|:------------------------------|:--------------------------------------------------------------------------------| -| Show group details | `GroupDetailsViewController` | `GroupDetailsViewController.swift` | -| View group members | `viewMembersView` action | `GroupDetailsViewController.swift` | -| Add members | `addMembersView` action | `GroupDetailsViewController.swift` | -| Ban members | `bannedMembersView` action | `GroupDetailsViewController.swift` | -| Join group | `CometChat.joinGroup()` | `GroupDetailsViewController.swift` | -| Leave group | `showLeaveGroupAlert()` | `GroupDetailsViewController.swift` | -| Delete group | `showDeleteGroupAlert()` | `GroupDetailsViewController.swift` | -| Real-time updates | `CometChatGroupDelegate` | `GroupDetailsViewController.swift` | - - - - Explore the complete Group Details flow: - [GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) +| Feature | Component / Method | File(s) | +|---------|-------------------|---------| +| Show group details | `GroupDetailsViewController` | `GroupDetailsViewController.swift` | +| View group members | `viewMembersView` action | `GroupDetailsViewController.swift` | +| Add members | `addMembersView` action | `GroupDetailsViewController.swift` | +| Ban members | `bannedMembersView` action | `GroupDetailsViewController.swift` | +| Join group | `CometChat.joinGroup()` | `GroupDetailsViewController.swift` | +| Leave group | `showLeaveGroupAlert()` | `GroupDetailsViewController.swift` | +| Delete group | `showDeleteGroupAlert()` | `GroupDetailsViewController.swift` | +| Real-time updates | `CometChatGroupDelegate` | `GroupDetailsViewController.swift` | + +## Related Components + +- [Groups](/ui-kit/ios/groups) - Display group list +- [Group Members](/ui-kit/ios/group-members) - Display group member list +- [Events](/ui-kit/ios/events) - Listen for chat events + + + + Explore the complete Group Details flow - - Browse the Group Details implementation: - [GitHub → GroupDetailsViewController.swift](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) + + Browse the Group Details implementation - \ No newline at end of file + diff --git a/ui-kit/ios/guide-group-ownership.mdx b/ui-kit/ios/guide-group-ownership.mdx index 1ee408e80..4d98a700f 100644 --- a/ui-kit/ios/guide-group-ownership.mdx +++ b/ui-kit/ios/guide-group-ownership.mdx @@ -1,185 +1,411 @@ --- title: "Transfer Group Ownership" sidebarTitle: "Transfer Group Ownership" +description: "Enable group owners to transfer ownership to another member" --- -Enable the current group owner to delegate ownership to another member using CometChat’s UIKit for iOS. +Enable the current group owner to delegate ownership to another member using CometChat's UIKit for iOS. ## Overview -The **Transfer Group Ownership** feature provides a modal interface where the group owner can: +The Transfer Group Ownership feature provides a modal interface where the group owner can: -- See a list of current group members (excluding themselves). -- Select exactly one member to become the new owner. -- Trigger the ownership transfer API call. -- Automatically exit the group after successful transfer. +- See a list of current group members (excluding themselves) +- Select exactly one member to become the new owner +- Trigger the ownership transfer API call +- Automatically exit the group after successful transfer ## Prerequisites -- A UIKit-based iOS project. -- CometChat UIKit for iOS v5 installed via CocoaPods or Swift Package Manager. -- CometChat SDKs (`CometChatSDK`, `CometChatUIKitSwift`) integrated. -- Logged-in user with `CometChat.login()`. -- `UINavigationController` or modal presentation flow set up. -- Group context (GUID) available when invoking the transfer screen. +Before implementing ownership transfer, ensure you have: + +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- CometChat UIKit v5+ installed via CocoaPods or Swift Package Manager +- CometChatSDK and CometChatUIKitSwift integrated +- User logged in with `CometChatUIKit.login()` +- `UINavigationController` or modal presentation flow set up +- Group context (GUID) available when invoking the transfer screen ## Components -| Component | Responsibility | -|:------------------------------------|:--------------------------------------------------------------------| -| `TransferOwnership` | Subclass of `CometChatGroupMembers` enabling single selection mode. | -| `viewModel.groupMembers` | Data source array of `GroupMember` objects. | -| `onSelectedItemProceed` | Closure invoked when user confirms selection. | -| `CometChat.transferGroupOwnership` | API call to delegate group ownership. | -| `spinnerView` | `UIActivityIndicatorView` showing loading state. | -| `leaveGroupCallback` | Callback to perform group exit after transfer. | +| Component | Description | +|-----------|-------------| +| `TransferOwnership` | Subclass of `CometChatGroupMembers` enabling single selection mode | +| `viewModel.groupMembers` | Data source array of `GroupMember` objects | +| `onSelectedItemProceed` | Closure invoked when user confirms selection | +| `CometChat.transferGroupOwnership` | API call to delegate group ownership | +| `spinnerView` | `UIActivityIndicatorView` showing loading state | +| `leaveGroupCallback` | Callback to perform group exit after transfer | ## Integration Steps -### 1. Present Transfer Ownership Screen +### Step 1: Present Transfer Ownership Screen -Show the ownership transfer UI modally. +Show the ownership transfer UI modally: ```swift -func showTransferOwnership(for group: Group) { - let transferVC = TransferOwnership() - transferVC.set(group: group) - let nav = UINavigationController(rootViewController: transferVC) - present(nav, animated: true) +import UIKit +import CometChatSDK +import CometChatUIKitSwift + +class GroupDetailsViewController: UIViewController { + + var group: Group? + + func showTransferOwnership(for group: Group) { + // Initialize transfer ownership view controller + let transferVC = TransferOwnership() + transferVC.set(group: group) + + // Set callback for after transfer completes + transferVC.leaveGroupCallback = { [weak self] in + self?.leaveGroup() + } + + // Present modally with navigation + let nav = UINavigationController(rootViewController: transferVC) + present(nav, animated: true) + } + + private func leaveGroup() { + // Handle leaving group after ownership transfer + navigationController?.popToRootViewController(animated: true) + } } ``` -**File reference:** -[`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) +**File reference:** [`GroupDetailsViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/DetailsPage/GroupDetailsViewController.swift) -### 2. Configure Single Selection Mode +### Step 2: Configure Single Selection Mode -Restrict selection to one member and capture selection. +Restrict selection to one member and capture selection: ```swift -override func viewDidLoad() { - selectionMode = .single - super.viewDidLoad() - title = "OWNERSHIP_TRANSFER".localize() - onSelectedItemProceed = { [weak self] users in - if let newOwner = users.first { - self?.transferOwnership(to: newOwner) +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class TransferOwnership: CometChatGroupMembers { + + var leaveGroupCallback: (() -> Void)? + + private let spinnerView: UIActivityIndicatorView = { + let spinner = UIActivityIndicatorView(style: .medium) + spinner.hidesWhenStopped = true + return spinner + }() + + override func viewDidLoad() { + // Enable single selection mode + selectionMode = .single + + super.viewDidLoad() + + // Set navigation title + title = "OWNERSHIP_TRANSFER".localize() + + // Handle member selection + onSelectedItemProceed = { [weak self] users in + if let newOwner = users.first as? GroupMember { + self?.transferOwnership(to: newOwner) + } + } } - } } ``` -**File reference:** -[`TransferOwnership.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift#L1-L30) +**File reference:** [`TransferOwnership.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift#L1-L30) -### 3. Load & Filter Member List +### Step 3: Load and Filter Member List -Exclude the current owner from the selectable list. +Exclude the current owner from the selectable list: ```swift override func reloadData() { - super.reloadData() - viewModel.reload = { [weak self] in - guard let self = self else { return } - let currentUID = CometChat.getLoggedInUser()?.uid - self.viewModel.groupMembers.removeAll { $0.uid == currentUID } - DispatchQueue.main.async { - self.removeLoadingView() - self.removeErrorView() - self.reload() - if self.viewModel.groupMembers.isEmpty { self.showEmptyView() } + super.reloadData() + + viewModel.reload = { [weak self] in + guard let self = self else { return } + + // Get current user's UID + let currentUID = CometChat.getLoggedInUser()?.uid + + // Remove current owner from the list + self.viewModel.groupMembers.removeAll { $0.uid == currentUID } + + DispatchQueue.main.async { + // Update UI state + self.removeLoadingView() + self.removeErrorView() + self.reload() + + // Show empty state if no eligible members + if self.viewModel.groupMembers.isEmpty { + self.showEmptyView() + } + } } - } } ``` -**File reference:** -[`TransferOwnership.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift#L31-L60) +**File reference:** [`TransferOwnership.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift#L31-L60) -### 4. Perform Ownership Transfer +### Step 4: Perform Ownership Transfer -Call the API, emit event, and exit the group. +Call the API, emit event, and exit the group: ```swift func transferOwnership(to member: GroupMember) { - addSpinnerView() - let uid = member.uid ?? "" - let guid = viewModel.group.guid - - CometChat.transferGroupOwnership(UID: uid, GUID: guid) { [weak self] _ in - DispatchQueue.main.async { - // Update local state - self?.viewModel.group.owner = uid - CometChatGroupEvents.ccOwnershipChanged(group: self!.viewModel.group, newOwner: member) - self?.leaveGroupCallback?() - self?.removeSpinnerView() - self?.dismiss(animated: true) + // Show loading indicator + addSpinnerView() + + let uid = member.uid ?? "" + let guid = viewModel.group.guid + + CometChat.transferGroupOwnership(UID: uid, GUID: guid) { [weak self] successMessage in + DispatchQueue.main.async { + guard let self = self else { return } + + // Update local group state + self.viewModel.group.owner = uid + + // Emit ownership changed event for other components + CometChatGroupEvents.ccOwnershipChanged( + group: self.viewModel.group, + newOwner: member + ) + + // Execute leave group callback + self.leaveGroupCallback?() + + // Hide loading and dismiss + self.removeSpinnerView() + self.dismiss(animated: true) + } + } onError: { [weak self] error in + DispatchQueue.main.async { + self?.removeSpinnerView() + + // Show error alert + let alert = UIAlertController( + title: "Transfer Failed", + message: error?.errorDescription ?? "Unable to transfer ownership", + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + self?.present(alert, animated: true) + } } - } onError: { [weak self] error in - DispatchQueue.main.async { - self?.removeSpinnerView() - // TODO: Show error alert - } - } } ``` -**File reference:** -[`TransferOwnership.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift#L61-L100) +**File reference:** [`TransferOwnership.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift#L61-L100) -### 5. Manage Loading State +### Step 5: Manage Loading State -Provide visual feedback during network calls. +Provide visual feedback during network calls: ```swift func addSpinnerView() { - spinnerView.startAnimating() - navigationItem.rightBarButtonItem = UIBarButtonItem(customView: spinnerView) + // Start spinner animation + spinnerView.startAnimating() + + // Replace right bar button with spinner + navigationItem.rightBarButtonItem = UIBarButtonItem(customView: spinnerView) } func removeSpinnerView() { - spinnerView.stopAnimating() - navigationItem.rightBarButtonItem = nil + // Stop spinner animation + spinnerView.stopAnimating() + + // Remove spinner from navigation bar + navigationItem.rightBarButtonItem = nil } ``` -**File reference:** -[`TransferOwnership.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift#L101-L130) +**File reference:** [`TransferOwnership.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift#L101-L130) + +## Complete Implementation + +Here's the complete `TransferOwnership` class: + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class TransferOwnership: CometChatGroupMembers { + + // MARK: - Properties + var leaveGroupCallback: (() -> Void)? + + private let spinnerView: UIActivityIndicatorView = { + let spinner = UIActivityIndicatorView(style: .medium) + spinner.hidesWhenStopped = true + return spinner + }() + + // MARK: - Lifecycle + override func viewDidLoad() { + selectionMode = .single + super.viewDidLoad() + + title = "Transfer Ownership" + + onSelectedItemProceed = { [weak self] users in + if let newOwner = users.first as? GroupMember { + self?.transferOwnership(to: newOwner) + } + } + } + + // MARK: - Data Loading + override func reloadData() { + super.reloadData() + + viewModel.reload = { [weak self] in + guard let self = self else { return } + + let currentUID = CometChat.getLoggedInUser()?.uid + self.viewModel.groupMembers.removeAll { $0.uid == currentUID } + + DispatchQueue.main.async { + self.removeLoadingView() + self.removeErrorView() + self.reload() + + if self.viewModel.groupMembers.isEmpty { + self.showEmptyView() + } + } + } + } + + // MARK: - Transfer Ownership + func transferOwnership(to member: GroupMember) { + addSpinnerView() + + let uid = member.uid ?? "" + let guid = viewModel.group.guid + + CometChat.transferGroupOwnership(UID: uid, GUID: guid) { [weak self] _ in + DispatchQueue.main.async { + guard let self = self else { return } + + self.viewModel.group.owner = uid + CometChatGroupEvents.ccOwnershipChanged( + group: self.viewModel.group, + newOwner: member + ) + + self.leaveGroupCallback?() + self.removeSpinnerView() + self.dismiss(animated: true) + } + } onError: { [weak self] error in + DispatchQueue.main.async { + self?.removeSpinnerView() + self?.showError(error) + } + } + } + + // MARK: - Loading State + func addSpinnerView() { + spinnerView.startAnimating() + navigationItem.rightBarButtonItem = UIBarButtonItem(customView: spinnerView) + } + + func removeSpinnerView() { + spinnerView.stopAnimating() + navigationItem.rightBarButtonItem = nil + } + + // MARK: - Error Handling + private func showError(_ error: CometChatException?) { + let alert = UIAlertController( + title: "Transfer Failed", + message: error?.errorDescription ?? "Unable to transfer ownership", + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + present(alert, animated: true) + } +} +``` ## Customization Options -- **Title Text:** Replace localization key with custom string. -- **Spinner Style:** Adjust `spinnerView.style` and color using `CometChatTheme`. -- **Error Handling:** Customize error alerts in the `onError` closure. +### Title Text -## Filtering & Edge Cases +Replace localization key with custom string: -- **Empty Member List:** Show an informative empty state when no eligible members exist. -- **Network Failures:** Disable proceed button until connection restores. -- **Blocked Members:** Exclude or disable blocked users from selection. +```swift +title = "Select New Owner" +``` + +### Spinner Style + +Adjust `spinnerView.style` and color using `CometChatTheme`: + +```swift +spinnerView.style = .large +spinnerView.color = CometChatTheme.palette.primary +``` + +### Error Handling + +Customize error alerts in the `onError` closure: + +```swift +let alert = UIAlertController( + title: "Oops!", + message: "Could not transfer ownership. Please try again.", + preferredStyle: .alert +) +alert.addAction(UIAlertAction(title: "Retry", style: .default) { [weak self] _ in + self?.transferOwnership(to: member) +}) +alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) +present(alert, animated: true) +``` + +## Edge Cases + +| Scenario | Handling | +|----------|----------| +| Empty member list | Show an informative empty state when no eligible members exist | +| Network failures | Disable proceed button until connection restores | +| Blocked members | Exclude or disable blocked users from selection | ## Error Handling -- **Transfer Failures:** Present `UIAlertController` with retry option. -- **Unexpected States:** Ensure `removeSpinnerView()` always executes in `defer`. +| Error Type | Solution | +|------------|----------| +| Transfer failures | Present `UIAlertController` with retry option | +| Unexpected states | Ensure `removeSpinnerView()` always executes in `defer` | ## Feature Matrix -| Feature | Method / Component | File(s) | -|:-------------------------------|:---------------------------------------|:------------------------------------------------------------------------------------------| -| Launch transfer flow | `showTransferOwnership(for:)` | `GroupDetailsViewController.swift` | -| Single-member selection | `selectionMode = .single` | `TransferOwnership.swift` | -| Filter out current owner | `reloadData()` override | `TransferOwnership.swift` | -| Execute API transfer | `CometChat.transferGroupOwnership()` | `TransferOwnership.swift` | -| Show/hide loading indicator | `addSpinnerView()`, `removeSpinnerView()` | `TransferOwnership.swift` | - - - - Explore the transfer ownership feature in context: - [GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) +| Feature | Method / Component | File(s) | +|---------|-------------------|---------| +| Launch transfer flow | `showTransferOwnership(for:)` | `GroupDetailsViewController.swift` | +| Single-member selection | `selectionMode = .single` | `TransferOwnership.swift` | +| Filter out current owner | `reloadData()` override | `TransferOwnership.swift` | +| Execute API transfer | `CometChat.transferGroupOwnership()` | `TransferOwnership.swift` | +| Show/hide loading indicator | `addSpinnerView()`, `removeSpinnerView()` | `TransferOwnership.swift` | + +## Related Components + +- [Groups](/ui-kit/ios/groups) - Display group list +- [Group Members](/ui-kit/ios/group-members) - Display group member list +- [Events](/ui-kit/ios/events) - Listen for chat events + + + + Explore the transfer ownership feature in context - - Review the implementation: - [TransferOwnership.swift](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/Transfer%20ownership%20/TransferOwnership.swift) + + Review the implementation - \ No newline at end of file + From 2e3ad6b018247582dc2cb25f8570eea76db6c819 Mon Sep 17 00:00:00 2001 From: Aditya Date: Thu, 12 Feb 2026 16:35:41 +0530 Subject: [PATCH 009/106] guide-message-privately , guide-new-chat , guide-overview --- ui-kit/ios/guide-message-privately.mdx | 199 +++++++++++------ ui-kit/ios/guide-new-chat.mdx | 286 +++++++++++++++++-------- ui-kit/ios/guide-overview.mdx | 21 +- 3 files changed, 344 insertions(+), 162 deletions(-) diff --git a/ui-kit/ios/guide-message-privately.mdx b/ui-kit/ios/guide-message-privately.mdx index 8d065a0d3..857c5c5b6 100644 --- a/ui-kit/ios/guide-message-privately.mdx +++ b/ui-kit/ios/guide-message-privately.mdx @@ -1,120 +1,187 @@ --- title: "Message Privately" sidebarTitle: "Message Privately" +description: "Start private one-on-one chats from group conversations" --- -Enable users to start a private one-on-one chat with a group member directly from a group chat screen using CometChat’s UIKit for iOS. +Enable users to start a private one-on-one chat with a group member directly from a group chat screen using CometChat's UIKit for iOS. ## Overview -The **Message Privately** feature allows users to long-press a message in a group chat and select **Message Privately** to transition into a private conversation with the original sender. This streamlines side discussions and follow-ups without manual user searches. +The Message Privately feature allows users to long-press a message in a group chat and select **Message Privately** to transition into a private conversation with the original sender. This streamlines side discussions and follow-ups without requiring manual user searches. ## Prerequisites -- UIKit-based iOS project. -- CometChat UIKit for iOS v5 installed via CocoaPods or Swift Package Manager. -- Valid CometChat **App ID**, **Region**, and **Auth Key**. -- Functional group chat via `CometChatMessageList`. -- A one-on-one chat screen (`CometChatMessages` or custom) and navigation flow configured. +Before implementing this feature, ensure you have: + +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- CometChat UIKit v5+ installed via CocoaPods or Swift Package Manager +- Valid CometChat App ID, Region, and Auth Key +- Functional group chat via `CometChatMessageList` +- A one-on-one chat screen (`CometChatMessages` or custom) and navigation flow configured ## Components -| Component | Role | -|:-----------------------------------|:-------------------------------------------------------------------------------------------------| -| `CometChatMessageList` | Displays group messages; handles long-press to show options. | -| `CometChatMessageOption` | Defines the **Message Privately** option in the context menu. | -| `MessageDataSource` | Supplies the `messagePrivatelyOption` in the options array. | -| `CometChatMessageListViewModel` | Manages UI state, including `hideMessagePrivatelyOption`. | -| `CometChatMessages` | Entry point for rendering or pushing the private chat interface. | -| `CometChatUIKit.getUser(uid:)` | Retrieves the `User` object for the selected message sender. | -| `CometChatUIKit.getConversationWith(user:)` | Creates or fetches the 1-on-1 conversation instance. | -| `UIViewController` (Navigation) | Pushes or presents the private chat screen (`CometChatMessages`). | +| Component | Description | +|-----------|-------------| +| `CometChatMessageList` | Displays group messages and handles long-press to show options | +| `CometChatMessageOption` | Defines the **Message Privately** option in the context menu | +| `MessageDataSource` | Supplies the `messagePrivatelyOption` in the options array | +| `CometChatMessageListViewModel` | Manages UI state, including `hideMessagePrivatelyOption` | +| `CometChatMessages` | Entry point for rendering or pushing the private chat interface | +| `CometChatUIKit.getUser(uid:)` | Retrieves the `User` object for the selected message sender | +| `CometChatUIKit.getConversationWith(user:)` | Creates or fetches the 1-on-1 conversation instance | +| `UIViewController` (Navigation) | Pushes or presents the private chat screen (`CometChatMessages`) | ## Integration Steps -### 1. Control Option Visibility via ViewModel +### Step 1: Control Option Visibility via ViewModel -Dynamically show or hide **Message Privately** based on app context. +Dynamically show or hide **Message Privately** based on app context: ```swift +import CometChatUIKitSwift + +// Control visibility of the Message Privately option public var hideMessagePrivatelyOption: Bool = false { didSet { + // Sync with view model viewModel.hideMessagePrivatelyOption = hideMessagePrivatelyOption } } ``` -**File reference:** -[`CometChatMessageList.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift) +This ensures the option only appears when appropriate (e.g., based on user permissions). -Ensures the option only appears when appropriate (e.g., user permissions). +**File reference:** [`CometChatMessageList.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift) -### 2. Handle Private Chat Navigation +### Step 2: Handle Private Chat Navigation -Retrieve the sender and initiate a private 1-on-1 chat. +Retrieve the sender and initiate a private 1-on-1 chat: ```swift -if let uid = selectedMessage.sender?.uid { - CometChatUIKit.getUser(uid: uid) { user in - CometChatUIKit.getConversationWith(user: user) { conversation in - let messagesVC = CometChatMessages(conversation: conversation) - navigationController?.pushViewController(messagesVC, animated: true) +import UIKit +import CometChatSDK +import CometChatUIKitSwift + +func startPrivateChat(with selectedMessage: BaseMessage) { + // Get the sender's UID from the selected message + if let uid = selectedMessage.sender?.uid { + + // Fetch the user object + CometChatUIKit.getUser(uid: uid) { user in + + // Get or create the conversation + CometChatUIKit.getConversationWith(user: user) { conversation in + + // Navigate to the private chat screen + let messagesVC = CometChatMessages(conversation: conversation) + navigationController?.pushViewController(messagesVC, animated: true) + } } } } ``` -**File reference:** -[`CometChatMessageList.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift) +This automates the transition from group context to private conversation. -Automates transition from group context to private conversation. +**File reference:** [`CometChatMessageList.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift) ## Implementation Flow -1. Long-press a group message in `CometChatMessageList`. -2. Options menu appears with **Message Privately**. -3. User taps **Message Privately**. -4. App fetches `User` via `CometChatUIKit.getUser(uid:)`. -5. Retrieves or creates conversation via `CometChatUIKit.getConversationWith(user:)`. -6. Pushes `CometChatMessages` onto the navigation stack. +| Step | Action | +|------|--------| +| 1 | Long-press a group message in `CometChatMessageList` | +| 2 | Options menu appears with **Message Privately** | +| 3 | User taps **Message Privately** | +| 4 | App fetches `User` via `CometChatUIKit.getUser(uid:)` | +| 5 | Retrieves or creates conversation via `CometChatUIKit.getConversationWith(user:)` | +| 6 | Pushes `CometChatMessages` onto the navigation stack | ## Customization Options -- **Styling:** Override `CometChatMessageOption` UI (icons, fonts, colors). -- **Availability:** Control via `viewModel.hideMessagePrivatelyOption`. -- **Extend Options:** Add additional actions in `MessageDataSource.getMessageOptions(for:)`. +### Styling + +Override `CometChatMessageOption` UI elements: + +```swift +// Customize the message option appearance +let privateOption = CometChatMessageOption( + id: "message-privately", + title: "Message Privately", + icon: UIImage(systemName: "person.fill"), + backgroundColor: .systemBlue +) +``` + +### Availability + +Control visibility via the view model: + +```swift +// Hide the option for specific scenarios +viewModel.hideMessagePrivatelyOption = true +``` + +### Extend Options + +Add additional actions in `MessageDataSource.getMessageOptions(for:)`: + +```swift +func getMessageOptions(for message: BaseMessage) -> [CometChatMessageOption] { + var options = [CometChatMessageOption]() + + // Add message privately option + if !hideMessagePrivatelyOption { + options.append(messagePrivatelyOption) + } + + // Add custom options + options.append(customOption) + + return options +} +``` + +## Edge Cases + +| Scenario | Handling | +|----------|----------| +| Blocked users | Hide option if the sender is in block list | +| Existing conversations | Reuse existing thread via `getConversationWith` | +| Unavailable users | Skip option or show disabled state if user data is missing | + +## Error Handling -## Filtering & Edge Cases +| Error Type | Solution | +|------------|----------| +| Block state | Catch errors from `getUser`/`getConversationWith` and alert user | +| Network failures | Present retry or toast on navigation errors | +| Invalid data | Disable option if `sender.uid` is nil | -- **Blocked Users:** Hide option if the sender is in block list. -- **Existing Conversations:** Reuse existing thread via `getConversationWith`. -- **Unavailable Users:** Skip option or show disabled state if user data missing. +## Additional Notes -## Error Handling & Blocked-User Handling +- This feature is only available in **group chat** screens (`CometChatMessageList`) +- The option is hidden automatically in direct/private chat views -- **Block State:** Catch errors from `getUser`/`getConversationWith` and alert user. -- **Network Failures:** Present retry or toast on navigation errors. -- **Invalid Data:** Disable option if `sender.uid` is nil. +## Feature Matrix -## Optional Context-Specific Notes +| Feature | Component / Method | File(s) | +|---------|-------------------|---------| +| Show options menu | `getMessageOptions(for:)` | [`MessageDataSource.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Framework/MessagesDataSource.swift) | +| Toggle Message Privately | `viewModel.hideMessagePrivatelyOption` | [`CometChatMessageList.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift), [`MessageListViewModel.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift) | -- Only available in **group chat** screens (`CometChatMessageList`). -- Hidden automatically in direct/private chat views. +## Related Components -## Summary / Feature Matrix +- [Message List](/ui-kit/ios/message-list) - Display messages in conversations +- [Users](/ui-kit/ios/users) - Display user list +- [Conversations](/ui-kit/ios/conversations) - Display conversation list -| Feature | Component / Method | File(s) | -|:----------------------------|:------------------------------------------|:--------------------------------------------------------------------------------------------| -| Show options menu | `getMessageOptions(for:)` | [`MessageDataSource.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Framework/MessagesDataSource.swift) | -| Toggle **Message Privately**| `viewModel.hideMessagePrivatelyOption` | [`CometChatMessageList.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift),
[`MessageListViewModel.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift) | - - - - Explore this feature in the CometChat SampleApp: - [GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) + + + Explore this feature in the CometChat SampleApp - - Browse the message list component: - [GitHub → CometChatMessageList.swift](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Message%20List/CometChatMessageList.swift) + + Browse the message list component - \ No newline at end of file + diff --git a/ui-kit/ios/guide-new-chat.mdx b/ui-kit/ios/guide-new-chat.mdx index 83716e6d4..18d9b7d1e 100644 --- a/ui-kit/ios/guide-new-chat.mdx +++ b/ui-kit/ios/guide-new-chat.mdx @@ -1,202 +1,308 @@ --- title: "Create Conversation" sidebarTitle: "Create Conversation" +description: "Enable users to start new 1:1 or group chats" --- -Enable users to start new 1:1 or group chats in your iOS app using CometChat’s UIKit for iOS by integrating the **CreateConversationVC** screen. +Enable users to start new 1:1 or group chats in your iOS app using CometChat's UIKit for iOS by integrating the `CreateConversationVC` screen. ## Overview -The `CreateConversation` enables users to: +The `CreateConversation` component enables users to: -- Browse CometChat users and groups via native list components. -- Search within users and groups. -- Toggle between “Users” and “Groups” tabs using a segmented control. -- Swipe between lists with a `UIPageViewController`. -- Navigate to `MessagesVC` upon selecting a user or group. +- Browse CometChat users and groups via native list components +- Search within users and groups +- Toggle between "Users" and "Groups" tabs using a segmented control +- Swipe between lists with a `UIPageViewController` +- Navigate to `MessagesVC` upon selecting a user or group ## Prerequisites -- A UIKit-based iOS project. -- CometChat UIKit for iOS v5 installed via CocoaPods or Swift Package Manager. -- User authenticated with `CometChat.login()` before presenting this screen. -- A `UINavigationController` embedded in your flow. -- `MessagesVC` implemented to handle chat screens. +Before implementing this feature, ensure you have: + +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- CometChat UIKit v5+ installed via CocoaPods or Swift Package Manager +- User authenticated with `CometChatUIKit.login()` before presenting this screen +- A `UINavigationController` embedded in your flow +- `MessagesVC` implemented to handle chat screens ## Components -| Component | Role | -|:------------------------|:------------------------------------------------------------| -| `UISegmentedControl` | Switches between “Users” and “Groups” tabs. | -| `UIPageViewController` | Enables swipe navigation between list views. | -| `CometChatUsers` | Displays the list of CometChat users. | -| `CometChatGroups` | Displays the list of CometChat groups. | -| `MessagesVC` | Chat interface, launched upon item selection. | -| `searchController` | Provides search for both users and groups. | -| `CometChatTheme` | Applies theming (colors, fonts) for UI consistency. | -| `CometChatTypography` | Defines text styles for segment labels. | +| Component | Description | +|-----------|-------------| +| `UISegmentedControl` | Switches between "Users" and "Groups" tabs | +| `UIPageViewController` | Enables swipe navigation between list views | +| `CometChatUsers` | Displays the list of CometChat users | +| `CometChatGroups` | Displays the list of CometChat groups | +| `MessagesVC` | Chat interface, launched upon item selection | +| `searchController` | Provides search for both users and groups | +| `CometChatTheme` | Applies theming (colors, fonts) for UI consistency | +| `CometChatTypography` | Defines text styles for segment labels | ## Integration Steps -### 1. Presenting the Create Conversation Screen +### Step 1: Present the Create Conversation Screen -Push `CreateConversations` to allow starting a chat. +Push `CreateConversations` to allow starting a chat: ```swift import UIKit import CometChatSDK -func showCreateConversation() { - let createVC = CreateConversationVC() - navigationController?.pushViewController(createVC, animated: true) +class HomeViewController: UIViewController { + + func showCreateConversation() { + // Initialize the create conversation view controller + let createVC = CreateConversationVC() + + // Push onto navigation stack + navigationController?.pushViewController(createVC, animated: true) + } } ``` -**File reference:** -[`HomeScreenViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/HomeScreenViewController.swift) +This provides the entry point to the create-conversation flow. -Provides entry point to the create-conversation flow. +**File reference:** [`HomeScreenViewController.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/HomeScreenViewController.swift) -### 2. Setting Up the User Interface +### Step 2: Set Up the User Interface -Build the segmented control and page view controller. +Build the segmented control and page view controller: ```swift -override public func viewDidLoad() { - super.viewDidLoad() - buildUI() // sets up segmentedControl, pageViewController, and searchController - setupPageViewController() - segmentedControl.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged) - navigationItem.searchController = usersViewController.searchController +import UIKit +import CometChatUIKitSwift + +class CreateConversationVC: UIViewController { + + private var segmentedControl: UISegmentedControl! + private var pageViewController: UIPageViewController! + private var usersViewController: CometChatUsers! + private var groupsViewController: CometChatGroups! + + override public func viewDidLoad() { + super.viewDidLoad() + + // Set up segmented control, page view controller, and search + buildUI() + setupPageViewController() + + // Add target for segment changes + segmentedControl.addTarget( + self, + action: #selector(segmentChanged(_:)), + for: .valueChanged + ) + + // Set initial search controller + navigationItem.searchController = usersViewController.searchController + } + + private func buildUI() { + // Configure segmented control and page view + } + + private func setupPageViewController() { + // Initialize page view controller with users and groups + } } ``` -**File reference:** -[`CreateConversations.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversations.swift) +This initializes the UI elements and search integration. -Initializes the UI elements and search integration. +**File reference:** [`CreateConversations.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversations.swift) -### 3. Configuring Segmented Control Navigation +### Step 3: Configure Segmented Control Navigation -Toggle between user and group lists when the segment changes. +Toggle between user and group lists when the segment changes: ```swift @objc public func segmentChanged(_ sender: UISegmentedControl) { let index = sender.selectedSegmentIndex + + // Determine navigation direction let direction: UIPageViewController.NavigationDirection = index == 0 ? .reverse : .forward + + // Update search controller based on selected tab navigationItem.searchController = (index == 0) ? usersViewController.searchController : groupsViewController.searchController - pageViewController.setViewControllers([pages[index]], direction: direction, animated: true) + + // Navigate to the selected page + pageViewController.setViewControllers( + [pages[index]], + direction: direction, + animated: true + ) } ``` -**File reference:** -[`CreateConversations.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversations.swift) +This keeps the proper search bar and view in sync with the selected tab. -Keeps the proper search bar and view in sync with the selected tab. +**File reference:** [`CreateConversations.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversations.swift) -### 4. Handling Item Selection +### Step 4: Handle Item Selection -Navigate to `MessagesVC` when a user or group is tapped. +Navigate to `MessagesVC` when a user or group is tapped: ```swift -// User tap +// Users list with tap handler public lazy var usersViewController: CometChatUsers = { let vc = CometChatUsers() + + // Handle user selection vc.set(onItemClick: { [weak self] user, _ in let chatVC = MessagesVC() chatVC.user = user self?.navigationController?.pushViewController(chatVC, animated: true) }) + + // Keep navigation bar visible during search vc.searchController.hidesNavigationBarDuringPresentation = false + return vc }() -// Group tap +// Groups list with tap handler public lazy var groupsViewController: CometChatGroups = { let vc = CometChatGroups() + + // Handle group selection vc.set(onItemClick: { [weak self] group, _ in let chatVC = MessagesVC() chatVC.group = group self?.navigationController?.pushViewController(chatVC, animated: true) }) + + // Keep navigation bar visible during search vc.searchController.hidesNavigationBarDuringPresentation = false + return vc }() ``` -**File reference:** -[`CreateConversations.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversations.swift) +This routes the user to the appropriate chat screen. -Routes the user to the appropriate chat screen. +**File reference:** [`CreateConversations.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversations.swift) -### 5. Managing Page View Transitions +### Step 5: Manage Page View Transitions -Implement data source and delegate for smooth swiping. +Implement data source and delegate for smooth swiping: ```swift +// MARK: - UIPageViewControllerDataSource extension CreateConversationVC: UIPageViewControllerDataSource { - public func pageViewController(_ pvc: UIPageViewController, viewControllerBefore vc: UIViewController) -> UIViewController? { + + public func pageViewController( + _ pvc: UIPageViewController, + viewControllerBefore vc: UIViewController + ) -> UIViewController? { guard let idx = pages.firstIndex(of: vc), idx > 0 else { return nil } return pages[idx - 1] } - public func pageViewController(_ pvc: UIPageViewController, viewControllerAfter vc: UIViewController) -> UIViewController? { + + public func pageViewController( + _ pvc: UIPageViewController, + viewControllerAfter vc: UIViewController + ) -> UIViewController? { guard let idx = pages.firstIndex(of: vc), idx < pages.count - 1 else { return nil } return pages[idx + 1] } } +// MARK: - UIPageViewControllerDelegate extension CreateConversationVC: UIPageViewControllerDelegate { - public func pageViewController(_ pvc: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { - if completed, let current = pvc.viewControllers?.first, let idx = pages.firstIndex(of: current) { + + public func pageViewController( + _ pvc: UIPageViewController, + didFinishAnimating finished: Bool, + previousViewControllers: [UIViewController], + transitionCompleted completed: Bool + ) { + // Sync segmented control with current page + if completed, + let current = pvc.viewControllers?.first, + let idx = pages.firstIndex(of: current) { segmentedControl.selectedSegmentIndex = idx } } } ``` -**File reference:** -[`CreateConversations.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversations.swift) +This synchronizes the segmented control with page swipes. -Synchronizes the segmented control with page swipes. +**File reference:** [`CreateConversations.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversations.swift) ## Customization Options -- **Segment Styling:** Use `CometChatTheme` to customize tint and font. -- **Labels:** Localize or rebrand “USERS” / “GROUPS” labels. -- **Search:** Adjust `searchController.placeholder` and styling. +### Segment Styling -## Filtering & Edge Cases +Use `CometChatTheme` to customize tint and font: -- **Live Search:** Built-in in `CometChatUsers` and `CometChatGroups`. -- **Empty States:** Components display default “no results” views. -- **Segment Disabled:** Hide tabs if only one list is relevant. +```swift +segmentedControl.selectedSegmentTintColor = CometChatTheme.palette.primary +segmentedControl.setTitleTextAttributes([ + .font: CometChatTypography.body, + .foregroundColor: UIColor.white +], for: .selected) +``` + +### Labels + +Localize or rebrand "USERS" / "GROUPS" labels: + +```swift +segmentedControl.setTitle("Contacts", forSegmentAt: 0) +segmentedControl.setTitle("Teams", forSegmentAt: 1) +``` + +### Search + +Adjust `searchController.placeholder` and styling: + +```swift +usersViewController.searchController.searchBar.placeholder = "Search contacts..." +groupsViewController.searchController.searchBar.placeholder = "Search teams..." +``` + +## Edge Cases + +| Scenario | Handling | +|----------|----------| +| Live search | Built-in in `CometChatUsers` and `CometChatGroups` | +| Empty states | Components display default "no results" views | +| Segment disabled | Hide tabs if only one list is relevant | ## Error Handling -- **Load Errors:** Use `setErrorView()` on list components. -- **Navigation Failures:** Present an alert if push fails. -- **Blocked Users:** Intercept in `onItemClick` to prevent navigation. +| Error Type | Solution | +|------------|----------| +| Load errors | Use `setErrorView()` on list components | +| Navigation failures | Present an alert if push fails | +| Blocked users | Intercept in `onItemClick` to prevent navigation | ## Feature Matrix -| Feature | Implementation | -|:------------------------------|:-----------------------------------------------| -| Show create screen | `showCreateConversation()` | -| Tabbed lists | `UISegmentedControl` + `UIPageViewController` | -| Display users | `CometChatUsers()` | -| Display groups | `CometChatGroups()` | -| Search functionality | `searchController` | -| Navigate to chat | `MessagesVC(user:)` / `MessagesVC(group:)` | - - - - Explore the complete create-conversation flow: - [GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) +| Feature | Implementation | +|---------|----------------| +| Show create screen | `showCreateConversation()` | +| Tabbed lists | `UISegmentedControl` + `UIPageViewController` | +| Display users | `CometChatUsers()` | +| Display groups | `CometChatGroups()` | +| Search functionality | `searchController` | +| Navigate to chat | `MessagesVC(user:)` / `MessagesVC(group:)` | + +## Related Components + +- [Users](/ui-kit/ios/users) - Display user list +- [Groups](/ui-kit/ios/groups) - Display group list +- [Conversations](/ui-kit/ios/conversations) - Display conversation list + + + + Explore the complete create-conversation flow - - Browse the source for `CreateConversationVC`: - [GitHub → CreateConversationVC.swift](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/CreateConversationVC.swift) + + Browse the source for CreateConversationVC - \ No newline at end of file + diff --git a/ui-kit/ios/guide-overview.mdx b/ui-kit/ios/guide-overview.mdx index 291ee9746..01318aeb5 100644 --- a/ui-kit/ios/guide-overview.mdx +++ b/ui-kit/ios/guide-overview.mdx @@ -1,23 +1,32 @@ --- title: "Overview" sidebarTitle: "Overview" +description: "Index of feature guides for iOS UI Kit" --- -> This page indexes focused, task‑oriented feature guides for the iOS UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UIKit components. + +This page indexes focused, task-oriented feature guides for the iOS UI Kit. Each guide shows how to implement a specific capability end-to-end using UIKit components. ## When to Use These Guides -Use these after completing [Getting Started](/ui-kit/ios/getting-started) and wiring your base conversations / messages flows. Apply them to layer feature depth without rebuilding standard patterns. +Use these guides after completing [Getting Started](/ui-kit/ios/getting-started) and wiring your base conversations/messages flows. Apply them to layer feature depth without rebuilding standard patterns. ## Guide Directory | Guide | Description | -|:------|:------------| +|-------|-------------| +| [AI Agent Integration](/ui-kit/ios/guide-ai-agent) | Add AI-powered chat assistants with chat history, contextual responses, and seamless handoffs. | | [Block / Unblock User](/ui-kit/ios/guide-block-unblock-user) | Add profile-level moderation so users can block or unblock others; hides interaction affordances and protects chat flow. | -| [Call Log Details](/ui-kit/ios/guide-call-log-details) | Provide a detailed post‑call screen with metadata, participants, history, and recordings for auditing & support. | +| [Call Log Details](/ui-kit/ios/guide-call-log-details) | Provide a detailed post-call screen with metadata, participants, history, and recordings for auditing and support. | | [Group Management](/ui-kit/ios/guide-group-chat) | Implement create/join, membership listing, role changes, bans, and structured group moderation actions. | | [Group Ownership Transfer](/ui-kit/ios/guide-group-ownership) | Allow admins to hand over group ownership securely to another member. | -| [Message Privately](/ui-kit/ios/guide-message-privately) | Launch a direct 1:1 conversation from a user profile or list; optionally seed with an initial message. | -| [New Chat](/ui-kit/ios/guide-new-chat) | Offer a unified entry to discover users & groups and jump into new conversations quickly. | +| [Message Privately](/ui-kit/ios/guide-message-privately) | Launch a direct 1:1 conversation from a group chat; streamlines side discussions without manual user searches. | +| [New Chat](/ui-kit/ios/guide-new-chat) | Offer a unified entry to discover users and groups and jump into new conversations quickly. | | [Threaded Messages](/ui-kit/ios/guide-threaded-messages) | Add threaded reply views so users can branch focused discussions off individual messages. | +## Related Resources + +- [Getting Started](/ui-kit/ios/getting-started) - Initial setup and configuration +- [Components Overview](/ui-kit/ios/components-overview) - All available UI components +- [Core Features](/ui-kit/ios/core-features) - Messaging, reactions, threads, and more + Need another guide? Request one via the [Developer Community](http://community.cometchat.com/) or Support. From 480d346bf92d9e93129cc4ac7fd236f0a7bc21d6 Mon Sep 17 00:00:00 2001 From: Aditya Date: Thu, 12 Feb 2026 17:07:25 +0530 Subject: [PATCH 010/106] modified guide-threaded-messages , incoming-call, ios-conversations --- ui-kit/ios/guide-threaded-messages.mdx | 236 ++++++++++++++++--------- ui-kit/ios/incoming-call.mdx | 236 ++++++++++++------------- ui-kit/ios/ios-conversation.mdx | 60 +++++-- 3 files changed, 307 insertions(+), 225 deletions(-) diff --git a/ui-kit/ios/guide-threaded-messages.mdx b/ui-kit/ios/guide-threaded-messages.mdx index a1cee6d7e..6086f40d4 100644 --- a/ui-kit/ios/guide-threaded-messages.mdx +++ b/ui-kit/ios/guide-threaded-messages.mdx @@ -1,153 +1,227 @@ --- title: "Threaded Messages" sidebarTitle: "Threaded Messages" +description: "Add threaded reply views to your iOS chat app" --- -Enhance your iOS chat app with threaded messaging by integrating CometChat’s **UIKit for iOS**, allowing users to reply to specific messages within a focused thread view. +Enhance your iOS chat app with threaded messaging by integrating CometChat's UIKit for iOS, allowing users to reply to specific messages within a focused thread view. ## Overview -Threaded messages allow users to reply to specific messages within a conversation, creating a sub-conversation for improved clarity and context. With CometChat’s UIKit for iOS, you can: +Threaded messages allow users to reply to specific messages within a conversation, creating a sub-conversation for improved clarity and context. With CometChat's UIKit for iOS, you can: -- Display a dedicated thread view. -- View and send replies to a selected message. -- Maintain context between the main conversation and the thread. +- Display a dedicated thread view +- View and send replies to a selected message +- Maintain context between the main conversation and the thread ## Prerequisites -- A working UIKit-based iOS project. -- CometChat UIKit for iOS v4+ installed via Swift Package Manager or CocoaPods. -- Valid CometChat **App ID**, **Region**, and **Auth Key**. -- A navigation controller configured in your project. +Before implementing threaded messages, ensure you have: + +- Completed [Getting Started](/ui-kit/ios/getting-started) setup +- CometChat UIKit v4+ installed via Swift Package Manager or CocoaPods +- Valid CometChat App ID, Region, and Auth Key +- A navigation controller configured in your project ## Components -| Component | Role | -|:----------------------------------|:-----------------------------------------------------------| -| `CometChatMessageList` | Displays messages and provides `onThreadRepliesClick` handler. | -| `CometChatThreadedMessageHeader` | Shows the parent message context at the top of the thread. | -| `CometChatMessageComposer` | Composes messages with an optional `parentMessageId`. | -| `ThreadedMessagesVC` | View controller that hosts the threaded conversation. | +| Component | Description | +|-----------|-------------| +| `CometChatMessageList` | Displays messages and provides `onThreadRepliesClick` handler | +| `CometChatThreadedMessageHeader` | Shows the parent message context at the top of the thread | +| `CometChatMessageComposer` | Composes messages with an optional `parentMessageId` | +| `ThreadedMessagesVC` | View controller that hosts the threaded conversation | ## Integration Steps -### Show the "Reply in Thread" Option +### Step 1: Show the "Reply in Thread" Option -Navigate to the thread when a message’s thread icon is tapped. +Navigate to the thread when a message's thread icon is tapped: ```swift -messageListView.set(onThreadRepliesClick: { [weak self] message, _ in - guard let self = self else { return } - let threadVC = ThreadedMessagesVC() - threadVC.parentMessage = message - self.navigationController?.pushViewController(threadVC, animated: true) -}) +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class MessagesViewController: UIViewController { + + var messageListView: CometChatMessageList! + + func setupThreadReplies() { + // Handle thread replies click + messageListView.set(onThreadRepliesClick: { [weak self] message, _ in + guard let self = self else { return } + + // Create and configure thread view controller + let threadVC = ThreadedMessagesVC() + threadVC.parentMessage = message + + // Navigate to thread screen + self.navigationController?.pushViewController(threadVC, animated: true) + }) + } +} ``` -**File reference:** -[`ThreadedMessagesVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/ThreadedMessagesVC.swift) - -Captures user intent and opens a focused thread screen. +This captures user intent and opens a focused thread screen. -### Navigate to the Thread Screen +**File reference:** [`ThreadedMessagesVC.swift`](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/SampleApp/View%20Controllers/CometChat%20Components/ThreadedMessagesVC.swift) -Show a dedicated UI for thread replies. +### Step 2: Navigate to the Thread Screen -In `ThreadedMessagesVC.swift`: +Show a dedicated UI for thread replies. In `ThreadedMessagesVC.swift`: ```swift -view.addSubview(parentMessageView) -view.addSubview(messageListView) -view.addSubview(composerView) +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ThreadedMessagesVC: UIViewController { + + var parentMessage: BaseMessage? + var user: User? + var group: Group? + + private var parentMessageContainerView: CometChatThreadedMessageHeader! + private var messageListView: CometChatMessageList! + private var composerView: CometChatMessageComposer! + + override func viewDidLoad() { + super.viewDidLoad() + setupUI() + } + + private func setupUI() { + // Add UI components to view hierarchy + view.addSubview(parentMessageView) + view.addSubview(messageListView) + view.addSubview(composerView) + } +} ``` -Header: +Header configuration: ```swift +// Create the threaded message header let parentMessageContainerView = CometChatThreadedMessageHeader() ``` -Message List: +Message list configuration: ```swift +// Configure message list with user and parent message messageListView.set(user: user, parentMessage: parentMessage) ``` -Provides a focused UI for thread interactions. +This provides a focused UI for thread interactions. -### Send a Threaded Message +### Step 3: Send a Threaded Message -Ensure new replies are attached to the correct parent message. +Ensure new replies are attached to the correct parent message: ```swift +// Set the parent message ID for threaded replies composerView.set(parentMessageId: parentMessage?.id ?? 0) ``` Set the conversation context: ```swift +// Configure composer for user conversation composerView.set(user: user) + +// Or configure for group conversation composerView.set(group: group) ``` -### Fetch & Display Thread Replies +### Step 4: Fetch and Display Thread Replies -Only messages that are part of the thread are displayed. - -Handled internally by: +Only messages that are part of the thread are displayed. This is handled internally by: ```swift +// Configure message list to fetch thread replies messageListView.set(user: user, parentMessage: parentMessage) ``` -Ensures `CometChatMessageList` fetches replies using the `parentMessageId`. +This ensures `CometChatMessageList` fetches replies using the `parentMessageId`. ## Customization Options -- **Header Styling:** Customize `CometChatThreadedMessageHeader` (fonts, colors, etc.). -- **Composer:** Modify placeholder text, input styles, and icons. -- **Navigation:** Add a custom `navigationItem.leftBarButtonItem` for back navigation. - -## Filtering / Edge Cases - -- **Parent Message Deleted:** Display a fallback UI or disable the composer. -- **No Replies:** Show an empty state (e.g., “No replies yet”). -- **Offline Mode:** Disable the composer and queue thread operations. - -## Error Handling & Edge Cases - -- **Fetch Failures:** Show an error UI or retry mechanism when loading thread messages. -- **Send Failures:** Handle send errors via delegate callbacks or show an alert with retry. -- **Loading States:** Display a `UIActivityIndicatorView` during fetch/send operations. -- **Blocked Users:** Remove the composer and display a blocked status label. - -## Summary / Feature Matrix +### Header Styling -| Feature | Implementation | -|:----------------------------|:------------------------------------------------------| -| Show thread option | `CometChatMessageList.onThreadRepliesClick` | -| Thread view screen | `ThreadedMessagesVC.swift` | -| Display threaded messages | `CometChatMessageList.set(parentMessage:)` | -| Send threaded message | `CometChatMessageComposer.set(parentMessageId:)` | -| Thread header | `CometChatThreadedMessageHeader` | -| Handle blocked user | Remove composer & show a blocked user label | +Customize `CometChatThreadedMessageHeader` appearance: - - - - -Explore a complete sample application demonstrating threaded messaging. +```swift +// Customize fonts, colors, and layout +let headerStyle = ThreadedMessageHeaderStyle() +headerStyle.titleFont = UIFont.systemFont(ofSize: 16, weight: .semibold) +headerStyle.titleColor = .label +parentMessageContainerView.set(style: headerStyle) +``` -[View on GitHub](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) +### Composer - +Modify placeholder text, input styles, and icons: - +```swift +// Customize composer appearance +composerView.set(placeholderText: "Reply in thread...") +``` -Browse the CometChat UIKit for iOS source code. +### Navigation -[View on GitHub](https://github.com/cometchat/cometchat-uikit-ios/tree/v5) +Add a custom back button for navigation: - +```swift +// Add custom back button +navigationItem.leftBarButtonItem = UIBarButtonItem( + image: UIImage(systemName: "chevron.left"), + style: .plain, + target: self, + action: #selector(goBack) +) +``` - \ No newline at end of file +## Edge Cases + +| Scenario | Handling | +|----------|----------| +| Parent message deleted | Display a fallback UI or disable the composer | +| No replies | Show an empty state (e.g., "No replies yet") | +| Offline mode | Disable the composer and queue thread operations | + +## Error Handling + +| Error Type | Solution | +|------------|----------| +| Fetch failures | Show an error UI or retry mechanism when loading thread messages | +| Send failures | Handle send errors via delegate callbacks or show an alert with retry | +| Loading states | Display a `UIActivityIndicatorView` during fetch/send operations | +| Blocked users | Remove the composer and display a blocked status label | + +## Feature Matrix + +| Feature | Implementation | +|---------|----------------| +| Show thread option | `CometChatMessageList.onThreadRepliesClick` | +| Thread view screen | `ThreadedMessagesVC.swift` | +| Display threaded messages | `CometChatMessageList.set(parentMessage:)` | +| Send threaded message | `CometChatMessageComposer.set(parentMessageId:)` | +| Thread header | `CometChatThreadedMessageHeader` | +| Handle blocked user | Remove composer and show a blocked user label | + +## Related Components + +- [Message List](/ui-kit/ios/message-list) - Display messages in conversations +- [Message Composer](/ui-kit/ios/message-composer) - Compose and send messages +- [Threaded Messages Header](/ui-kit/ios/threaded-messages-header) - Thread header component + + + + Explore a complete sample application demonstrating threaded messaging + + + Browse the CometChat UIKit for iOS source code + + diff --git a/ui-kit/ios/incoming-call.mdx b/ui-kit/ios/incoming-call.mdx index d3c3876e2..bcbf2a736 100644 --- a/ui-kit/ios/incoming-call.mdx +++ b/ui-kit/ios/incoming-call.mdx @@ -1,5 +1,6 @@ --- title: "Incoming Call" +description: "Display and handle incoming voice and video calls" --- ## Overview @@ -10,37 +11,36 @@ The `Incoming call` is a [Component](/ui-kit/ios/components-overview#components) -*** +--- ## Usage ### Integration -`CometChatIncomingCall` being a custom **view controller**, offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. +`CometChatIncomingCall` is a custom view controller that offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. ```swift +// Create and configure incoming call view controller let cometChatIncomingCall = CometChatIncomingCall().set(call: call) + +// Present full screen cometChatIncomingCall.modalPresentationStyle = .fullScreen self.present(cometChatIncomingCall, animated: true) ``` - - - If you are already using a navigation controller, you can use the `pushViewController` function instead of presenting the view controller. - ### Actions [Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. -##### 1. SetOnAcceptClick +#### 1. SetOnAcceptClick The `setOnAcceptClick` action is typically triggered when the user clicks on the accept button, initiating a predefined action. However, by implementing the following code snippet, you can easily customize or override this default behavior to suit your specific requirements. @@ -48,17 +48,14 @@ The `setOnAcceptClick` action is typically triggered when the user clicks on the ```swift let cometChatIncomingCall = CometChatIncomingCall() -.set(onAcceptClick: { call, controller in -//Perform Your Action - -}) + .set(onAcceptClick: { call, controller in + // Perform your custom action when call is accepted + }) ``` - - -##### 2. SetOnCancelClick +#### 2. SetOnCancelClick The `setOnCancelClick` action is typically triggered when the user clicks on the reject button, initiating a predefined action. However, by implementing the following code snippet, you can easily customize or override this default behavior to suit your specific requirements. @@ -66,118 +63,110 @@ The `setOnCancelClick` action is typically triggered when the user clicks on the ```swift let cometChatIncomingCall = CometChatIncomingCall() -.set(onCancelClick: { call, controller in - //Perform Your Action - -}) + .set(onCancelClick: { call, controller in + // Perform your custom action when call is rejected + }) ``` - - -##### 3. OnError +#### 3. OnError You can customize this behavior by using the provided code snippet to override the `On Error` and improve error handling. ```swift - let incomingCallConfiguration = IncomingCallConfiguration() -.set(onError:{ error in -//Perform Your Action - -}) + .set(onError: { error in + // Perform your custom error handling action + }) ``` - - -*** +--- ### Filters -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized experience. Filters can be applied using RequestBuilders of Chat SDK. The IncomingCall component does not have any exposed filters. -*** +--- ### Events -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. -Events emitted by the Incoming Call component is as follows. +Events emitted by the Incoming Call component are as follows: -| Event | Description | -| -------------------------- | -------------------------------------------------------------------------- | -| **onIncomingCallAccepted** | Triggers when the logged-in user accepts the incoming call. | -| **onIncomingCallRejected** | This event is triggered when the logged-in user rejects the incoming call. | -| **onCallEnded** | This event is triggered when the initiated call successfully ends. | +| Event | Description | +|-------|-------------| +| `onIncomingCallAccepted` | Triggers when the logged-in user accepts the incoming call | +| `onIncomingCallRejected` | Triggers when the logged-in user rejects the incoming call | +| `onCallEnded` | Triggers when the initiated call successfully ends | ```swift -// View controller from your project where you want to listen events. +// View controller from your project where you want to listen to events public class ViewController: UIViewController { - public override func viewDidLoad() { + public override func viewDidLoad() { super.viewDidLoad() - // Subscribing for the listener to listen events from user module + // Subscribe to call events CometChatCallEvents.addListener("UNIQUE_ID", self as CometChatCallEventListener) } - } - // Listener events from user module -extension ViewController: CometChatCallEventListener { + +// Listener events from call module +extension ViewController: CometChatCallEventListener { func onIncomingCallAccepted(call: Call) { - // Do Stuff + // Handle accepted call } - func onIncomingCallRejected(call: Call){ - // Do Stuff + + func onIncomingCallRejected(call: Call) { + // Handle rejected call } func onCallEnded(call: Call) { - // Do Stuff + // Handle ended call } } ``` -```swift Emitting Group Events -//emit this when logged in user accepts the incoming call +```swift +// Emitting Call Events + +// Emit when logged in user accepts the incoming call CometChatCallEvents.emitOnIncomingCallAccepted(call: Call) -//emit this when logged in user rejects the incoming call +// Emit when logged in user rejects the incoming call CometChatCallEvents.emitOnIncomingCallRejected(call: Call) -//emit this when logged in user cancels a call +// Emit when logged in user ends a call CometChatCallEvents.emitOnCallEnded(call: Call) ``` - - -*** +--- -```swift View Controller +```swift public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from user module - CometChatCallEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") + // Unsubscribe from call events + CometChatCallEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") } ``` - - -*** +--- ## Customization @@ -185,9 +174,9 @@ To fit your app's design requirements, you can customize the appearance of the c ### Style -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. -##### 1. IncomingCall Style +#### 1. IncomingCall Style You can customize the appearance of the `IncomingCall` Component by applying the `IncomingCallStyle` to it using the following code snippet. @@ -196,19 +185,19 @@ You can customize the appearance of the `IncomingCall` Component by applying the ```swift +// Create custom avatar style let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) - + +// Apply global incoming call styles CometChatIncomingCall.style.nameLabelFont = UIFont(name: "Times-New-Roman", size: 20) CometChatIncomingCall.style.callLabelFont = UIFont(name: "Times-New-Roman", size: 14) CometChatIncomingCall.style.acceptButtonCornerRadius = .init(cornerRadius: 8) CometChatIncomingCall.style.rejectButtonCornerRadius = .init(cornerRadius: 8) CometChatIncomingCall.avatarStyle = customAvatarStyle ``` - - **Instance level styling** @@ -216,65 +205,66 @@ CometChatIncomingCall.avatarStyle = customAvatarStyle ```swift +// Create custom avatar style var customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) - + +// Create custom incoming call style var incomingCallStyle = IncomingCallStyle() incomingCallStyle.nameLabelFont = UIFont(name: "Times-New-Roman", size: 20) incomingCallStyle.callLabelFont = UIFont(name: "Times-New-Roman", size: 14) incomingCallStyle.acceptButtonCornerRadius = .init(cornerRadius: 8) incomingCallStyle.rejectButtonCornerRadius = .init(cornerRadius: 8) - + +// Apply styles to instance let incomingCall = CometChatIncomingCall() incomingCall.style = incomingCallStyle incomingCall.avatarStyle = customAvatarStyle ``` - - -List of properties exposed by IncomingCallStyle - -| Property | Description | Code | -| ----------------------------- | --------------------------------------- | ------------------------------------------------- | -| `overlayBackgroundColor` | Background color for the overlay. | `overlayBackgroundColor: UIColor` | -| `acceptButtonBackgroundColor` | Background color for the accept button. | `acceptButtonBackgroundColor: UIColor` | -| `rejectButtonBackgroundColor` | Background color for the reject button. | `rejectButtonBackgroundColor: UIColor` | -| `acceptButtonTintColor` | Tint color for the accept button. | `acceptButtonTintColor: UIColor` | -| `rejectButtonTintColor` | Tint color for the reject button. | `rejectButtonTintColor: UIColor` | -| `acceptButtonImage` | Icon image for the accept button. | `acceptButtonImage: UIImage` | -| `rejectButtonImage` | Icon image for the reject button. | `rejectButtonImage: UIImage` | -| `acceptButtonCornerRadius` | Sets corner radius for accept button | `acceptButtonCornerRadius: CometChatCornerStyle?` | -| `rejectButtonCornerRadius` | Sets corner radius for reject button | `rejectButtonCornerRadius: CometChatCornerStyle?` | -| `acceptButtonBorderWidth` | Sets border width for accept button | `acceptButtonBorderWidth: CGFloat?` | -| `rejectButtonBorderWidth` | Sets border width for reject button | `rejectButtonBorderWidth: CGFloat?` | -| `acceptButtonBorderColor` | Sets border color for accept button | `acceptButtonBorderColor: UIColor?` | -| `rejectButtonBorderColor` | Sets border color for reject button | `rejectButtonBorderColor: UIColor?` | -| `backgroundColor` | Background color for the call view. | `backgroundColor: UIColor` | -| `cornerRadius` | Corner radius for the view. | `cornerRadius: nil` | -| `borderColor` | Border color for the view. | `borderColor: UIColor` | -| `borderWidth` | Border width for the view. | `borderWidth: CGFloat` | -| `callLabelColor` | Text color for the call label. | `callLabelColor: UIColor` | -| `callLabelFont` | Font for the call label. | `callLabelFont: UIFont` | -| `nameLabelColor` | Text color for the name label. | `nameLabelColor: UIColor` | -| `nameLabelFont` | Font for the name label. | `nameLabelFont: UIFont` | - -*** +List of properties exposed by IncomingCallStyle: + +| Property | Description | Code | +|----------|-------------|------| +| `overlayBackgroundColor` | Background color for the overlay | `overlayBackgroundColor: UIColor` | +| `acceptButtonBackgroundColor` | Background color for the accept button | `acceptButtonBackgroundColor: UIColor` | +| `rejectButtonBackgroundColor` | Background color for the reject button | `rejectButtonBackgroundColor: UIColor` | +| `acceptButtonTintColor` | Tint color for the accept button | `acceptButtonTintColor: UIColor` | +| `rejectButtonTintColor` | Tint color for the reject button | `rejectButtonTintColor: UIColor` | +| `acceptButtonImage` | Icon image for the accept button | `acceptButtonImage: UIImage` | +| `rejectButtonImage` | Icon image for the reject button | `rejectButtonImage: UIImage` | +| `acceptButtonCornerRadius` | Sets corner radius for accept button | `acceptButtonCornerRadius: CometChatCornerStyle?` | +| `rejectButtonCornerRadius` | Sets corner radius for reject button | `rejectButtonCornerRadius: CometChatCornerStyle?` | +| `acceptButtonBorderWidth` | Sets border width for accept button | `acceptButtonBorderWidth: CGFloat?` | +| `rejectButtonBorderWidth` | Sets border width for reject button | `rejectButtonBorderWidth: CGFloat?` | +| `acceptButtonBorderColor` | Sets border color for accept button | `acceptButtonBorderColor: UIColor?` | +| `rejectButtonBorderColor` | Sets border color for reject button | `rejectButtonBorderColor: UIColor?` | +| `backgroundColor` | Background color for the call view | `backgroundColor: UIColor` | +| `cornerRadius` | Corner radius for the view | `cornerRadius: nil` | +| `borderColor` | Border color for the view | `borderColor: UIColor` | +| `borderWidth` | Border width for the view | `borderWidth: CGFloat` | +| `callLabelColor` | Text color for the call label | `callLabelColor: UIColor` | +| `callLabelFont` | Font for the call label | `callLabelFont: UIFont` | +| `nameLabelColor` | Text color for the name label | `nameLabelColor: UIColor` | +| `nameLabelFont` | Font for the name label | `nameLabelFont: UIFont` | + +--- ### Functionality These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. -| Property | Description | Code | -| ---------------------- | --------------------------------------- | ------------------------------- | -| disableSoundForCalls | Disables sound for incoming calls. | `disableSoundForCalls = true` | -| setCustomSoundForCalls | Sets a custom sound for incoming calls. | `set(customSoundForCalls: URL)` | +| Property | Description | Code | +|----------|-------------|------| +| `disableSoundForCalls` | Disables sound for incoming calls | `disableSoundForCalls = true` | +| `setCustomSoundForCalls` | Sets a custom sound for incoming calls | `set(customSoundForCalls: URL)` | ### Advanced @@ -292,20 +282,18 @@ cometChatIncomingCall.set(listItemView: { call in return customView }) ``` - - -Demonstration +Demonstration: -You can create a CustomListItemView as a custom `UIView`. +You can create a CustomListItemView as a custom `UIView`: -```swift swift +```swift import UIKit class CustomListItemView: UIView { @@ -405,11 +393,11 @@ class CustomListItemView: UIView { } ``` -*** +--- #### SetLeadingView -You can modify the leading view of a Incoming call component using the property below. +You can modify the leading view of an Incoming call component using the property below. @@ -419,18 +407,16 @@ cometChatIncomingCall.set(leadingView: { call in return view }) ``` - - -Demonstration +Demonstration: -You can create a CustomLeadingView as a custom `UIView`. +You can create a CustomLeadingView as a custom `UIView`: @@ -453,7 +439,7 @@ class CustomLeadingView: UIView { label.text = "PRO USER" label.font = UIFont.boldSystemFont(ofSize: 14) label.textColor = .white - text.textAlignment = .center + label.textAlignment = .center return label }() @@ -489,16 +475,14 @@ class CustomLeadingView: UIView { } } ``` - - -*** +--- #### SetTitleView -You can customize the title view of a incoming call component using the property below. +You can customize the title view of an incoming call component using the property below. @@ -508,25 +492,23 @@ cometChatIncomingCall.set(titleView: { call in return view }) ``` - - -Demonstration +Demonstration: -You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()` +You can create a `CustomTitleView` as a custom `UIView` which we will inflate in `setTitleView()`: ```swift import UIKit -class `CustomTitleView`: UIView { +class CustomTitleView: UIView { private let titleLabel: UILabel = { let label = UILabel() @@ -597,9 +579,13 @@ class `CustomTitleView`: UIView { } } ``` - - -*** +--- + +## Related Components + +- [Outgoing Call](/ui-kit/ios/outgoing-call) - Display outgoing call interface +- [Ongoing Call](/ui-kit/ios/ongoing-call) - Display active call interface +- [Call Logs](/ui-kit/ios/call-logs) - Display call history diff --git a/ui-kit/ios/ios-conversation.mdx b/ui-kit/ios/ios-conversation.mdx index 6124c475c..1acf8462b 100644 --- a/ui-kit/ios/ios-conversation.mdx +++ b/ui-kit/ios/ios-conversation.mdx @@ -1,33 +1,36 @@ --- title: "Building A Conversation List + Message View" sidebarTitle: "Conversation List + Message View" +description: "Create a two-panel chat experience with conversation list and messages" --- -The **Conversation List + Message View** layout offers a modern two-panel chat experience. It's ideal for applications needing seamless switching between multiple conversations and chat windows—similar to **WhatsApp Web**, **Slack**, or **Microsoft Teams**. +The Conversation List + Message View layout offers a modern two-panel chat experience. It's ideal for applications needing seamless switching between multiple conversations and chat windows—similar to WhatsApp Web, Slack, or Microsoft Teams. -*** +--- -## **User Interface Preview** +## User Interface Preview -### **Key Components** +### Key Components -1. **Chat Header** – Displays user or group name, avatar, and back button. -2. **Message List** – Displays chat messages and real-time updates. -3. **Message Composer** – Allows sending of text, media, and reactions. +| Component | Description | +|-----------|-------------| +| Chat Header | Displays user or group name, avatar, and back button | +| Message List | Displays chat messages and real-time updates | +| Message Composer | Allows sending of text, media, and reactions | -*** +--- -## **Step-by-Step Guide** +## Step-by-Step Guide -### **Step 1: Setup SceneDelegate.swift** +### Step 1: Setup SceneDelegate.swift Ensure UIKit is initialized and the user is logged in before presenting the conversation view. -```swift SceneDelegate.swift highlight={15-17} lines +```swift import UIKit import CometChatUIKitSwift import CometChatSDK @@ -41,6 +44,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard let windowScene = (scene as? UIWindowScene) else { return } + // Configure UIKit settings with your credentials let uikitSettings = UIKitSettings() .set(appID: "<#Enter Your App ID Here#>") .set(region: "<#Enter Your Region Code Here#>") @@ -48,11 +52,13 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { .subscribePresenceForAllUsers() .build() + // Initialize CometChat UIKit CometChatUIKit.init(uiKitSettings: uikitSettings) { result in switch result { case .success: debugPrint("CometChatUIKit initialization succeeded") + // Login with a test user let uid = "cometchat-uid-1" CometChatUIKit.login(uid: uid) { loginResult in @@ -60,6 +66,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { case .success: debugPrint("CometChatUIKit login succeeded") + // Setup conversations view on main thread DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.setupConversationsView(windowScene: windowScene) @@ -78,16 +85,23 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } func setupConversationsView(windowScene: UIWindowScene) { + // Create conversations list view controller let conversationsVC = CometChatConversations() let navController = UINavigationController(rootViewController: conversationsVC) + // Handle conversation item click conversationsVC.set(onItemClick: { [weak navController] conversation, _ in let messagesVC = MessagesVC() + + // Set user or group based on conversation type messagesVC.group = conversation.conversationWith as? Group messagesVC.user = conversation.conversationWith as? CometChatSDK.User + + // Navigate to messages screen navController?.pushViewController(messagesVC, animated: true) }) + // Configure and display window window = UIWindow(windowScene: windowScene) window?.rootViewController = navController window?.makeKeyAndVisible() @@ -95,13 +109,13 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } ``` -*** +--- -### **Step 2: Create MessagesVC.swift** +### Step 2: Create MessagesVC.swift This view controller handles chat between users or within groups. -```swift MessagesVC.swift lines +```swift import UIKit import CometChatSDK import CometChatUIKitSwift @@ -123,12 +137,14 @@ class MessagesVC: UIViewController { private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { view.set(group: group) } + view.set(controller: self) return view }() @@ -137,12 +153,14 @@ class MessagesVC: UIViewController { private lazy var composerView: CometChatMessageComposer = { let composer = CometChatMessageComposer() composer.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { composer.set(user: user) } else if let group = group { composer.set(group: group) } + composer.set(controller: self) return composer }() @@ -151,12 +169,14 @@ class MessagesVC: UIViewController { private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { listView.set(group: group) } + listView.set(controller: self) return listView }() @@ -210,12 +230,14 @@ class MessagesVC: UIViewController { } ``` -*** +--- -## **Next Steps** +## Next Steps -### **Enhance the User Experience** +### Enhance the User Experience -* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. +- [Advanced Customizations](/ui-kit/ios/theme-introduction) — Personalize the chat UI to align with your brand +- [Core Features](/ui-kit/ios/core-features) — Explore messaging, reactions, threads, and more +- [Components Overview](/ui-kit/ios/components-overview) — Browse all available UI components -*** +--- From f1543dc75c5a6b223da5cb83db62e81ba29ee4b7 Mon Sep 17 00:00:00 2001 From: Aditya Date: Thu, 12 Feb 2026 17:56:39 +0530 Subject: [PATCH 011/106] modified one-to-one-chat, ios-tab-based-chat,localize --- ui-kit/ios/ios-one-to-one-chat.mdx | 63 ++++++---- ui-kit/ios/ios-tab-based-chat.mdx | 175 +++++++++++++++----------- ui-kit/ios/localize.mdx | 193 +++++++++++++++-------------- 3 files changed, 245 insertions(+), 186 deletions(-) diff --git a/ui-kit/ios/ios-one-to-one-chat.mdx b/ui-kit/ios/ios-one-to-one-chat.mdx index ae1c160d6..300f4a062 100644 --- a/ui-kit/ios/ios-one-to-one-chat.mdx +++ b/ui-kit/ios/ios-one-to-one-chat.mdx @@ -1,33 +1,36 @@ --- title: "Building A One To One/Group Chat Experience" sidebarTitle: "One To One/Group Chat" +description: "Create a direct messaging interface for private conversations" --- -The **One-to-One Chat** feature provides a streamlined **direct messaging interface**, making it ideal for **support chats, dating apps, and private messaging platforms**. This setup eliminates distractions by focusing solely on a **dedicated chat window**. +The One-to-One Chat feature provides a streamlined direct messaging interface, making it ideal for support chats, dating apps, and private messaging platforms. This setup eliminates distractions by focusing solely on a dedicated chat window. -*** +--- -## **User Interface Preview** +## User Interface Preview -### **Key Components** +### Key Components -1. **Chat Header** – Displays recipient details and optional call/video call buttons. -2. **Message View** – Shows real-time chat history. -3. **Message Input Box** – Enables users to send messages, media, and reactions. +| Component | Description | +|-----------|-------------| +| Chat Header | Displays recipient details and optional call/video call buttons | +| Message View | Shows real-time chat history | +| Message Input Box | Enables users to send messages, media, and reactions | -*** +--- -## **Step-by-Step Guide** +## Step-by-Step Guide -### **Step 1: Setup SceneDelegate.swift** +### Step 1: Setup SceneDelegate.swift Ensure UI Kit is initialized and the user is logged in before presenting the message view. -```swift SceneDelegate.swift highlight={15-17} lines +```swift import UIKit import CometChatUIKitSwift import CometChatSDK @@ -41,6 +44,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard let windowScene = (scene as? UIWindowScene) else { return } + // Configure UIKit settings with your credentials let uikitSettings = UIKitSettings() .set(appID: "<#Enter Your App ID Here#>") .set(region: "<#Enter Your Region Code Here#>") @@ -48,11 +52,13 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { .subscribePresenceForAllUsers() .build() + // Initialize CometChat UIKit CometChatUIKit.init(uiKitSettings: uikitSettings) { result in switch result { case .success: debugPrint("CometChat UI Kit initialization succeeded") + // Login with a test user let uid = "cometchat-uid-1" CometChatUIKit.login(uid: uid) { loginResult in @@ -60,6 +66,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { case .success: debugPrint("CometChat UI Kit login succeeded") + // Setup one-on-one conversation on main thread DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.setUpOneOneOrGroupConversation(windowScene: windowScene, uid: "cometchat-uid-2") @@ -77,33 +84,35 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } } - func setUpOneOneOrGroupConversation(windowScene: UIWindowScene, uid : String) { + func setUpOneOneOrGroupConversation(windowScene: UIWindowScene, uid: String) { + // Fetch the user to chat with CometChat.getUser(UID: uid) { user in DispatchQueue.main.async { + // Create messages view controller let messagesVC = MessagesVC() let navController = UINavigationController(rootViewController: messagesVC) messagesVC.user = user + + // Configure and display window self.window = UIWindow(windowScene: windowScene) self.window?.rootViewController = navController self.window?.makeKeyAndVisible() } } onError: { error in - + // Handle error } - } - } ``` -*** +--- -### **Step 2: Create MessagesVC.swift** +### Step 2: Create MessagesVC.swift This view controller handles chat between users or within groups. -```swift MessagesVC.swift lines +```swift import UIKit import CometChatSDK import CometChatUIKitSwift @@ -125,12 +134,14 @@ class MessagesVC: UIViewController { private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { view.set(group: group) } + view.set(controller: self) return view }() @@ -139,12 +150,14 @@ class MessagesVC: UIViewController { private lazy var composerView: CometChatMessageComposer = { let composer = CometChatMessageComposer() composer.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { composer.set(user: user) } else if let group = group { composer.set(group: group) } + composer.set(controller: self) return composer }() @@ -153,12 +166,14 @@ class MessagesVC: UIViewController { private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { listView.set(group: group) } + listView.set(controller: self) return listView }() @@ -212,12 +227,14 @@ class MessagesVC: UIViewController { } ``` -*** +--- -## **Next Steps** +## Next Steps -### **Enhance the User Experience** +### Enhance the User Experience -* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. +- [Advanced Customizations](/ui-kit/ios/theme-introduction) — Personalize the chat UI to align with your brand +- [Core Features](/ui-kit/ios/core-features) — Explore messaging, reactions, threads, and more +- [Components Overview](/ui-kit/ios/components-overview) — Browse all available UI components -*** +--- diff --git a/ui-kit/ios/ios-tab-based-chat.mdx b/ui-kit/ios/ios-tab-based-chat.mdx index 8c6d7b047..7b953306b 100644 --- a/ui-kit/ios/ios-tab-based-chat.mdx +++ b/ui-kit/ios/ios-tab-based-chat.mdx @@ -1,77 +1,100 @@ --- title: "Building A Tab Based Messaging UI In iOS" sidebarTitle: "Tab Based Chat Experience" +description: "Create a complete tab-based messaging interface with Chats, Calls, Users, and Groups tabs using CometChat UI Kit for iOS" --- This guide walks you through creating a **tab-based messaging interface** in your **iOS application** using **CometChat UI Kit for iOS**. The UI includes tabs for **Chats**, **Calls**, **Users**, and **Groups**, offering an organized and fluid experience. -*** +--- -## **User Interface Preview** +## User Interface Preview -This layout contains: +### Tab Layout Overview -1. **Conversations** – Lists all recent chats. -2. **Calls** – Displays call logs. -3. **Users** – Lists available users. -4. **Groups** – Lists available groups. +| Tab | Component | Description | +|-----|-----------|-------------| +| Chats | `CometChatConversations` | Lists all recent conversations | +| Calls | `CometChatCallLogs` | Displays call history and logs | +| Users | `CometChatUsers` | Lists available users to chat with | +| Groups | `CometChatGroups` | Lists available groups to join | -*** +--- -## **Step-by-Step Guide** +## Step-by-Step Guide -### **Step 1: Initialize UIKit in `SceneDelegate.swift`** +### Step 1: Initialize UIKit in SceneDelegate.swift Ensure UIKit is initialized and the user is logged in before presenting the tabbed view. -```swift SceneDelegate.swift highlight={5-7} lines -func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - guard let windowScene = (scene as? UIWindowScene) else { return } - - let uikitSettings = UIKitSettings() - .set(appID: "<#Enter Your App ID Here#>") - .set(region: "<#Enter Your Region Code Here#>") - .set(authKey: "<#Enter Your AuthKey Here#>") - .subscribePresenceForAllUsers() - .build() - - CometChatUIKit.init(uiKitSettings: uikitSettings) { result in - switch result { - case .success: - CometChatUIKit.login(uid: "cometchat-uid-1") { loginResult in - switch loginResult { - case .success: - DispatchQueue.main.async { - self.setupTabbedView(windowScene: windowScene) +```swift SceneDelegate.swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class SceneDelegate: UIResponder, UIWindowSceneDelegate { + + var window: UIWindow? + + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + guard let windowScene = (scene as? UIWindowScene) else { return } + + // Configure UIKit settings with your credentials + let uikitSettings = UIKitSettings() + .set(appID: "<#Enter Your App ID Here#>") + .set(region: "<#Enter Your Region Code Here#>") + .set(authKey: "<#Enter Your AuthKey Here#>") + .subscribePresenceForAllUsers() + .build() + + // Initialize CometChat UIKit + CometChatUIKit.init(uiKitSettings: uikitSettings) { result in + switch result { + case .success: + debugPrint("CometChat UI Kit initialization succeeded") + + // Login with a test user + CometChatUIKit.login(uid: "cometchat-uid-1") { loginResult in + switch loginResult { + case .success: + debugPrint("CometChat UI Kit login succeeded") + + // Setup tabbed view on main thread + DispatchQueue.main.async { + self.setupTabbedView(windowScene: windowScene) + } + + case .onError(let error): + debugPrint("Login failed: \(error.description)") + @unknown default: break } - default: - break } + + case .failure(let error): + debugPrint("Initialization failed: \(error.localizedDescription)") } - default: - break } } } ``` -*** +--- -### **Step 2: Setup Tab Bar** +### Step 2: Setup Tab Bar Controller -Create a method to display the tab layout. +Create a method to configure and display the tab layout with all four tabs. -```swift SceneDelegate.swift lines +```swift SceneDelegate.swift func setupTabbedView(windowScene: UIWindowScene) { // Create the main Tab Bar Controller let tabBarController = UITabBarController() tabBarController.tabBar.backgroundColor = .white - + // MARK: - Conversations Tab let conversationsVC = CometChatConversations() let conversationsNav = UINavigationController(rootViewController: conversationsVC) @@ -80,8 +103,8 @@ func setupTabbedView(windowScene: UIWindowScene) { image: UIImage(systemName: "message.fill"), tag: 0 ) - - // Handle item click inside conversation list + + // Handle conversation item tap to open messages conversationsVC.set(onItemClick: { [weak conversationsNav] conversation, indexPath in let messagesVC = MessagesVC() messagesVC.group = conversation.conversationWith as? Group @@ -89,7 +112,7 @@ func setupTabbedView(windowScene: UIWindowScene) { messagesVC.hidesBottomBarWhenPushed = true conversationsNav?.pushViewController(messagesVC, animated: true) }) - + // MARK: - Call Logs Tab let callLogsVC = CometChatCallLogs() let callLogsNav = UINavigationController(rootViewController: callLogsVC) @@ -98,7 +121,7 @@ func setupTabbedView(windowScene: UIWindowScene) { image: UIImage(systemName: "phone.fill"), tag: 1 ) - + // MARK: - Users Tab let usersVC = CometChatUsers() let usersNav = UINavigationController(rootViewController: usersVC) @@ -107,7 +130,7 @@ func setupTabbedView(windowScene: UIWindowScene) { image: UIImage(systemName: "person.2.fill"), tag: 2 ) - + // MARK: - Groups Tab let groupsVC = CometChatGroups() let groupsNav = UINavigationController(rootViewController: groupsVC) @@ -116,7 +139,7 @@ func setupTabbedView(windowScene: UIWindowScene) { image: UIImage(systemName: "person.3.fill"), tag: 3 ) - + // Assign all navigation controllers to the Tab Bar tabBarController.viewControllers = [ conversationsNav, @@ -124,110 +147,115 @@ func setupTabbedView(windowScene: UIWindowScene) { usersNav, groupsNav ] - + // Ensures layout includes space for opaque bars like the navigation bar tabBarController.extendedLayoutIncludesOpaqueBars = true - + // Setup and display main window with tabBarController as root window = UIWindow(windowScene: windowScene) window?.rootViewController = tabBarController window?.makeKeyAndVisible() - } ``` -*** +--- -### **Step 3: Create `MessagesVC.swift`** +### Step 3: Create MessagesVC.swift -This view controller handles chat between users or within groups. +This view controller handles chat between users or within groups when a conversation is selected. -```swift MessagesVC.swift lines +```swift MessagesVC.swift import UIKit import CometChatSDK import CometChatUIKitSwift /// A view controller that displays a chat interface using CometChat components class MessagesVC: UIViewController { - + // MARK: - Properties - + /// The user entity for one-on-one chats var user: User? - + /// The group entity for group chats var group: Group? - + // MARK: - UI Components - + /// Header view displaying user/group information private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { view.set(group: group) } + view.set(controller: self) return view }() - + /// Message input composer view private lazy var composerView: CometChatMessageComposer = { let composer = CometChatMessageComposer() composer.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { composer.set(user: user) } else if let group = group { composer.set(group: group) } + composer.set(controller: self) return composer }() - + /// List view displaying chat messages private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false + // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { listView.set(group: group) } + listView.set(controller: self) return listView }() - + // MARK: - Lifecycle Methods - + override func viewDidLoad() { super.viewDidLoad() configureView() setupLayout() } - + override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } - + // MARK: - Private Methods - + /// Configure basic view properties private func configureView() { view.backgroundColor = .systemBackground navigationController?.setNavigationBarHidden(true, animated: false) } - + /// Set up view hierarchy and constraints private func setupLayout() { // Add subviews to the view hierarchy [headerView, messageListView, composerView].forEach { view.addSubview($0) } - + // Set up constraints NSLayoutConstraint.activate([ // Header view constraints @@ -235,13 +263,13 @@ class MessagesVC: UIViewController { headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), headerView.heightAnchor.constraint(equalToConstant: 50), - + // Message list view constraints messageListView.topAnchor.constraint(equalTo: headerView.bottomAnchor), messageListView.leadingAnchor.constraint(equalTo: view.leadingAnchor), messageListView.trailingAnchor.constraint(equalTo: view.trailingAnchor), messageListView.bottomAnchor.constraint(equalTo: composerView.topAnchor), - + // Composer view constraints composerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), composerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), @@ -251,12 +279,13 @@ class MessagesVC: UIViewController { } ``` -*** - -## **Next Steps** +--- -### **Enhance the User Experience** +## Next Steps -* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. +- [One To One/Group Chat](/ui-kit/ios/ios-one-to-one-chat) — Build a focused direct messaging interface +- [Conversation List + Messages](/ui-kit/ios/ios-conversation) — Create a split-view chat experience +- [Theme Introduction](/ui-kit/ios/theme-introduction) — Customize the chat UI to match your brand +- [Components Overview](/ui-kit/ios/components-overview) — Explore all available UI components -*** +--- diff --git a/ui-kit/ios/localize.mdx b/ui-kit/ios/localize.mdx index af5cc2617..af0ef6c2a 100644 --- a/ui-kit/ios/localize.mdx +++ b/ui-kit/ios/localize.mdx @@ -1,73 +1,66 @@ --- title: "Localize" +sidebarTitle: "Localization" +description: "Adapt CometChat UI Kit to different languages and customize date/time formatting for your iOS application" --- ## Overview -CometChat UI Kit provides language localization to adapt to the language of a specific country or region. The CometChatLocalize class allows you to detect the language of your users based on their browser or device settings, and set the language accordingly. - -CometChatLocalize is a class that includes methods related to locale. Developers can use these methods to change the language of the UI Kit library. - -Presently, the UI Kit supports 17 languages for localization, which are: - -- English (en, en-US) -- English-UK (en-GB) -- Chinese (zh, zh-TW) -- Spanish (es) -- Hindi (hi) -- Russian (ru) -- Portuguese (pt) -- Malay (ms) -- French (fr) -- German (de) -- Swedish (sv) -- Lithuanian (lt) -- Hungarian (hu) -- Dutch (nl) -- Japanese (ja) -- Korean (ko) -- Turkish (tr) +CometChat UI Kit provides language localization to adapt to the language of a specific country or region. The `CometChatLocalize` class allows you to detect the language of your users based on their browser or device settings, and set the language accordingly. + +`CometChatLocalize` is a class that includes methods related to locale. Developers can use these methods to change the language of the UI Kit library. + +### Supported Languages + +The UI Kit supports 17 languages for localization: + +| Language | Code | Language | Code | +|----------|------|----------|------| +| English | `en`, `en-US` | Japanese | `ja` | +| English-UK | `en-GB` | Korean | `ko` | +| Chinese | `zh`, `zh-TW` | Turkish | `tr` | +| Spanish | `es` | Malay | `ms` | +| Hindi | `hi` | Swedish | `sv` | +| Russian | `ru` | Lithuanian | `lt` | +| Portuguese | `pt` | Hungarian | `hu` | +| French | `fr` | Dutch | `nl` | +| German | `de` | | | --- -### How Localization Works +## How Localization Works Localization in the SDK is powered by: -1. The **CometChatLocalize** class — for setting and fetching the active locale. -2. A **String** extension method called `.localize` — to fetch localized text dynamically. - -#### Example: +1. The `CometChatLocalize` class — for setting and fetching the active locale +2. A `String` extension method called `.localize` — to fetch localized text dynamically ```swift +// Example: Localizing a string key "CHATS".localize ``` The SDK checks the following bundles in order: -1. The app's Localizable.strings (for developer-defined overrides) +1. The app's `Localizable.strings` (for developer-defined overrides) 2. The SDK's built-in localization files 3. Fallback to English or the original key if no match is found --- -### Methods +## Methods -Here are the methods included in the CometChatLocalize class: - -| **Method** | **Description** | -|---------------------------------|------------------------------------------------------| -| **set(locale:)** | Sets the language using Language enum (.english, .french, etc.) | -| **getLocale()** | Returns the currently active locale. By default, it will return the current language from the device/browser. | +The `CometChatLocalize` class provides the following methods: +| Method | Description | +|--------|-------------| +| `set(locale:)` | Sets the language using Language enum (`.english`, `.french`, etc.) | +| `getLocale()` | Returns the currently active locale. By default, returns the current language from the device/browser | ### Usage -Here is how you can put these methods into use: - - - + ```swift // Set Language to French CometChatLocalize.set(locale: .french) @@ -80,14 +73,12 @@ let lang = CometChatLocalize.getLocale() --- -### App-Level Overrides +## App-Level Overrides -To customize any text used by the SDK, simply define the same key in your app’s Localizable.strings files. +To customize any text used by the SDK, simply define the same key in your app's `Localizable.strings` files. -Example – Localizable.strings (en.lproj): - - + ```swift "CHATS" = "Conversations"; "USERS" = "People"; @@ -95,36 +86,44 @@ Example – Localizable.strings (en.lproj): -When your app runs, this will override the SDK’s built-in translation for "CHATS" and "USERS" wherever they are used via .localize. +When your app runs, this will override the SDK's built-in translation for "CHATS" and "USERS" wherever they are used via `.localize`. No additional configuration is needed. --- -### How to discover available keys +## How to Discover Available Keys All localization keys used by the SDK are available in our [GitHub repository](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/CometChatUIKitSwift/Components/Shared/Resources). This allows you to: -* Know exactly which keys are used -* Provide custom translations for them in your app -* Keep your localization files in sync with SDK updates +- Know exactly which keys are used +- Provide custom translations for them in your app +- Keep your localization files in sync with SDK updates -By using the CometChatLocalize class, you can provide a user-friendly, localized experience to your users, enhancing the overall user experience within your application. +By using the `CometChatLocalize` class, you can provide a user-friendly, localized experience to your users, enhancing the overall user experience within your application. + +--- ## Customization -CometChatUIKit for iOS allows developers to customize localization values easily. For example, if an English-language app requires the label "Chat" to be shown as "Chats," the developer can simply define the same localization key used in the UIKit inside the app's English localization file and assign it a different value. CometChatUIKit will automatically detect and use the overridden value from the app-level localization. +CometChatUIKit for iOS allows developers to customize localization values easily. For example, if an English-language app requires the label "Chat" to be shown as "Chats," the developer can simply define the same localization key used in the UIKit inside the app's English localization file and assign it a different value. CometChatUIKit will automatically detect and use the overridden value from the app-level localization. ### Steps to Customize Strings -1. Identify the String Key - - Check the UIKit source code for the exact key of the string you want to modify. [Localization file](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Resources/en.lproj/Localizable.strings). -2. Navigate to the app level localization file for that same langauge - - Added the same key with the changed vale you whant value. -3. Build and Run Your App - - The changes will automatically reflect wherever the key is used. + +1. **Identify the String Key** + - Check the UIKit source code for the exact key of the string you want to modify: [Localization file](https://github.com/cometchat/cometchat-uikit-ios/blob/v5/CometChatUIKitSwift/Components/Shared/Resources/en.lproj/Localizable.strings) + +2. **Navigate to the App Level Localization File** + - Add the same key with the changed value you want + +3. **Build and Run Your App** + - The changes will automatically reflect wherever the key is used + +--- ## DateTimeFormatter -This feature allows developers to customize how date and time values are displayed across the CometChat UI Kit components. It introduces the CometChatDateTimeFormatter class, enabling tailored formatting for strings such as "Today", "Yesterday", or time formats like "12:00 PM". + +This feature allows developers to customize how date and time values are displayed across the CometChat UI Kit components. It introduces the `CometChatDateTimeFormatter` class, enabling tailored formatting for strings such as "Today", "Yesterday", or time formats like "12:00 PM". Custom formats can be set based on locale, branding, or user preferences, enhancing localization and UX consistency. @@ -144,33 +143,35 @@ This system uses closures that you can override to provide your own custom strin `CometChatDateTimeFormatter` is a configuration class that exposes customizable closures for various time-related strings. Developers can assign custom behavior to each closure based on their desired formatting logic. -#### Available closures +#### Available Closures -| Property | Description | Code | -|---------------------------------------|--------------------------------------------------------------------------|---------------------------------------------------------| -| time | Called to format a timestamp as a standard time (e.g., "12:30 PM"). | `CometChatUIKit.dateTimeFormatter.time = { ... }` | -| today | Called when rendering messages sent today. | `CometChatUIKit.dateTimeFormatter.today = { ... }` | -| yesterday | Called for yesterday's messages. | `CometChatUIKit.dateTimeFormatter.yesterday = { ... }` | -| lastweek | Called for messages within the last week. | `CometChatUIKit.dateTimeFormatter.lastweek = { ... }` | -| otherDay | Called for dates older than last week. | `CometChatUIKit.dateTimeFormatter.otherDay = { ... }` | -| minute | Called when referring to "a minute ago". | `CometChatUIKit.dateTimeFormatter.minute = { ... }` | -| minutes | Called for "x minutes ago". | `CometChatUIKit.dateTimeFormatter.minutes = { ... }` | -| hour | Called for "an hour ago". | `CometChatUIKit.dateTimeFormatter.hour = { ... }` | -| hours | Called for "x hours ago". | `CometChatUIKit.dateTimeFormatter.hours = { ... }` | +| Property | Description | Code | +|----------|-------------|------| +| `time` | Called to format a timestamp as a standard time (e.g., "12:30 PM") | `CometChatUIKit.dateTimeFormatter.time = { ... }` | +| `today` | Called when rendering messages sent today | `CometChatUIKit.dateTimeFormatter.today = { ... }` | +| `yesterday` | Called for yesterday's messages | `CometChatUIKit.dateTimeFormatter.yesterday = { ... }` | +| `lastweek` | Called for messages within the last week | `CometChatUIKit.dateTimeFormatter.lastweek = { ... }` | +| `otherDay` | Called for dates older than last week | `CometChatUIKit.dateTimeFormatter.otherDay = { ... }` | +| `minute` | Called when referring to "a minute ago" | `CometChatUIKit.dateTimeFormatter.minute = { ... }` | +| `minutes` | Called for "x minutes ago" | `CometChatUIKit.dateTimeFormatter.minutes = { ... }` | +| `hour` | Called for "an hour ago" | `CometChatUIKit.dateTimeFormatter.hour = { ... }` | +| `hours` | Called for "x hours ago" | `CometChatUIKit.dateTimeFormatter.hours = { ... }` | -Each closure receives a timestamp (Int, representing UNIX time) and must return a String representing the formatted time. +Each closure receives a timestamp (`Int`, representing UNIX time) and must return a `String` representing the formatted time. --- -#### Integration Options +### Integration Options The formatter can be applied at three levels: -1. **Global Level**: A global formatter is available via `CometChatUIKit.dateTimeFormatter`. Use this to apply formatting across all components in the `CometChatUIKit`. +#### 1. Global Level + +A global formatter is available via `CometChatUIKit.dateTimeFormatter`. Use this to apply formatting across all components in the `CometChatUIKit`. -```swift +```swift CometChatUIKit.dateTimeFormatter.hour = { timestamp in return "Today" } @@ -179,16 +180,16 @@ CometChatUIKit.dateTimeFormatter.time = { timestamp in return "12:00 PM" } ``` - - -2. **Component Global Level**: Each component has a static formatter that overrides the global formatter only for that component across all instances. +#### 2. Component Global Level + +Each component has a static formatter that overrides the global formatter only for that component across all instances. -```swift +```swift CometChatMessageList.dateTimeFormatter.hour = { timestamp in return "Today" } @@ -197,15 +198,16 @@ CometChatMessageList.dateTimeFormatter.time = { timestamp in return "12:00 PM" } ``` - -3. **Local Component Level**: Components also expose an instance-level formatter for per-instance customization. This provides the highest precedence. +#### 3. Local Component Level + +Components also expose an instance-level formatter for per-instance customization. This provides the highest precedence. -```swift +```swift let messageList = CometChatMessageList() messageList.set(user: user) @@ -217,19 +219,30 @@ messageList.dateTimeFormatter.time = { timestamp in return "12:00 PM" } ``` - +--- + ### Component-Level Date-Time Formatting Options -The following components support dateTimeFormatter: +The following components support `dateTimeFormatter`: -* [CometChatConversations](/ui-kit/ios/conversations#date-time-formatter) -* [CometChatMessageList](/ui-kit/ios/message-list#date-time-formatter) -* [CometChatCallLogs](/ui-kit/ios/call-logs#date-time-formatter) -* [CometChatMessageHeader](/ui-kit/ios/message-header#date-time-formatter) +- [CometChatConversations](/ui-kit/ios/conversations#date-time-formatter) +- [CometChatMessageList](/ui-kit/ios/message-list#date-time-formatter) +- [CometChatCallLogs](/ui-kit/ios/call-logs#date-time-formatter) +- [CometChatMessageHeader](/ui-kit/ios/message-header#date-time-formatter) -Each of these components checks the most relevant closure in CometChatDateTimeFormatter based on the timestamp and context. +Each of these components checks the most relevant closure in `CometChatDateTimeFormatter` based on the timestamp and context. -The `CometChatDateTimeFormatter` gives developers fine-grained control over how date and time appear throughout their app. Whether you’re customizing for locale, branding, or clarity, this system ensures your app’s time formatting is as user-friendly and context-aware as possible. +The `CometChatDateTimeFormatter` gives developers fine-grained control over how date and time appear throughout their app. Whether you're customizing for locale, branding, or clarity, this system ensures your app's time formatting is as user-friendly and context-aware as possible. + +--- + +## Next Steps + +- [Theme Introduction](/ui-kit/ios/theme-introduction) — Customize the visual appearance of UI components +- [Color Resources](/ui-kit/ios/color-resources) — Configure color schemes for your app +- [Component Styling](/ui-kit/ios/component-styling) — Apply custom styles to individual components + +--- From 267b3d170b5999295c01617bbe37c750af2e6487 Mon Sep 17 00:00:00 2001 From: Aditya Date: Thu, 12 Feb 2026 19:00:01 +0530 Subject: [PATCH 012/106] modified mentions-formatter , message-bubble-styling , message-composer --- ui-kit/ios/mentions-formatter-guide.mdx | 127 ++++--- ui-kit/ios/message-bubble-styling.mdx | 148 +++++--- ui-kit/ios/message-composer.mdx | 477 ++++++++++++------------ 3 files changed, 405 insertions(+), 347 deletions(-) diff --git a/ui-kit/ios/mentions-formatter-guide.mdx b/ui-kit/ios/mentions-formatter-guide.mdx index 8f623bdc7..6c500d5cb 100644 --- a/ui-kit/ios/mentions-formatter-guide.mdx +++ b/ui-kit/ios/mentions-formatter-guide.mdx @@ -1,18 +1,24 @@ --- title: "Mentions Formatter" +sidebarTitle: "Mentions Formatter" +description: "Format and customize @mentions within text messages using CometChat UI Kit for iOS" --- ## Overview -The `CometChatMentionsFormatter` class is a part of the CometChat UI Kit, a ready-to-use chat UI component library for integrating CometChat into your iOS applications. This class provides functionality to format mentions within text messages displayed in the chat interface. Mentions allow users to reference other users within a conversation, providing a convenient way to direct messages or involve specific participants. +The `CometChatMentionsFormatter` class is part of the CometChat UI Kit, a ready-to-use chat UI component library for integrating CometChat into your iOS applications. This class provides functionality to format mentions within text messages displayed in the chat interface. Mentions allow users to reference other users within a conversation, providing a convenient way to direct messages or involve specific participants. + +--- ## Features -* **Mention Formatting**: Automatically formats mentions within text messages based on provided styles and settings. -* **Customizable Styles**: Allows customization of text styles for mentions, including colors, fonts, and background colors. -* **User and Group Member Mentions**: Supports mentions for both individual users and group members, providing flexibility in communication scenarios. -* **Mention List Generation**: Generates a list of suggested mentions based on user input, facilitating easy selection of recipients during message composition. -* **Mention Click Handling**: Provides a listener interface for handling click events on mentions, enabling custom actions to be performed when a mention is tapped by the user. +- **Mention Formatting**: Automatically formats mentions within text messages based on provided styles and settings +- **Customizable Styles**: Allows customization of text styles for mentions, including colors, fonts, and background colors +- **User and Group Member Mentions**: Supports mentions for both individual users and group members, providing flexibility in communication scenarios +- **Mention List Generation**: Generates a list of suggested mentions based on user input, facilitating easy selection of recipients during message composition +- **Mention Click Handling**: Provides a listener interface for handling click events on mentions, enabling custom actions to be performed when a mention is tapped by the user + +--- ## Usage @@ -20,39 +26,39 @@ To integrate the `CometChatMentionsFormatter` class into your application: 1. **Initialization**: Create an instance of the `CometChatMentionsFormatter` class and configure it with desired settings, such as mention text styles and limit settings. -2. **Set Mention Listeners**: Set listeners for handling mention click events (`.setonMentionCLicked`). +2. **Set Mention Listeners**: Set listeners for handling mention click events (`.setOnMentionClicked`). 3. **Format Messages**: Use the `.set(leftBubbleTextStyle)`, `.set(rightBubbleTextStyle)`, `.set(composerTextStyle)`, and `.set(conversationListTextStyle)` methods to format text messages with mentions appropriately for display in the chat interface. 4. **Customization**: Customize the appearance and behavior of mentions by adjusting the text styles, colors, and other formatting properties as needed. -`CometChatMentionsFormatter` can directly be initialised, tweak using its properties and passed into different configurations. +`CometChatMentionsFormatter` can be directly initialized, tweaked using its properties, and passed into different configurations. -Below is an example demonstrating how to use the `CometChatMentionsFormatter` class in components such as [CometChatConversations](/ui-kit/ios/conversations), [CometChatMessageList](/ui-kit/ios/message-list), [CometChatMessageComposer](/ui-kit/ios/message-composer). +Below is an example demonstrating how to use the `CometChatMentionsFormatter` class in components such as [CometChatConversations](/ui-kit/ios/conversations), [CometChatMessageList](/ui-kit/ios/message-list), and [CometChatMessageComposer](/ui-kit/ios/message-composer). ```swift +// Create a custom mention formatter instance let customMentionFormatter = CometChatMentionsFormatter() +// Apply the formatter to a message list let messageListView = CometChatMessageList() messageListView.set(textFormatters: [customMentionFormatter]) ``` - - +--- + ## Actions [Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. -##### setOnMentionClick +### setOnMentionClick Setting a listener for mention-click events in Message Bubbles enhances interactivity within the chat. This listener is activated when a mention is clicked, returning the corresponding user object. This feature transforms mentions into interactive links, enabling more in-depth and contextual engagement with the user associated with the clicked mention. -**Example** - @@ -60,22 +66,32 @@ Setting a listener for mention-click events in Message Bubbles enhances interact ```swift +// Set up mention click handler let customMentionFormatter = CometChatMentionsFormatter() customMentionFormatter.set { message, tappedText, controller in + // Display the name of the first mentioned user controller?.view.showToastMessage(message: "\(message.mentionedUsers.first?.name)") } ``` - - -The following code snippet represents a UIView extension used to display `showToastMessage`. +The following code snippet represents a UIView extension used to display `showToastMessage`: -```swift Swift + + +```swift extension UIView { - func showToastMessage(message : String) { - let toastLabel = UILabel(frame: CGRect(x: self.frame.size.width/2 - 100, y: self.frame.size.height-120, width: 200, height: 35)) + func showToastMessage(message: String) { + // Create toast label with centered positioning + let toastLabel = UILabel(frame: CGRect( + x: self.frame.size.width/2 - 100, + y: self.frame.size.height - 120, + width: 200, + height: 35 + )) + + // Configure toast appearance toastLabel.backgroundColor = UIColor.black toastLabel.textColor = UIColor.white toastLabel.textAlignment = .center @@ -83,35 +99,42 @@ extension UIView { toastLabel.alpha = 2.0 toastLabel.layer.cornerRadius = 13 toastLabel.clipsToBounds = true + self.addSubview(toastLabel) + + // Animate fade out and remove UIView.animate(withDuration: 4.0, delay: 0.4, options: .curveEaseOut, animations: { toastLabel.alpha = 0.0 - }, completion: {(isCompleted) in + }, completion: { isCompleted in toastLabel.removeFromSuperview() }) } } ``` + + + +--- ## Customization -| Methods | Description | Code | -| ----------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------- | -| **Set Conversation List TextStyle** | Use to set stying for conversation list's formatted text. | `MentionTextStyle` | -| **Set GroupMembersRequestBuilder** | Sets the builder for fetching group members. | `GroupMembersRequest.GroupMembersRequestBuilder?` | -| **Set UsersRequestBuilder** | Sets the builder for fetching users. | `UsersRequest.UsersRequestBuilder?` | -| **Set OnMentionCLick** | Sets a listener for mention click in Message Bubbles events. | `((_ baseMessage: BaseMessage, _ tappedText: String, _ controller: UIViewController?)->())` | -| **Set composerTextStyle** | Use to set stying for composer's formatted text. | `MentionTextStyle` | +| Method | Description | Type | +|--------|-------------|------| +| **Set Conversation List TextStyle** | Sets styling for conversation list's formatted text | `MentionTextStyle` | +| **Set GroupMembersRequestBuilder** | Sets the builder for fetching group members | `GroupMembersRequest.GroupMembersRequestBuilder?` | +| **Set UsersRequestBuilder** | Sets the builder for fetching users | `UsersRequest.UsersRequestBuilder?` | +| **Set OnMentionClick** | Sets a listener for mention click events in Message Bubbles | `((_ baseMessage: BaseMessage, _ tappedText: String, _ controller: UIViewController?)->())` | +| **Set composerTextStyle** | Sets styling for composer's formatted text | `MentionTextStyle` | -## Advance +--- -For advanced-level customization, you can set the style of the Mentions formatters. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your formatters style. +## Advanced -### Composer Mention Text Style +For advanced-level customization, you can set the style of the Mentions formatters. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own formatter styles. -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel for [CometChatMessageComposer](/ui-kit/ios/message-composer) refer to the below code snippet +### Composer Mention Text Style -**Example** +Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel for [CometChatMessageComposer](/ui-kit/ios/message-composer), refer to the code snippet below. @@ -120,21 +143,19 @@ Assigns the list of text formatters. If the provided list is not null, it sets t ```swift +// Create and configure composer mention style let composerMentionStyle = MentionTextStyle() composerMentionStyle.textColor = UIColor(hex: "#30A46C") - + +// Apply the style globally CometChatMentionsFormatter.composerTextStyle = composerMentionStyle ``` - - ### Message Bubble Mention Text Style -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel for [CometChatMessageList](/ui-kit/ios/message-list) - -**Example** +Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel for [CometChatMessageList](/ui-kit/ios/message-list), refer to the code snippet below. @@ -143,26 +164,22 @@ Assigns the list of text formatters. If the provided list is not null, it sets t ```swift +// Configure left bubble (incoming) mention style var leftBubbleMentionsStyle = MentionTextStyle() leftBubbleMentionsStyle.textColor = UIColor(hex: "#D6409F") - CometChatMentionsFormatter.leftBubbleTextStyle = leftBubbleMentionsStyle - + +// Configure right bubble (outgoing) mention style var rightBubbleMentionsStyle = MentionTextStyle() rightBubbleMentionsStyle.textColor = UIColor(hex: "#30A46C") - CometChatMentionsFormatter.rightBubbleTextStyle = rightBubbleMentionsStyle ``` - - ### Conversations Mention Text Style -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel for [CometChatConversations](/ui-kit/ios/conversations) - -**Example** +Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel for [CometChatConversations](/ui-kit/ios/conversations), refer to the code snippet below. @@ -171,12 +188,22 @@ Assigns the list of text formatters. If the provided list is not null, it sets t ```swift +// Create and configure conversation list mention style let mentionsStyle = MentionTextStyle() mentionsStyle.textColor = UIColor(hex: "#30A46C") - + +// Apply the style globally CometChatMentionsFormatter.conversationListTextStyle = mentionsStyle ``` - - + +--- + +## Next Steps + +- [Message Composer](/ui-kit/ios/message-composer) — Learn about the message input component +- [Message List](/ui-kit/ios/message-list) — Display and customize chat messages +- [Conversations](/ui-kit/ios/conversations) — Manage conversation lists + +--- diff --git a/ui-kit/ios/message-bubble-styling.mdx b/ui-kit/ios/message-bubble-styling.mdx index b4be2c467..f4ba87a39 100644 --- a/ui-kit/ios/message-bubble-styling.mdx +++ b/ui-kit/ios/message-bubble-styling.mdx @@ -1,5 +1,7 @@ --- title: "Message Bubble Styling" +sidebarTitle: "Message Bubble Styling" +description: "Customize the appearance of incoming and outgoing message bubbles in CometChat UI Kit for iOS" --- ## Overview @@ -8,80 +10,88 @@ The MessageBubble styling API allows developers to customize the appearance of i There are two primary classes for styling message bubbles: -* **CometChat Incoming Message Bubble Style** -* **CometChat Outgoing Message Bubble Style** +- **CometChat Incoming Message Bubble Style** +- **CometChat Outgoing Message Bubble Style** Both classes provide properties for customizing background color, border, corner radius, and specific styles for individual message types. -### Properties +--- + +## Properties -**Global Styling (Static Variables)** +### Global Styling (Static Variables) -* **backgroundColor:** The background color for message bubbles. -* **backgroundDrawable:** A background image for message bubbles. -* **borderWidth:** The width of the border for message bubbles. -* **borderColor:** The color of the border for message bubbles. -* **cornerRadius:** The corner radius for message bubbles. +| Property | Description | +|----------|-------------| +| **backgroundColor** | The background color for message bubbles | +| **backgroundDrawable** | A background image for message bubbles | +| **borderWidth** | The width of the border for message bubbles | +| **borderColor** | The color of the border for message bubbles | +| **cornerRadius** | The corner radius for message bubbles | -**Specific Message Type Styles:** +### Specific Message Type Styles -* **textBubbleStyle:** Style for text message bubbles. -* **imageBubbleStyle:** Style for image message bubbles. -* **videoBubbleStyle:** Style for video message bubbles. -* **audioBubbleStyle:** Style for audio message bubbles. -* **fileBubbleStyle:** Style for file message bubbles. -* **documentBubbleStyle:** Style for document message bubbles. +| Property | Description | +|----------|-------------| +| **textBubbleStyle** | Style for text message bubbles | +| **imageBubbleStyle** | Style for image message bubbles | +| **videoBubbleStyle** | Style for video message bubbles | +| **audioBubbleStyle** | Style for audio message bubbles | +| **fileBubbleStyle** | Style for file message bubbles | +| **documentBubbleStyle** | Style for document message bubbles | + +--- ## Customization Examples ### Customizing Incoming Message Bubble -The following code snippet shows how customize the incoming message bubble style: +The following code snippet shows how to customize the incoming message bubble style: ```swift +// Customize incoming message bubble appearance CometChatMessageBubble.style.incoming.backgroundColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.incoming.borderWidth = 2 CometChatMessageBubble.style.incoming.borderColor = UIColor.black ``` - - ### Customizing Outgoing Message Bubble -The following code snippet shows how customize the outgoing message bubble style: +The following code snippet shows how to customize the outgoing message bubble style: ```swift +// Customize outgoing message bubble appearance CometChatMessageBubble.style.outgoing.backgroundColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.outgoing.borderWidth = 2 CometChatMessageBubble.style.outgoing.borderColor = UIColor.black ``` - - +--- + ## Text Bubble Text bubbles display plain text messages, which are the most common message type. -The following code snippet shows how customize the text message bubble: +The following code snippet shows how to customize the text message bubble: ```swift +// Customize text bubble for incoming messages CometChatMessageBubble.style.incoming.textBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") +// Customize text bubble for outgoing messages CometChatMessageBubble.style.outgoing.textBubbleStyle.backgroundColor = UIColor(hexString: "#F76808") ``` - - **Default** @@ -96,22 +106,24 @@ CometChatMessageBubble.style.outgoing.textBubbleStyle.backgroundColor = UIColor( +--- + ## Image Bubble Image bubbles display messages with images. -The following code snippet shows how customize the Image message bubble: +The following code snippet shows how to customize the image message bubble: ```swift +// Customize image bubble for incoming messages CometChatMessageBubble.style.incoming.imageBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") +// Customize image bubble for outgoing messages CometChatMessageBubble.style.outgoing.imageBubbleStyle.backgroundColor = UIColor(hexString: "#F76808") ``` - - **Default** @@ -126,24 +138,26 @@ CometChatMessageBubble.style.outgoing.imageBubbleStyle.backgroundColor = UIColor +--- + ## Video Bubble Video bubbles display messages with video clips. -The following code snippet shows how customize the Video message bubble: +The following code snippet shows how to customize the video message bubble: ```swift +// Customize video bubble for incoming messages CometChatMessageBubble.style.incoming.videoBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") CometChatMessageBubble.style.incoming.videoBubbleStyle.playButtonTint = UIColor(hexString: "#F76808") - + +// Customize video bubble for outgoing messages CometChatMessageBubble.style.outgoing.deleteBubbleStyle.backgroundColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.outgoing.videoBubbleStyle.playButtonTint = UIColor(hexString: "#F76808") ``` - - **Default** @@ -158,25 +172,27 @@ CometChatMessageBubble.style.outgoing.videoBubbleStyle.playButtonTint = UIColor( +--- + ## Audio Bubble -Audio bubbles display Audio messages. +Audio bubbles display audio messages. -The following code snippet shows how customize the Audio message bubble: +The following code snippet shows how to customize the audio message bubble: ```swift +// Customize audio bubble for incoming messages CometChatMessageBubble.style.incoming.audioBubbleStyle.audioWaveFormTintColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.incoming.audioBubbleStyle.playImageTintColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.incoming.audioBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") +// Customize audio bubble for outgoing messages CometChatMessageBubble.style.outgoing.audioBubbleStyle.playImageTintColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.outgoing.audioBubbleStyle.backgroundColor = UIColor(hexString: "#F76808") ``` - - **Default** @@ -191,24 +207,26 @@ CometChatMessageBubble.style.outgoing.audioBubbleStyle.backgroundColor = UIColor +--- + ## Poll Bubble -Poll bubbles display messages with polling. +Poll bubbles display messages with polling options. -The following code snippet shows how customize the Poll message bubble: +The following code snippet shows how to customize the poll message bubble: ```swift +// Customize poll bubble for incoming messages CometChatMessageBubble.style.incoming.pollBubbleStyle.optionProgressTintColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.incoming.pollBubbleStyle.selectedPollImageTint = UIColor(hexString: "#F76808") CometChatMessageBubble.style.incoming.pollBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") - + +// Customize poll bubble for outgoing messages CometChatMessageBubble.style.outgoing.pollBubbleStyle.backgroundColor = UIColor(hexString: "#F76808") ``` - - **Default** @@ -223,22 +241,24 @@ CometChatMessageBubble.style.outgoing.pollBubbleStyle.backgroundColor = UIColor( +--- + ## Link Preview Bubble -The Link Preview Bubble is designed to display a preview of links shared in messages. It enriches the messaging experience by showing details such as the page title, description, and an image from the linked content, making links more engaging and informative. +The Link Preview Bubble displays a preview of links shared in messages. It enriches the messaging experience by showing details such as the page title, description, and an image from the linked content, making links more engaging and informative. -The following code snippet shows how customize the Link preview message bubble: +The following code snippet shows how to customize the link preview message bubble: ```swift +// Customize link preview bubble for incoming messages CometChatMessageBubble.style.incoming.linkPreviewBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") - + +// Customize link preview bubble for outgoing messages CometChatMessageBubble.style.outgoing.linkPreviewBubbleStyle.backgroundColor = UIColor(hexString: "#F76808") ``` - - **Default** @@ -253,22 +273,23 @@ CometChatMessageBubble.style.outgoing.linkPreviewBubbleStyle.backgroundColor = U +--- + ## Action Bubble Action bubbles provide a customizable interface for displaying a variety of actions, such as group actions, within a chat. -The following code snippet shows how customize the action message bubble: +The following code snippet shows how to customize the action message bubble: ```swift +// Customize action bubble appearance CometChatMessageBubble.actionBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") CometChatMessageBubble.actionBubbleStyle.bubbleTextColor = UIColor(hexString: "#F76808") CometChatMessageBubble.actionBubbleStyle.borderColor = UIColor(hexString: "#F76808") ``` - - **Default** @@ -283,22 +304,24 @@ CometChatMessageBubble.actionBubbleStyle.borderColor = UIColor(hexString: "#F768 +--- + ## Delete Bubble -Delete bubbles displays messages that have been deleted by the sender. These indicate the message removal within the chat interface. +Delete bubbles display messages that have been deleted by the sender. These indicate the message removal within the chat interface. -The following code snippet shows how customize the delete message bubble: +The following code snippet shows how to customize the delete message bubble: ```swift +// Customize delete bubble for incoming messages CometChatMessageBubble.style.incoming.deleteBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") +// Customize delete bubble for outgoing messages CometChatMessageBubble.style.outgoing.deleteBubbleStyle.backgroundColor = UIColor(hexString: "#F76808") ``` - - **Default** @@ -313,25 +336,26 @@ CometChatMessageBubble.style.outgoing.deleteBubbleStyle.backgroundColor = UIColo +--- -## AIAssistantBubble +## AI Assistant Bubble The AI Assistant Bubble displays responses or messages sent by the AI assistant within the chat interface. These bubbles are designed to visually distinguish AI-generated messages from user messages, maintaining a clear and intuitive conversation flow. -You can customize the appearance of the AI Assistant message bubble to match your app’s theme — including background color, text color, font, and border styling. +You can customize the appearance of the AI Assistant message bubble to match your app's theme — including background color, text color, font, and border styling. The following code snippet shows how to customize the AI Assistant message bubble: ```swift +// Customize AI assistant bubble for incoming messages CometChatMessageBubble.style.incoming.aiAssistantBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") +// Customize AI assistant bubble for outgoing messages CometChatMessageBubble.style.outgoing.aiAssistantBubbleStyle.backgroundColor = UIColor(hexString: "#F76808") ``` - - **Default** @@ -345,3 +369,13 @@ CometChatMessageBubble.style.outgoing.aiAssistantBubbleStyle.backgroundColor = U + +--- + +## Next Steps + +- [Message List](/ui-kit/ios/message-list) — Display and customize the message list component +- [Message Composer](/ui-kit/ios/message-composer) — Customize the message input component +- [Component Styling](/ui-kit/ios/component-styling) — Learn about global styling options + +--- diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index c49a79373..3a07fdfcc 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -1,5 +1,7 @@ --- title: "Message Composer" +sidebarTitle: "Message Composer" +description: "Enable users to write and send text, media, and custom messages using CometChat UI Kit for iOS" --- ## Overview @@ -12,65 +14,62 @@ MessageComposer is a [Component](/ui-kit/ios/components-overview#components) tha MessageComposer is comprised of the following [Base Components](/ui-kit/ios/components-overview#base-components): -| Base Components | Description | -| ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| [MessageInput](/ui-kit/ios/message-input) | This provides a basic layout for the contents of this component, such as the TextField and buttons | -| [ActionSheet](/ui-kit/ios/action-sheet) | The ActionSheet component presents a list of options in either a list or grid mode, depending on the user's preference | +| Base Components | Description | +|-----------------|-------------| +| [MessageInput](/ui-kit/ios/message-input) | Provides a basic layout for the contents of this component, such as the TextField and buttons | +| [ActionSheet](/ui-kit/ios/action-sheet) | Presents a list of options in either a list or grid mode, depending on the user's preference | + +--- ## Usage ### Integration -The following code snippet illustrates how you can directly incorporate the MessageComposer component into your file. +The following code snippet illustrates how you can directly incorporate the MessageComposer component into your application: -```csharp -// syntax for set(user: User) +```swift +// Create and configure the message composer let messageComposer = CometChatMessageComposer() messageComposer.set(user: user) messageComposer.set(parentMessageId: 20) ``` +--- + ### Actions [Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. -##### 1. onSendButtonClick +#### 1. onSendButtonClick -The `set(onSendButtonClick:)` event gets activated when the send message button is clicked. The following code snippet Overrides the action of the send button in CometChatMessageComposer. +The `set(onSendButtonClick:)` event gets activated when the send message button is clicked. The following code snippet overrides the action of the send button in CometChatMessageComposer. ```swift messageComposer.set(onSendButtonClick: { message in -// return custom action here + // Handle custom send action here }) ``` - - -*** +#### 2. OnTextChanged -##### 2. OnTextChanged: - -The `set(onTextChanged:)` event gets activated when the user starts typing in message composer. This will return the text entered by the user. +The `set(onTextChanged:)` event gets activated when the user starts typing in the message composer. This returns the text entered by the user. ```swift -messageComposer.set(onTextChanged: { error in - // Handle action +messageComposer.set(onTextChanged: { text in + // Handle text change action }) ``` - - -*** -##### 3. SetOnError +#### 3. SetOnError This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatMessageComposer. @@ -78,29 +77,27 @@ This method proves helpful when a user needs to customize the action taken upon ```swift messageComposer.set(onError { error in - // Override on error + // Handle error }) ``` - - -*** +--- ### Filters MessageComposer component does not have any available filters. -*** +--- ### Events -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using events you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. The MessageComposer Component does not emit any events of its own. -*** +--- ## Customization @@ -108,9 +105,9 @@ To fit your app's design requirements, you can customize the appearance of the M ### Style -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. -##### 1. MessageComposer Style +#### 1. MessageComposer Style To customize the styling, you can apply the `MessageComposerStyle` to the `MessageComposer` component. @@ -125,9 +122,7 @@ CometChatMessageComposer.style.voiceRecordingImageTint = UIColor(hex: "#F76808") CometChatMessageComposer.style.stickerTint = UIColor(hex: "#F76808") CometChatMessageComposer.style.aiImageTint = UIColor(hex: "#F76808") ``` - - **Instance level styling** @@ -135,75 +130,77 @@ CometChatMessageComposer.style.aiImageTint = UIColor(hex: "#F76808") ```swift +// Create custom composer style let customComposerStyle = MessageComposerStyle() customComposerStyle.activeSendButtonImageBackgroundColor = UIColor(hex: "#F76808") customComposerStyle.attachmentImageTint = UIColor(hex: "#F76808") customComposerStyle.voiceRecordingImageTint = UIColor(hex: "#F76808") customComposerStyle.stickerTint = UIColor(hex: "#F76808") customComposerStyle.aiImageTint = UIColor(hex: "#F76808") - + +// Apply to message composer instance let messageComposer = CometChatMessageComposer() messageComposer.style = customComposerStyle ``` - - + The following properties are exposed by MessageComposerStyle: -| **Property** | **Description** | **Code** | -| ----------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | -| **Placeholder Text Font** | Font for the placeholder text in the input field. | `CometChatMessageComposer.style.placeHolderTextFont = CometChatTypography.Body.regular` | -| **Placeholder Text Color** | Color for the placeholder text in the input field. | `CometChatMessageComposer.style.placeHolderTextColor = CometChatTheme.textColorTertiary` | -| **Text Field Color** | Text color for the input field. | `CometChatMessageComposer.style.textFiledColor = CometChatTheme.textColorPrimary` | -| **Text Field Font** | Font for the input field text. | `CometChatMessageComposer.style.textFiledFont = CometChatTypography.Body.regular` | -| **Background Color** | Background color with dynamic support for light and dark mode. | `CometChatMessageComposer.style.backgroundColor = UIColor.dynamicColor(lightModeColor: ..., darkModeColor: ...)` | -| **Corner Radius** | Corner radius for the composer. | `CometChatMessageComposer.style.cornerRadius = CometChatCornerStyle?` | -| **Border Width** | Border width for the composer. | `CometChatMessageComposer.style.borderWidth = 0` | -| **Border Color** | Border color for the composer. | `CometChatMessageComposer.style.borderColor = .clear` | -| **Send Button Image** | Icon for the send button. | `CometChatMessageComposer.style.sendButtonImage = UIImage(named: "custom-send")` | -| **Send Button Tint Color** | Tint color for the send button image. | `CometChatMessageComposer.style.sendButtonImageTint = CometChatTheme.white` | -| **Active Send Button Background Color** | Background color for the send button when active. | `CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = CometChatTheme.primaryColor` | -| **Inactive Send Button Background Color** | Background color for the send button when inactive. | `CometChatMessageComposer.style.inactiveSendButtonImageBackgroundColor = CometChatTheme.neutralColor300` | -| **Compose Box Background Color** | Background color for the compose box. | `CometChatMessageComposer.style.composeBoxBackgroundColor = CometChatTheme.backgroundColor01` | -| **Compose Box Border Color** | Border color for the compose box. | `CometChatMessageComposer.style.composeBoxBorderColor = CometChatTheme.borderColorDefault` | -| **Compose Box Border Width** | Border width for the compose box. | `CometChatMessageComposer.style.composeBoxBorderWidth = 1` | -| **Compose Box Corner Radius** | Corner radius for the compose box. | `CometChatMessageComposer.style.composerBoxCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r2)` | -| **Compose Box Separator Color** | Color for the separator in the compose box. | `CometChatMessageComposer.style.composerSeparatorColor = CometChatTheme.borderColorLight` | -| **Attachment Image** | Icon for the attachment button. | `CometChatMessageComposer.style.attachmentImage = UIImage(systemName: "plus.circle")` | -| **Attachment Image Tint** | Tint color for the attachment image. | `CometChatMessageComposer.style.attachmentImageTint = CometChatTheme.iconColorSecondary` | -| **Voice Recording Image** | Icon for the voice recording button. | `CometChatMessageComposer.style.voiceRecordingImage = UIImage(systemName: "mic")?.withRenderingMode(.alwaysTemplate)` | -| **Voice Recording Image Tint** | Tint color for the voice recording image. | `CometChatMessageComposer.style.voiceRecordingImageTint = CometChatTheme.iconColorSecondary` | -| **AI Image** | Icon for the AI button. | `CometChatMessageComposer.style.aiImage = UIImage(named: "ai-image")` | -| **AI Image Tint** | Tint color for the AI image. | `CometChatMessageComposer.style.aiImageTint = CometChatTheme.iconColorSecondary` | -| **Sticker Image** | Icon for the sticker button. | `CometChatMessageComposer.style.stickerImage = UIImage(named: "sticker-image")` | -| **Sticker Image Tint** | Tint color for the sticker image. | `CometChatMessageComposer.style.stickerTint = CometChatTheme.iconColorSecondary` | -| **Edit Preview Title Font** | Font for the title in the edit preview. | `CometChatMessageComposer.style.editPreviewTitleTextFont = CometChatTypography.Body.regular` | -| **Edit Preview Message Font** | Font for the message text in the edit preview. | `CometChatMessageComposer.style.editPreviewMessageTextFont = CometChatTypography.Caption1.regular` | -| **Edit Preview Title Color** | Text color for the title in the edit preview. | `CometChatMessageComposer.style.editPreviewTitleTextColor = CometChatTheme.textColorPrimary` | -| **Edit Preview Message Color** | Text color for the message in the edit preview. | `CometChatMessageComposer.style.editPreviewMessageTextColor = CometChatTheme.textColorSecondary` | -| **Edit Preview Background Color** | Background color for the edit preview. | `CometChatMessageComposer.style.editPreviewBackgroundColor = CometChatTheme.backgroundColor03` | -| **Edit Preview Corner Radius** | Corner radius for the edit preview. | `CometChatMessageComposer.style.editPreviewCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r1)` | -| **Edit Preview Border Color** | Border color for the edit preview. | `CometChatMessageComposer.style.editPreviewBorderColor = .clear` | -| **Edit Preview Border Width** | Border width for the edit preview. | `CometChatMessageComposer.style.editPreviewBorderWidth = 0` | -| **Edit Preview Close Icon** | Icon for closing the edit preview. | `CometChatMessageComposer.style.editPreviewCloseIcon = UIImage(systemName: "xmark")?.withRenderingMode(.alwaysTemplate)` | -| **Edit Preview Close Icon Tint** | Tint color for the close icon in the edit preview. | `CometChatMessageComposer.style.editPreviewCloseIconTint = CometChatTheme.iconColorPrimary` | -| **Info Icon** | Icon for the info button. | `CometChatMessageComposer.style.infoIcon = UIImage(systemName: "info.circle")` | -| **Info Icon Tint** | Tint color for the info icon. | `CometChatMessageComposer.style.infoIconTint = CometChatTheme.errorColor` | -| **Info Text Color** | Text color for the info text. | `CometChatMessageComposer.style.infoTextColor = CometChatTheme.errorColor` | -| **Info Text Font** | Font for the info text. | `CometChatMessageComposer.style.infoTextFont = CometChatTypography.Caption1.regular` | -| **Info Separator Color** | Color for the separator in the info section. | `CometChatMessageComposer.style.infoSeparatorColor = CometChatTheme.borderColorLight` | -| **Info Background Color** | Background color for the info section. | `CometChatMessageComposer.style.infoBackgroundColor = CometChatTheme.backgroundColor02` | -| **Info Corner Radius** | Corner radius for the info section. | `CometChatMessageComposer.style.infoCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r1)` | -| **Info Border Color** | Border color for the info section. | `CometChatMessageComposer.style.infoBorderColor = .clear` | -| **Info Border Width** | Border width for the info section. | `CometChatMessageComposer.style.infoBorderWidth = 0` | - -##### 2. MediaRecorder Style +| Property | Description | Code | +|----------|-------------|------| +| **Placeholder Text Font** | Font for the placeholder text in the input field | `CometChatMessageComposer.style.placeHolderTextFont = CometChatTypography.Body.regular` | +| **Placeholder Text Color** | Color for the placeholder text in the input field | `CometChatMessageComposer.style.placeHolderTextColor = CometChatTheme.textColorTertiary` | +| **Text Field Color** | Text color for the input field | `CometChatMessageComposer.style.textFiledColor = CometChatTheme.textColorPrimary` | +| **Text Field Font** | Font for the input field text | `CometChatMessageComposer.style.textFiledFont = CometChatTypography.Body.regular` | +| **Background Color** | Background color with dynamic support for light and dark mode | `CometChatMessageComposer.style.backgroundColor = UIColor.dynamicColor(lightModeColor: ..., darkModeColor: ...)` | +| **Corner Radius** | Corner radius for the composer | `CometChatMessageComposer.style.cornerRadius = CometChatCornerStyle?` | +| **Border Width** | Border width for the composer | `CometChatMessageComposer.style.borderWidth = 0` | +| **Border Color** | Border color for the composer | `CometChatMessageComposer.style.borderColor = .clear` | +| **Send Button Image** | Icon for the send button | `CometChatMessageComposer.style.sendButtonImage = UIImage(named: "custom-send")` | +| **Send Button Tint Color** | Tint color for the send button image | `CometChatMessageComposer.style.sendButtonImageTint = CometChatTheme.white` | +| **Active Send Button Background Color** | Background color for the send button when active | `CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = CometChatTheme.primaryColor` | +| **Inactive Send Button Background Color** | Background color for the send button when inactive | `CometChatMessageComposer.style.inactiveSendButtonImageBackgroundColor = CometChatTheme.neutralColor300` | +| **Compose Box Background Color** | Background color for the compose box | `CometChatMessageComposer.style.composeBoxBackgroundColor = CometChatTheme.backgroundColor01` | +| **Compose Box Border Color** | Border color for the compose box | `CometChatMessageComposer.style.composeBoxBorderColor = CometChatTheme.borderColorDefault` | +| **Compose Box Border Width** | Border width for the compose box | `CometChatMessageComposer.style.composeBoxBorderWidth = 1` | +| **Compose Box Corner Radius** | Corner radius for the compose box | `CometChatMessageComposer.style.composerBoxCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r2)` | +| **Compose Box Separator Color** | Color for the separator in the compose box | `CometChatMessageComposer.style.composerSeparatorColor = CometChatTheme.borderColorLight` | +| **Attachment Image** | Icon for the attachment button | `CometChatMessageComposer.style.attachmentImage = UIImage(systemName: "plus.circle")` | +| **Attachment Image Tint** | Tint color for the attachment image | `CometChatMessageComposer.style.attachmentImageTint = CometChatTheme.iconColorSecondary` | +| **Voice Recording Image** | Icon for the voice recording button | `CometChatMessageComposer.style.voiceRecordingImage = UIImage(systemName: "mic")?.withRenderingMode(.alwaysTemplate)` | +| **Voice Recording Image Tint** | Tint color for the voice recording image | `CometChatMessageComposer.style.voiceRecordingImageTint = CometChatTheme.iconColorSecondary` | +| **AI Image** | Icon for the AI button | `CometChatMessageComposer.style.aiImage = UIImage(named: "ai-image")` | +| **AI Image Tint** | Tint color for the AI image | `CometChatMessageComposer.style.aiImageTint = CometChatTheme.iconColorSecondary` | +| **Sticker Image** | Icon for the sticker button | `CometChatMessageComposer.style.stickerImage = UIImage(named: "sticker-image")` | +| **Sticker Image Tint** | Tint color for the sticker image | `CometChatMessageComposer.style.stickerTint = CometChatTheme.iconColorSecondary` | +| **Edit Preview Title Font** | Font for the title in the edit preview | `CometChatMessageComposer.style.editPreviewTitleTextFont = CometChatTypography.Body.regular` | +| **Edit Preview Message Font** | Font for the message text in the edit preview | `CometChatMessageComposer.style.editPreviewMessageTextFont = CometChatTypography.Caption1.regular` | +| **Edit Preview Title Color** | Text color for the title in the edit preview | `CometChatMessageComposer.style.editPreviewTitleTextColor = CometChatTheme.textColorPrimary` | +| **Edit Preview Message Color** | Text color for the message in the edit preview | `CometChatMessageComposer.style.editPreviewMessageTextColor = CometChatTheme.textColorSecondary` | +| **Edit Preview Background Color** | Background color for the edit preview | `CometChatMessageComposer.style.editPreviewBackgroundColor = CometChatTheme.backgroundColor03` | +| **Edit Preview Corner Radius** | Corner radius for the edit preview | `CometChatMessageComposer.style.editPreviewCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r1)` | +| **Edit Preview Border Color** | Border color for the edit preview | `CometChatMessageComposer.style.editPreviewBorderColor = .clear` | +| **Edit Preview Border Width** | Border width for the edit preview | `CometChatMessageComposer.style.editPreviewBorderWidth = 0` | +| **Edit Preview Close Icon** | Icon for closing the edit preview | `CometChatMessageComposer.style.editPreviewCloseIcon = UIImage(systemName: "xmark")?.withRenderingMode(.alwaysTemplate)` | +| **Edit Preview Close Icon Tint** | Tint color for the close icon in the edit preview | `CometChatMessageComposer.style.editPreviewCloseIconTint = CometChatTheme.iconColorPrimary` | +| **Info Icon** | Icon for the info button | `CometChatMessageComposer.style.infoIcon = UIImage(systemName: "info.circle")` | +| **Info Icon Tint** | Tint color for the info icon | `CometChatMessageComposer.style.infoIconTint = CometChatTheme.errorColor` | +| **Info Text Color** | Text color for the info text | `CometChatMessageComposer.style.infoTextColor = CometChatTheme.errorColor` | +| **Info Text Font** | Font for the info text | `CometChatMessageComposer.style.infoTextFont = CometChatTypography.Caption1.regular` | +| **Info Separator Color** | Color for the separator in the info section | `CometChatMessageComposer.style.infoSeparatorColor = CometChatTheme.borderColorLight` | +| **Info Background Color** | Background color for the info section | `CometChatMessageComposer.style.infoBackgroundColor = CometChatTheme.backgroundColor02` | +| **Info Corner Radius** | Corner radius for the info section | `CometChatMessageComposer.style.infoCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r1)` | +| **Info Border Color** | Border color for the info section | `CometChatMessageComposer.style.infoBorderColor = .clear` | +| **Info Border Width** | Border width for the info section | `CometChatMessageComposer.style.infoBorderWidth = 0` | + + +#### 2. MediaRecorder Style To customize the media recording styling, you can apply the `MediaRecorderStyle` to the `MessageComposer` component. For more details, please refer to [MediaRecorder](/ui-kit/ios/component-styling#media-recorder) styles. @@ -218,9 +215,7 @@ CometChatMessageComposer.mediaRecorderStyle.stopButtonCornerRadius = .init(corne CometChatMessageComposer.mediaRecorderStyle.recordingButtonCornerRadius = .init(cornerRadius: 8) CometChatMessageComposer.mediaRecorderStyle.recordingButtonBackgroundColor = UIColor(hex: "#F44649") ``` - - **Instance level styling** @@ -228,6 +223,7 @@ CometChatMessageComposer.mediaRecorderStyle.recordingButtonBackgroundColor = UIC ```swift +// Create custom media recorder style var mediaRecorderStyle = MediaRecorderStyle() mediaRecorderStyle.deleteButtonCornerRadius = .init(cornerRadius: 8) mediaRecorderStyle.pauseButtonCornerRadius = .init(cornerRadius: 8) @@ -235,12 +231,11 @@ mediaRecorderStyle.stopButtonCornerRadius = .init(cornerRadius: 8) mediaRecorderStyle.recordingButtonCornerRadius = .init(cornerRadius: 8) mediaRecorderStyle.recordingButtonBackgroundColor = UIColor(hex: "#F44649") +// Apply to message composer instance let messageComposer = CometChatMessageComposer() messageComposer.mediaRecorderStyle = mediaRecorderStyle ``` - - @@ -249,28 +244,29 @@ messageComposer.mediaRecorderStyle = mediaRecorderStyle The following properties are exposed by Media Recorder Style: -| **Property** | **Description** | **Code** | -| ---------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| **backgroundColor** | Sets the background color of the media recorder. | `mediaRecorderStyle.backgroundColor: UIColor = CometChatTheme.backgroundColor01` | -| **borderWidth** | Defines the width of the border for the media recorder. | `mediaRecorderStyle.borderWidth: CGFloat = 1` | -| **borderColor** | Specifies the border color of the media recorder. | `mediaRecorderStyle.borderColor: UIColor = CometChatTheme.borderColorLight` | -| **cornerRadius** | Configures the corner radius of the media recorder. | `mediaRecorderStyle.cornerRadius: CometChatCornerStyle? = nil` | -| **recordingButtonBackgroundColor** | Sets the background color of the recording button. | `mediaRecorderStyle.recordingButtonBackgroundColor: UIColor = CometChatTheme.iconColorHighlight` | -| **recordingButtonCornerRadius** | Configures the corner radius of the recording button. | `mediaRecorderStyle.recordingButtonCornerRadius: CometChatCornerStyle? = nil` | -| **recordingButtonBorderWidth** | Sets the border width of the recording button. | `mediaRecorderStyle.recordingButtonBorderWidth: CGFloat = 0` | -| **recordingButtonBorderColor** | Sets the border color of the recording button. | `mediaRecorderStyle.recordingButtonBorderColor: UIColor = .clear` | -| **recordingButtonImageTintColor** | Specifies the tint color of the recording button image. | `mediaRecorderStyle.recordingButtonImageTintColor: UIColor = CometChatTheme.white` | -| **recordingButtonImage** | The image displayed on the recording button. | `mediaRecorderStyle.recordingButtonImage: UIImage = UIImage(systemName: "mic.fill") ?? UIImage()` | -| **deleteButtonBackgroundColor** | Sets the background color of the delete button. | `mediaRecorderStyle.deleteButtonBackgroundColor: UIColor = CometChatTheme.backgroundColor01` | -| **deleteButtonImageTintColor** | Specifies the tint color of the delete button image. | `mediaRecorderStyle.deleteButtonImageTintColor: UIColor = CometChatTheme.iconColorSecondary` | -| **deleteButtonImage** | The image displayed on the delete button. | `mediaRecorderStyle.deleteButtonImage: UIImage = UIImage(systemName: "trash.fill") ?? UIImage()` | -| **deleteButtonCornerRadius** | Configures the corner radius of the delete button. | `mediaRecorderStyle.deleteButtonCornerRadius: CometChatCornerStyle? = nil` | -| **deleteButtonBorderWidth** | Sets the border width of the delete button. | `mediaRecorderStyle.deleteButtonBorderWidth: CGFloat = 1` | -| **deleteButtonBorderColor** | Specifies the border color of the delete button. | `mediaRecorderStyle.deleteButtonBorderColor: UIColor = CometChatTheme.borderColorLight` | - -##### 3. AI Options Style - -To customize the media recording styling, you can apply the `AIOptionsStyle` to the `MessageComposer` component. For more details, please refer to [MediaRecorder](/ui-kit/ios/component-styling#media-recorder) styles. +| Property | Description | Code | +|----------|-------------|------| +| **backgroundColor** | Sets the background color of the media recorder | `mediaRecorderStyle.backgroundColor: UIColor = CometChatTheme.backgroundColor01` | +| **borderWidth** | Defines the width of the border for the media recorder | `mediaRecorderStyle.borderWidth: CGFloat = 1` | +| **borderColor** | Specifies the border color of the media recorder | `mediaRecorderStyle.borderColor: UIColor = CometChatTheme.borderColorLight` | +| **cornerRadius** | Configures the corner radius of the media recorder | `mediaRecorderStyle.cornerRadius: CometChatCornerStyle? = nil` | +| **recordingButtonBackgroundColor** | Sets the background color of the recording button | `mediaRecorderStyle.recordingButtonBackgroundColor: UIColor = CometChatTheme.iconColorHighlight` | +| **recordingButtonCornerRadius** | Configures the corner radius of the recording button | `mediaRecorderStyle.recordingButtonCornerRadius: CometChatCornerStyle? = nil` | +| **recordingButtonBorderWidth** | Sets the border width of the recording button | `mediaRecorderStyle.recordingButtonBorderWidth: CGFloat = 0` | +| **recordingButtonBorderColor** | Sets the border color of the recording button | `mediaRecorderStyle.recordingButtonBorderColor: UIColor = .clear` | +| **recordingButtonImageTintColor** | Specifies the tint color of the recording button image | `mediaRecorderStyle.recordingButtonImageTintColor: UIColor = CometChatTheme.white` | +| **recordingButtonImage** | The image displayed on the recording button | `mediaRecorderStyle.recordingButtonImage: UIImage = UIImage(systemName: "mic.fill") ?? UIImage()` | +| **deleteButtonBackgroundColor** | Sets the background color of the delete button | `mediaRecorderStyle.deleteButtonBackgroundColor: UIColor = CometChatTheme.backgroundColor01` | +| **deleteButtonImageTintColor** | Specifies the tint color of the delete button image | `mediaRecorderStyle.deleteButtonImageTintColor: UIColor = CometChatTheme.iconColorSecondary` | +| **deleteButtonImage** | The image displayed on the delete button | `mediaRecorderStyle.deleteButtonImage: UIImage = UIImage(systemName: "trash.fill") ?? UIImage()` | +| **deleteButtonCornerRadius** | Configures the corner radius of the delete button | `mediaRecorderStyle.deleteButtonCornerRadius: CometChatCornerStyle? = nil` | +| **deleteButtonBorderWidth** | Sets the border width of the delete button | `mediaRecorderStyle.deleteButtonBorderWidth: CGFloat = 1` | +| **deleteButtonBorderColor** | Specifies the border color of the delete button | `mediaRecorderStyle.deleteButtonBorderColor: UIColor = CometChatTheme.borderColorLight` | + + +#### 3. AI Options Style + +To customize the AI options styling, you can apply the `AIOptionsStyle` to the `MessageComposer` component. For more details, please refer to [AIOptions](/ui-kit/ios/component-styling#media-recorder) styles. **Global level styling** @@ -281,9 +277,7 @@ CometChatMessageComposer.aiOptionsStyle.backgroundColor = UIColor(hex: "#FFF9F5" CometChatMessageComposer.aiOptionsStyle.textColor = .black CometChatMessageComposer.aiOptionsStyle.aiImageTintColor = UIColor(hex: "#F76808") ``` - - **Instance level styling** @@ -291,17 +285,17 @@ CometChatMessageComposer.aiOptionsStyle.aiImageTintColor = UIColor(hex: "#F76808 ```swift +// Create custom AI options style var aIOptionsStyle = AIOptionsStyle() aIOptionsStyle.backgroundColor = UIColor(hex: "#FFF9F5") aIOptionsStyle.textColor = .black aIOptionsStyle.aiImageTintColor = UIColor(hex: "#F76808") +// Apply to message composer instance let messageComposer = CometChatMessageComposer() messageComposer.aiOptionsStyle = aIOptionsStyle ``` - - @@ -310,56 +304,57 @@ messageComposer.aiOptionsStyle = aIOptionsStyle The following properties are exposed by AI Options Style: -| **Property** | **Description** | **Code** | -| ---------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------ | -| **errorViewTextFont** | Specifies the font used for the text in the error view. | `aIOptionsStyle.errorViewTextFont: UIFont?` | -| **errorViewTextColor** | Sets the color of the text in the error view. | `aIOptionsStyle.errorViewTextColor: UIColor?` | -| **emptyViewTextFont** | Specifies the font used for the text in the empty view. | `aIOptionsStyle.emptyViewTextFont: UIFont?` | -| **emptyViewTextColor** | Sets the color of the text in the empty view. | `aIOptionsStyle.emptyViewTextColor: UIColor?` | -| **aiImageTintColor** | Configures the tint color for AI-related images. | `aIOptionsStyle.aiImageTintColor: UIColor = CometChatTheme.iconColorHighlight` | -| **textColor** | Sets the color of the text. | `aIOptionsStyle.textColor: UIColor = CometChatTheme.textColorPrimary` | -| **textFont** | Specifies the font for the text. | `aIOptionsStyle.textFont: UIFont = CometChatTypography.Heading4.regular` | -| **backgroundColor** | Sets the background color. | `aIOptionsStyle.backgroundColor: UIColor = CometChatTheme.backgroundColor01` | -| **borderWidth** | Sets the width of the border. | `aIOptionsStyle.borderWidth: CGFloat = 0` | -| **borderColor** | Sets the color of the border. | `aIOptionsStyle.borderColor: UIColor = .clear` | -| **cornerRadius** | Configures the corner radius of the view. | `aIOptionsStyle.cornerRadius: CometChatCornerStyle? = nil` | - -*** +| Property | Description | Code | +|----------|-------------|------| +| **errorViewTextFont** | Specifies the font used for the text in the error view | `aIOptionsStyle.errorViewTextFont: UIFont?` | +| **errorViewTextColor** | Sets the color of the text in the error view | `aIOptionsStyle.errorViewTextColor: UIColor?` | +| **emptyViewTextFont** | Specifies the font used for the text in the empty view | `aIOptionsStyle.emptyViewTextFont: UIFont?` | +| **emptyViewTextColor** | Sets the color of the text in the empty view | `aIOptionsStyle.emptyViewTextColor: UIColor?` | +| **aiImageTintColor** | Configures the tint color for AI-related images | `aIOptionsStyle.aiImageTintColor: UIColor = CometChatTheme.iconColorHighlight` | +| **textColor** | Sets the color of the text | `aIOptionsStyle.textColor: UIColor = CometChatTheme.textColorPrimary` | +| **textFont** | Specifies the font for the text | `aIOptionsStyle.textFont: UIFont = CometChatTypography.Heading4.regular` | +| **backgroundColor** | Sets the background color | `aIOptionsStyle.backgroundColor: UIColor = CometChatTheme.backgroundColor01` | +| **borderWidth** | Sets the width of the border | `aIOptionsStyle.borderWidth: CGFloat = 0` | +| **borderColor** | Sets the color of the border | `aIOptionsStyle.borderColor: UIColor = .clear` | +| **cornerRadius** | Configures the corner radius of the view | `aIOptionsStyle.cornerRadius: CometChatCornerStyle? = nil` | + +--- ### Functionality -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can set maximum lines text area will show before scrolling in the composer, edit a message, add header view and footer view to the composer, etc. - -Below is a list of customizations along with corresponding code snippets message composer offers - -| Property | Description | Code | -| --------------------------------- | -------------------------------------------------------- | ------------------------------------------ | -| setInitialComposerText | Sets the initial text in the composer when it loads. | `setInitialComposerText("Hello")` | -| disableTypingEvents | Disables sending typing indicators when the user types. | `disableTypingEvents = true` | -| disableMentions | Disables the mention feature in the composer. | `disableMentions = true` | -| hideImageAttachmentOption | Hides the option to attach images. | `hideImageAttachmentOption = true` | -| hideVideoAttachmentOption | Hides the option to attach videos. | `hideVideoAttachmentOption = true` | -| hideAudioAttachmentOption | Hides the option to attach audio files. | `hideAudioAttachmentOption = true` | -| hideFileAttachmentOption | Hides the option to attach files. | `hideFileAttachmentOption = true` | -| hidePollsOption | Hides the option to create polls. | `hidePollsOption = true` | -| hideCollaborativeDocumentOption | Hides the option for collaborative documents. | `hideCollaborativeDocumentOption = true` | -| hideCollaborativeWhiteboardOption | Hides the option for collaborative whiteboards. | `hideCollaborativeWhiteboardOption = true` | -| hideAttachmentButton | Hides the attachment button in the composer. | `hideAttachmentButton = true` | -| hideVoiceRecordingButton | Hides the voice recording button. | `hideVoiceRecordingButton = true` | -| hideStickersButton | Hides the stickers button. | `hideStickersButton = true` | -| hideSendButton | Hides the send button. | `hideSendButton = true` | -| setUser | Sets the user for direct messaging. | `set(user: User)` | -| setGroup | Sets the group for group messaging. | `set(group: Group)` | -| setParentMessageId | Sets the parent message ID for replying in a thread. | `set(parentMessageId: 12345)` | -| setMaxLine | Sets the maximum number of lines for the composer input. | `set(maxLine: 3)` | -| setCustomSoundForMessages | Sets a custom sound for sending messages. | `set(customSoundForMessages: URL?)` | -| disableSoundForMessages | Disables sound while sending messages. | `disableSoundForMessages = true` | - -*** +These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can set maximum lines the text area will show before scrolling in the composer, edit a message, add header view and footer view to the composer, and more. + +Below is a list of customizations along with corresponding code snippets that the message composer offers: + +| Property | Description | Code | +|----------|-------------|------| +| setInitialComposerText | Sets the initial text in the composer when it loads | `setInitialComposerText("Hello")` | +| disableTypingEvents | Disables sending typing indicators when the user types | `disableTypingEvents = true` | +| disableMentions | Disables the mention feature in the composer | `disableMentions = true` | +| hideImageAttachmentOption | Hides the option to attach images | `hideImageAttachmentOption = true` | +| hideVideoAttachmentOption | Hides the option to attach videos | `hideVideoAttachmentOption = true` | +| hideAudioAttachmentOption | Hides the option to attach audio files | `hideAudioAttachmentOption = true` | +| hideFileAttachmentOption | Hides the option to attach files | `hideFileAttachmentOption = true` | +| hidePollsOption | Hides the option to create polls | `hidePollsOption = true` | +| hideCollaborativeDocumentOption | Hides the option for collaborative documents | `hideCollaborativeDocumentOption = true` | +| hideCollaborativeWhiteboardOption | Hides the option for collaborative whiteboards | `hideCollaborativeWhiteboardOption = true` | +| hideAttachmentButton | Hides the attachment button in the composer | `hideAttachmentButton = true` | +| hideVoiceRecordingButton | Hides the voice recording button | `hideVoiceRecordingButton = true` | +| hideStickersButton | Hides the stickers button | `hideStickersButton = true` | +| hideSendButton | Hides the send button | `hideSendButton = true` | +| setUser | Sets the user for direct messaging | `set(user: User)` | +| setGroup | Sets the group for group messaging | `set(group: Group)` | +| setParentMessageId | Sets the parent message ID for replying in a thread | `set(parentMessageId: 12345)` | +| setMaxLine | Sets the maximum number of lines for the composer input | `set(maxLine: 3)` | +| setCustomSoundForMessages | Sets a custom sound for sending messages | `set(customSoundForMessages: URL?)` | +| disableSoundForMessages | Disables sound while sending messages | `disableSoundForMessages = true` | + + +--- ### Advanced -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. #### AttachmentOptions @@ -373,9 +368,7 @@ messageComposer.set(attachmentOptions: { user, group, controller in return [CometChatMessageComposerAction] }) ``` - - **Demonstration** @@ -384,63 +377,69 @@ messageComposer.set(attachmentOptions: { user, group, controller in -In this example, we are overriding the existing MessageComposerActions List with Capture Photo actions. +In this example, we are overriding the existing MessageComposerActions List with custom actions: ```swift -let messageComposer = CometChatMessageComposer() +let messageComposer = CometChatMessageComposer() messageComposer.setAttachmentOptions { user, group, controller in + // Create custom action 1 let customComposerAction1 = CometChatMessageComposerAction( - id: "customAction1", - text: "Custom Option 1", - startIcon: UIImage(systemName: "play_circle"), - startIconTint: .black, - textColor: .black, - onActionClick: { - print("Custom Action 1 clicked!") - } - ) + id: "customAction1", + text: "Custom Option 1", + startIcon: UIImage(systemName: "play_circle"), + startIconTint: .black, + textColor: .black, + onActionClick: { + print("Custom Action 1 clicked!") + } + ) + + // Create custom action 2 let customComposerAction2 = CometChatMessageComposerAction( - id: "customAction2", - text: "Custom Option 2", - startIcon: UIImage(systemName: "add_box"), - startIconTint: .black, - textColor: .black, - onActionClick: { - print("Custom Action 2 clicked!") - } - ) + id: "customAction2", + text: "Custom Option 2", + startIcon: UIImage(systemName: "add_box"), + startIconTint: .black, + textColor: .black, + onActionClick: { + print("Custom Action 2 clicked!") + } + ) + + // Create custom action 3 let customComposerAction3 = CometChatMessageComposerAction( - id: "customAction3", - text: "Custom Option 3", - startIcon: UIImage(systemName: "change_circle"), - startIconTint: .black, - textColor: .black, - onActionClick: { - print("Custom Action 3 clicked!") - } - ) + id: "customAction3", + text: "Custom Option 3", + startIcon: UIImage(systemName: "change_circle"), + startIconTint: .black, + textColor: .black, + onActionClick: { + print("Custom Action 3 clicked!") + } + ) + + // Create custom action 4 let customComposerAction4 = CometChatMessageComposerAction( - id: "customAction4", - text: "Custom Option 4", - startIcon: UIImage(systemName: "sunny"), - startIconTint: .black, - textColor: .black, - onActionClick: { - print("Custom Action 4 clicked!") - } - ) - - return [customComposerAction1 , customComposerAction2, customComposerAction3, customComposerAction4] -} + id: "customAction4", + text: "Custom Option 4", + startIcon: UIImage(systemName: "sunny"), + startIconTint: .black, + textColor: .black, + onActionClick: { + print("Custom Action 4 clicked!") + } + ) + + return [customComposerAction1, customComposerAction2, customComposerAction3, customComposerAction4] +} ``` - - -*** + +--- #### SendButtonView @@ -449,15 +448,13 @@ By using `set(sendButtonView:)`, you can set a custom send button for the Messag ```swift -let messageComposer = CustomSendButton() +let messageComposer = CometChatMessageComposer() messageComposer.set(sendButtonView: { user, group in let view = CustomSendButton() return view }) ``` - - **Demonstration** @@ -483,7 +480,8 @@ class CustomSendButton: UIView { return button }() - var onPlayTapped: (() -> Void)? // Closure to handle button tap + // Closure to handle button tap + var onPlayTapped: (() -> Void)? override init(frame: CGRect) { super.init(frame: frame) @@ -509,16 +507,14 @@ class CustomSendButton: UIView { } @objc private func playButtonTapped() { - onPlayTapped?() // Executes the closure when tapped + onPlayTapped?() } } ``` - - -*** +--- #### HeaderView @@ -533,9 +529,7 @@ messageComposer.set(headerView: { user, group in return view }) ``` - - **Demonstration** @@ -553,7 +547,7 @@ class CustomHeaderView: UIView { private let iconImageView: UIImageView = { let imageView = UIImageView() - imageView.image = UIImage(systemName: "bell.slash.fill") // Replace with the actual image if needed + imageView.image = UIImage(systemName: "bell.slash.fill") imageView.tintColor = .purple imageView.contentMode = .scaleAspectFit return imageView @@ -599,63 +593,66 @@ class CustomHeaderView: UIView { } } ``` - - -*** -#### SetTextFormatters +--- -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/ios/mentions-formatter-guide) +#### SetTextFormatters -**Example** +Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel, check out [CometChatMentionsFormatter](/ui-kit/ios/mentions-formatter-guide). ```swift +// Create custom composer text style for mentions let composerTextStyle = MentionTextStyle() -.set(textBackgroundColor: .white) -.set(textColor: UIColor.black) -.set(textFont: UIFont.systemFont(ofSize: 18, weight: .heavy)) -.set(loggedInUserTextColor: UIColor.systemTeal) -.set(loggedInUserTextFont: UIFont.systemFont(ofSize: 18, weight: .bold)) + .set(textBackgroundColor: .white) + .set(textColor: UIColor.black) + .set(textFont: UIFont.systemFont(ofSize: 18, weight: .heavy)) + .set(loggedInUserTextColor: UIColor.systemTeal) + .set(loggedInUserTextFont: UIFont.systemFont(ofSize: 18, weight: .bold)) +// Create custom mention formatter with the style let customMentionFormatter = CometChatMentionsFormatter() -.set(composerTextStyle: composerTextStyle) + .set(composerTextStyle: composerTextStyle) +// Configure message composer with the formatter let messageComposerConfiguration = MessageComposerConfiguration() -.set(textFormatter: [customMentionFormatter]) + .set(textFormatter: [customMentionFormatter]) +// Apply to CometChatMessages let cometChatMessages = CometChatMessages() -.set(user: user) -.set(messageComposerConfiguration: messageComposerConfiguration) + .set(user: user) + .set(messageComposerConfiguration: messageComposerConfiguration) ``` - - -*** +--- - To ensure that the `MessageComposer` is properly configured, passing the controller is mandatory. -* Swift - ```swift let composerView = CometChatMessageComposer() composerView.set(controller: UIViewController) // Passing the controller is required ``` - -*** +--- - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - + +--- + +## Next Steps + +- [Message List](/ui-kit/ios/message-list) — Display and customize the message list +- [Message Header](/ui-kit/ios/message-header) — Customize the conversation header +- [Mentions Formatter](/ui-kit/ios/mentions-formatter-guide) — Configure @mention formatting + +--- From f96448d88d192f8439cbb4d29f87572fa27148be Mon Sep 17 00:00:00 2001 From: Aditya Date: Fri, 13 Feb 2026 12:34:18 +0530 Subject: [PATCH 013/106] modified message-header, message-list, message-template --- ui-kit/ios/message-header.mdx | 306 ++++++++-------- ui-kit/ios/message-list.mdx | 495 ++++++++++++------------- ui-kit/ios/message-template.mdx | 632 ++++++++++++++++++-------------- 3 files changed, 726 insertions(+), 707 deletions(-) diff --git a/ui-kit/ios/message-header.mdx b/ui-kit/ios/message-header.mdx index 81973492d..fab93ed10 100644 --- a/ui-kit/ios/message-header.mdx +++ b/ui-kit/ios/message-header.mdx @@ -1,10 +1,12 @@ --- title: "Message Header" +sidebarTitle: "Message Header" +description: "Display user or group details with typing indicators and navigation controls in CometChat UI Kit for iOS" --- ## Overview -`MessageHeader` is a [Component](/ui-kit/ios/components-overview#components) that showcases the [User](/sdk/ios/users-overview) or [Group](/sdk/ios/groups-overview) details in the toolbar. Furthermore, it also presents a typing indicator and a back navigation button for ease of use. +`MessageHeader` is a [Component](/ui-kit/ios/components-overview#components) that showcases the [User](/sdk/ios/users-overview) or [Group](/sdk/ios/groups-overview) details in the toolbar. It also presents a typing indicator and a back navigation button for ease of use. @@ -12,85 +14,89 @@ title: "Message Header" The `MessageHeader` is comprised of the following components: -| Components | Description | -| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| [ListItem Component](/ui-kit/ios/list-item) | This component’s view consists of avatar, status indicator , title, and subtitle. The fields are then mapped with the SDK’s user, group class. | -| Back Button | BackButton that allows users to navigate back from the current activity or screen to the previous one | +| Components | Description | +|------------|-------------| +| ListItem | This component's view consists of avatar, status indicator, title, and subtitle. The fields are mapped with the SDK's [User](/sdk/ios/users-overview) and [Group](/sdk/ios/groups-overview) class. | +| Back Button | Allows users to navigate back from the current activity or screen to the previous one | + +--- ## Usage ### Integration -You can add `MessageHeader` component directly by setting the user. +You can add the `MessageHeader` component directly by setting the user: -```ruby Swift -// syntax for set(user: User) -messageHeader.set(user: user) // The object which is going to be rendered in the data item +```swift +// Set the user for the message header +messageHeader.set(user: user) ``` +--- + ### Actions [Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. The `MessageHeader` component does not have any exposed actions. -##### 1. set(onBack:) +#### 1. set(onBack:) -This `set(onBack:)` method becomes valuable when a user needs to override the action triggered upon pressing the back button in CometChatMessageHeader. +The `set(onBack:)` method becomes valuable when you need to override the action triggered upon pressing the back button in CometChatMessageHeader. ```swift cometChatMessageHeader.set(onBack: { - // Override on back + // Handle back button action }) ``` - - -*** +--- -##### 2. set(onError:) +#### 2. set(onError:) -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatMessageHeader. +This method proves helpful when you need to customize the action taken upon encountering an error in CometChatMessageHeader. ```swift cometChatMessageHeader.set(onError: { error in - // Override on error + // Handle error }) ``` - - -*** +--- ### Filters -**Filters** allow you to customize the data displayed in a list within a `Component`. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. +Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for more customization. Filters can be applied using `RequestBuilders` of the Chat SDK. The `MessageHeader` component does not have any exposed filters. +--- + ### Events -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. The `MessageHeader` component does not produce any events. +--- + ## Customization To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. ### Style -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. -##### 1. MessageHeader Style +#### 1. MessageHeader Style To customize the appearance, you can assign a `MessageHeaderStyle` object to the `MessageHeader` component. @@ -99,18 +105,18 @@ To customize the appearance, you can assign a `MessageHeaderStyle` object to the ```swift +// Create custom avatar style let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.textFont = UIFont(name: "Times-New-Roman", size: 18) - + +// Apply global message header styling CometChatMessageHeader.style.titleTextColor = UIColor(hex: "#F76808") CometChatMessageHeader.style.titleTextFont = UIFont(name: "Times-New-Roman", size: 16) CometChatMessageHeader.style.subtitleTextFont = UIFont(name: "Times-New-Roman", size: 12) CometChatMessageHeader.style.avatarStyle = customAvatarStyle ``` - - **Instance level styling** @@ -118,71 +124,73 @@ CometChatMessageHeader.style.avatarStyle = customAvatarStyle ```swift +// Create custom avatar style let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.textFont = UIFont(name: "Times-New-Roman", size: 18) - + +// Create custom message header style let messageHeaderStyle = MessageHeaderStyle() messageHeaderStyle.titleTextColor = UIColor(hex: "#F76808") messageHeaderStyle.titleTextFont = UIFont(name: "Times-New-Roman", size: 16) messageHeaderStyle.subtitleTextFont = UIFont(name: "Times-New-Roman", size: 12) - + +// Apply styles to instance let messageHeader = CometChatMessageHeader() messageHeader.style = messageHeaderStyle messageHeader.avatarStyle = customAvatarStyle ``` - - + The properties exposed by `MessageHeaderStyle` are as follows: -| **Property** | **Description** | **Code** | -| --------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| **Title Text Color** | Used to set the text color of the header title. | `CometChatMessageHeader.style.titleTextColor = UIColor.black` | -| **Title Text Font** | Used to set the font style of the header title. | `CometChatMessageHeader.style.titleTextFont = UIFont.boldSystemFont(ofSize: 18)` | -| **Subtitle Text Color** | Used to set the text color of the subtitle in the header. | `CometChatMessageHeader.style.subtitleTextColor = UIColor.gray` | -| **Subtitle Text Font** | Used to set the font style of the subtitle in the header. | `CometChatMessageHeader.style.subtitleTextFont = UIFont.systemFont(ofSize: 14)` | -| **Back Button Image Tint Color** | Used to set the tint color of the back button image in the header. | `CometChatMessageHeader.style.backButtonImageTintColor = UIColor.blue` | -| **Private Group Badge Tint Color** | Used to set the tint color of the private group badge in the header. | `CometChatMessageHeader.style.privateGroupBadgeImageTintColor = UIColor.green` | -| **Password-Protected Badge Tint Color** | Used to set the tint color of the password-protected group badge in the header. | `CometChatMessageHeader.style.passwordProtectedGroupBadgeImageTintColor = UIColor.orange` | -| **Private Group Background Color** | Used to set the background color of the private group badge. | `CometChatMessageHeader.style.privateGroupImageBackgroundColor = UIColor.lightGray` | -| **Password-Protected Background Color** | Used to set the background color of the password-protected group badge. | `CometChatMessageHeader.style.passwordGroupImageBackgroundColor = UIColor.red` | -| **Group Image Background Color** | Used to set the background color for group icons in the header. | `CometChatMessageHeader.style.groupImageBackgroundColor = UIColor.clear` | -| **Avatar Style** | Used to customize the appearance of the avatar in the header. | `CometChatMessageHeader.style.avatarStyle = customAvatarStyle` | -| **Background Color** | Used to set the background color of the header. | `CometChatMessageHeader.style.backgroundColor = UIColor.white` | -| **Corner Radius** | Used to set the corner radius of the header. | `CometChatMessageHeader.style.cornerRadius = CometChatCornerStyle(cornerRadius: 8)` | -| **Border Width** | Used to set the border width of the header. | `CometChatMessageHeader.style.borderWidth = 2` | -| **Border Color** | Used to set the border color of the header. | `CometChatMessageHeader.style.borderColor = UIColor.gray` | -| **Back Button Icon** | Used to set a custom icon for the back button. | `CometChatMessageHeader.style.backButtonIcon = UIImage(named: "customBackIcon")` | -| **Private Group Icon** | Used to set a custom icon for private groups. | `CometChatMessageHeader.style.privateGroupIcon = UIImage(named: "privateIcon")` | -| **Protected Group Icon** | Used to set a custom icon for password-protected groups. | `CometChatMessageHeader.style.protectedGroupIcon = UIImage(named: "protectedIcon")` | -| **Background Image** | Used to set a background image for the header. | `CometChatMessageHeader.style.backgroundImage = UIImage(named: "headerBackground")` | -| **New Chat Icon** | Sets a custom icon for the new chat button for AI agent. | `CometChatAIAssistantChatHistory.newChatIcon = UIImage(named: "iconName")` | -| **Chat History Icon** | Sets a custom icon for the chat history button for AI agent. | `CometChatAIAssistantChatHistory.chatHistoryIcon = UIImage(named: "iconName")` | - -##### 2. Avatar Style - -If you want to apply customized styles to the `Avatar` component within the `MessageHeader` Component, you can use the following code snippet. For more information you can refer [Avatar Styles](/ui-kit/ios/component-styling#avatar#methods). +| Property | Description | Code | +|----------|-------------|------| +| **Title Text Color** | Sets the text color of the header title | `CometChatMessageHeader.style.titleTextColor = UIColor.black` | +| **Title Text Font** | Sets the font style of the header title | `CometChatMessageHeader.style.titleTextFont = UIFont.boldSystemFont(ofSize: 18)` | +| **Subtitle Text Color** | Sets the text color of the subtitle in the header | `CometChatMessageHeader.style.subtitleTextColor = UIColor.gray` | +| **Subtitle Text Font** | Sets the font style of the subtitle in the header | `CometChatMessageHeader.style.subtitleTextFont = UIFont.systemFont(ofSize: 14)` | +| **Back Button Image Tint Color** | Sets the tint color of the back button image | `CometChatMessageHeader.style.backButtonImageTintColor = UIColor.blue` | +| **Private Group Badge Tint Color** | Sets the tint color of the private group badge | `CometChatMessageHeader.style.privateGroupBadgeImageTintColor = UIColor.green` | +| **Password-Protected Badge Tint Color** | Sets the tint color of the password-protected group badge | `CometChatMessageHeader.style.passwordProtectedGroupBadgeImageTintColor = UIColor.orange` | +| **Private Group Background Color** | Sets the background color of the private group badge | `CometChatMessageHeader.style.privateGroupImageBackgroundColor = UIColor.lightGray` | +| **Password-Protected Background Color** | Sets the background color of the password-protected group badge | `CometChatMessageHeader.style.passwordGroupImageBackgroundColor = UIColor.red` | +| **Group Image Background Color** | Sets the background color for group icons in the header | `CometChatMessageHeader.style.groupImageBackgroundColor = UIColor.clear` | +| **Avatar Style** | Customizes the appearance of the avatar in the header | `CometChatMessageHeader.style.avatarStyle = customAvatarStyle` | +| **Background Color** | Sets the background color of the header | `CometChatMessageHeader.style.backgroundColor = UIColor.white` | +| **Corner Radius** | Sets the corner radius of the header | `CometChatMessageHeader.style.cornerRadius = CometChatCornerStyle(cornerRadius: 8)` | +| **Border Width** | Sets the border width of the header | `CometChatMessageHeader.style.borderWidth = 2` | +| **Border Color** | Sets the border color of the header | `CometChatMessageHeader.style.borderColor = UIColor.gray` | +| **Back Button Icon** | Sets a custom icon for the back button | `CometChatMessageHeader.style.backButtonIcon = UIImage(named: "customBackIcon")` | +| **Private Group Icon** | Sets a custom icon for private groups | `CometChatMessageHeader.style.privateGroupIcon = UIImage(named: "privateIcon")` | +| **Protected Group Icon** | Sets a custom icon for password-protected groups | `CometChatMessageHeader.style.protectedGroupIcon = UIImage(named: "protectedIcon")` | +| **Background Image** | Sets a background image for the header | `CometChatMessageHeader.style.backgroundImage = UIImage(named: "headerBackground")` | +| **New Chat Icon** | Sets a custom icon for the new chat button (AI agent) | `CometChatAIAssistantChatHistory.newChatIcon = UIImage(named: "iconName")` | +| **Chat History Icon** | Sets a custom icon for the chat history button (AI agent) | `CometChatAIAssistantChatHistory.chatHistoryIcon = UIImage(named: "iconName")` | + +#### 2. Avatar Style + +If you want to apply customized styles to the `Avatar` component within the `MessageHeader` Component, you can use the following code snippet. For more information, refer to [Avatar Styles](/ui-kit/ios/component-styling#avatar#methods). **Global level styling** ```swift +// Create custom avatar style with rounded corners let customAvatarStyle = AvatarStyle() customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) - + +// Apply globally CometChatMessageHeader.style.avatarStyle = customAvatarStyle ``` - - **Instance level styling** @@ -190,79 +198,80 @@ CometChatMessageHeader.style.avatarStyle = customAvatarStyle ```swift +// Create custom avatar style let customAvatarStyle = AvatarStyle() customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) - + +// Apply to instance let messageHeader = CometChatMessageHeader() messageHeader.avatarStyle = customAvatarStyle ``` - - -*** +--- ### Functionality These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. -Below is a list of customizations along with corresponding code snippets - -| Method | Description | Code | -| ------------------- | ---------------------------------------------------------------------- | ---------------------------- | -| set(user:User) | Sets message header for CometChat user. | `.set(user:User)` | -| set(group:Group) | Sets message header for CometChat group. | `.set(group:Group)` | -| hideBackButton | Hides the back button of message header. | `hideBackButton = true` | -| hideUserStatus | Hides or shows the user status of user(online/offline/last active at). | `hideUserStatus = true` | -| hideVideoCallButton | Hides the video call button. | `hideVideoCallButton = true` | -| hideVoiceCallButton | Hides the voice call button. | `hideVoiceCallButton = true` | -| hideChatHistoryButton | Hides the chat history button in the component. | `CometChatAIAssistantChatHistory.hideChatHistoryButton = true` | -| hideNewChatButton | Hides the new chat button in the component for AI agent. | `CometChatAIAssistantChatHistory.hideNewChatButton = true` | -| onNewChatButtonClicked | Used to handle actions when the “New Chat” button is clicked. | `CometChatAIAssistantChatHistory.set(onNewChatButtonClicked: { user in })` | -| onMessageClicked | Used to handle actions when a message is clicked. | `CometChatAIAssistantChatHistory.set(onMessageClicked: { message in })` | +Below is a list of customizations along with corresponding code snippets: + +| Method | Description | Code | +|--------|-------------|------| +| set(user:User) | Sets message header for CometChat user | `.set(user:User)` | +| set(group:Group) | Sets message header for CometChat group | `.set(group:Group)` | +| hideBackButton | Hides the back button of message header | `hideBackButton = true` | +| hideUserStatus | Hides or shows the user status (online/offline/last active at) | `hideUserStatus = true` | +| hideVideoCallButton | Hides the video call button | `hideVideoCallButton = true` | +| hideVoiceCallButton | Hides the voice call button | `hideVoiceCallButton = true` | +| hideChatHistoryButton | Hides the chat history button in the component | `CometChatAIAssistantChatHistory.hideChatHistoryButton = true` | +| hideNewChatButton | Hides the new chat button in the component (AI agent) | `CometChatAIAssistantChatHistory.hideNewChatButton = true` | +| onNewChatButtonClicked | Handles actions when the "New Chat" button is clicked | `CometChatAIAssistantChatHistory.set(onNewChatButtonClicked: { user in })` | +| onMessageClicked | Handles actions when a message is clicked | `CometChatAIAssistantChatHistory.set(onMessageClicked: { message in })` | -*** +--- ### Advanced -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. #### Date Time Formatter -The **CometChatMessageHeader** component supports full customization of how date and time are displayed using the [CometChatDateTimeFormatter](/ui-kit/ios/localize#datetimeformatter). +The `CometChatMessageHeader` component supports full customization of how date and time are displayed using the [CometChatDateTimeFormatter](/ui-kit/ios/localize#datetimeformatter). -This enables developers to localize, format, or personalize the date and time strings shown next to the message header such as “Today”, “Yesterday”, “12:45 PM”, etc. +This enables developers to localize, format, or personalize the date and time strings shown next to the message header such as "Today", "Yesterday", "12:45 PM", etc. -1. Component-Level (Global) +**1. Component-Level (Global)** ```swift +// Customize time format CometChatMessageHeader.dateTimeFormatter.time = { timestamp in return "Last seen at " + DateFormatter.localizedString(from: Date(timeIntervalSince1970: TimeInterval(timestamp)), dateStyle: .none, timeStyle: .short) } +// Customize today format CometChatMessageHeader.dateTimeFormatter.today = { timestamp in return "Last seen: Today • \(formattedTime(from: timestamp))" } -CometChatMessageHeader.dateTimeFormatter.otherDay = { timestamp in // This will display older dates as "24 Apr 2025" instead of the default relative format. +// Customize older dates format +CometChatMessageHeader.dateTimeFormatter.otherDay = { timestamp in let formatter = DateFormatter() formatter.dateFormat = "dd MMM yyyy" return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) } ``` - - -2. Instance-Level (Local) +**2. Instance-Level (Local)** @@ -272,28 +281,26 @@ messageHeader.dateTimeFormatter.yesterday = { timestamp in return "Yesterday at " + formattedTime(from: timestamp) } ``` - - -##### Available closures +##### Available Closures -| Property | Description | Code | -| --------- | ------------------------------------------------------------------- | -------------------------------------------------------------- | -| time | Called to format a timestamp as a standard time (e.g., "12:30 PM"). | `CometChatMessageHeader.dateTimeFormatter.time = { ... }` | -| today | Called when rendering messages sent today. | `CometChatMessageHeader.dateTimeFormatter.today = { ... }` | -| yesterday | Called for yesterday's messages. | `CometChatMessageHeader.dateTimeFormatter.yesterday = { ... }` | -| lastweek | Called for messages within the last week. | `CometChatMessageHeader.dateTimeFormatter.lastweek = { ... }` | -| otherDay | Called for dates older than last week. | `CometChatMessageHeader.dateTimeFormatter.otherDay = { ... }` | -| minute | Called when referring to "a minute ago". | `CometChatMessageHeader.dateTimeFormatter.minute = { ... }` | -| minutes | Called for "x minutes ago". | `CometChatMessageHeader.dateTimeFormatter.minutes = { ... }` | -| hour | Called for "an hour ago". | `CometChatMessageHeader.dateTimeFormatter.hour = { ... }` | -| hours | Called for "x hours ago". | `CometChatMessageHeader.dateTimeFormatter.hours = { ... }` | +| Property | Description | Code | +|----------|-------------|------| +| time | Called to format a timestamp as a standard time (e.g., "12:30 PM") | `CometChatMessageHeader.dateTimeFormatter.time = { ... }` | +| today | Called when rendering messages sent today | `CometChatMessageHeader.dateTimeFormatter.today = { ... }` | +| yesterday | Called for yesterday's messages | `CometChatMessageHeader.dateTimeFormatter.yesterday = { ... }` | +| lastweek | Called for messages within the last week | `CometChatMessageHeader.dateTimeFormatter.lastweek = { ... }` | +| otherDay | Called for dates older than last week | `CometChatMessageHeader.dateTimeFormatter.otherDay = { ... }` | +| minute | Called when referring to "a minute ago" | `CometChatMessageHeader.dateTimeFormatter.minute = { ... }` | +| minutes | Called for "x minutes ago" | `CometChatMessageHeader.dateTimeFormatter.minutes = { ... }` | +| hour | Called for "an hour ago" | `CometChatMessageHeader.dateTimeFormatter.hour = { ... }` | +| hours | Called for "x hours ago" | `CometChatMessageHeader.dateTimeFormatter.hours = { ... }` | Each closure receives a timestamp (Int, representing UNIX time) and must return a String representing the formatted time. -*** +--- #### SetListItemView @@ -308,20 +315,20 @@ cometChatMessageHeader.set(listItemView: { user, group in return view }) ``` - - -Demonstration +**Demonstration** -You can create a `CustomListItemView` as a custom `UIView`. Which we will inflate in `setListItemView()` +You can create a `CustomListItemView` as a custom `UIView` which will be inflated in `setListItemView()`: -```swift swift + + +```swift import UIKit class CustomListItemView: UIView { @@ -440,12 +447,15 @@ class CustomListItemView: UIView { } } ``` + + -*** + +--- #### SetLeadingView -You can modify the leading view of a group cell using .set(leadingView:). +You can modify the leading view of a group cell using `.set(leadingView:)`. @@ -453,20 +463,18 @@ You can modify the leading view of a group cell using .set(leadingView:). cometChatMessageHeader.set(leadingView: { user, group in let view = CustomLeadingView() return view -}) +}) ``` - - -Demonstration +**Demonstration** -You can create a `CustomLeadingView` as a custom `UIView`. Which we will inflate in `setLeadingView()` +You can create a `CustomLeadingView` as a custom `UIView` which will be inflated in `setLeadingView()`: @@ -480,7 +488,7 @@ class CustomLeadingView: UIView { imageView.contentMode = .scaleAspectFill imageView.layer.cornerRadius = 20 imageView.clipsToBounds = true - imageView.backgroundColor = .lightGray // Placeholder color + imageView.backgroundColor = .lightGray imageView.image = UIImage(systemName: "person.fill") return imageView }() @@ -530,16 +538,14 @@ class CustomLeadingView: UIView { } } ``` - - -*** +--- #### SetTitleView -You can customize the title view of a group cell using .set(titleView:). +You can customize the title view of a group cell using `.set(titleView:)`. @@ -547,25 +553,23 @@ You can customize the title view of a group cell using .set(titleView:). cometChatMessageHeader.set(titleView: { user, group in let view = CustomTitleView() return view -}) +}) ``` - - -Demonstration +**Demonstration** -You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()` +You can create a `CustomTitleView` as a custom `UIView` which will be inflated in `setTitleView()`: ```swift - class CustomTitleView: UIView { +class CustomTitleView: UIView { private let titleLabel: UILabel = { let label = UILabel() @@ -632,16 +636,14 @@ You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate i } } ``` - - -*** +--- #### SetTrailView -You can modify the trailing view of a message header using .set(trailView:). +You can modify the trailing view of a message header using `.set(trailView:)`. @@ -649,20 +651,18 @@ You can modify the trailing view of a message header using .set(trailView:). cometChatMessageHeader.set(trailView: { user, group in let view = CustomTrailView() return view -}) +}) ``` - - -Demonstration +**Demonstration** -You can create a `CustomTrailView` as a custom `UIView`. Which we will inflate in `setTrailView()` +You can create a `CustomTrailView` as a custom `UIView` which will be inflated in `setTrailView()`: @@ -705,7 +705,6 @@ class CustomTrailView: UIView { } private func setupView() { - let buttonsStack = UIStackView(arrangedSubviews: [videoCallButton, callButton]) buttonsStack.axis = .horizontal buttonsStack.spacing = 16 @@ -725,18 +724,15 @@ class CustomTrailView: UIView { ]) } } - ``` - - -*** +--- #### SetSubTitleView -You can customize the subtitle view for each group item to meet your requirements +You can customize the subtitle view for each group item to meet your requirements. @@ -746,20 +742,16 @@ cometChatMessageHeader.set(subtitleView: { user, group in return view }) ``` - - -**Example** - -Demonstration +**Demonstration** -You can seamlessly integrate this `CustomSubtitleView` UIView file into the `.set(subtitleView:)` method within CometChatMessageHeader. +You can seamlessly integrate this `CustomSubtitleView` UIView file into the `.set(subtitleView:)` method within CometChatMessageHeader: @@ -781,22 +773,26 @@ class CustomSubtitleView: UILabel { } } ``` - - -*** +--- - To ensure that the `MessageHeader` is properly configured, passing the controller is mandatory. -* Swift - ```swift let headerView = CometChatMessageHeader() headerView.set(controller: UIViewController) // Passing the controller is required ``` - + +--- + +## Next Steps + +- [Message List](/ui-kit/ios/message-list) — Display and customize the message list +- [Message Composer](/ui-kit/ios/message-composer) — Customize the message input component +- [Conversations](/ui-kit/ios/conversations) — Manage conversation lists + +--- diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index 0deb40de6..d39830cef 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -1,5 +1,7 @@ --- title: "Message List" +sidebarTitle: "Message List" +description: "Display and manage real-time chat messages with various message types using CometChat UI Kit for iOS" --- ## Overview @@ -12,118 +14,106 @@ title: "Message List" -*** +--- ## Usage ### Integration -The following code snippet illustrates how you can directly incorporate the MessageList component. +The following code snippet illustrates how you can directly incorporate the MessageList component: ```swift -// syntax for set(user: User) +// Set user for the message list messageList.set(user: user) -// syntax for set(user: User, parentMessage: BaseMessage? = nil) +// Set user with parent message for threaded conversations messageList.set(user: user, parentMessage: textMessage) ``` - - - To retrieve messages for a specific entity, you must associate it with either a `User` or `Group` object. - -*** +--- ### Actions [Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. -##### 1. onThreadRepliesClick +#### 1. onThreadRepliesClick -`onThreadRepliesClick` is triggered when you click on the thread indicator of message bubble. The `onThreadRepliesClick` action doesn't have a predefined behavior. You can override this action using the following code snippet. +`onThreadRepliesClick` is triggered when you click on the thread indicator of a message bubble. The `onThreadRepliesClick` action doesn't have a predefined behavior. You can override this action using the following code snippet: ```swift - let messageListView = CometChatMessageList() - messageListView.set(onThreadRepliesClick: { message, template in - // Your action onclick +let messageListView = CometChatMessageList() +messageListView.set(onThreadRepliesClick: { message, template in + // Handle thread replies click }) ``` - - -*** +--- -##### 2. onReactionClick +#### 2. onReactionClick `onReactionClick` is triggered when you click on a reaction on a message bubble. ```swift - let messageListView = CometChatMessageList() - messageListView.set(onReactionClick: { reactionCount, baseMessage in - // Your action onclick +let messageListView = CometChatMessageList() +messageListView.set(onReactionClick: { reactionCount, baseMessage in + // Handle reaction click }) ``` - - -*** +--- -##### 3. onReactionListItemClick +#### 3. onReactionListItemClick `onReactionListItemClick` is triggered when you click on the list item of CometChatReactionList on a message bubble. ```swift - let messageListView = CometChatMessageList() - messageListView.set(onReactionListItemClick: { messageReaction, baseMessage in - // Your action onclick +let messageListView = CometChatMessageList() +messageListView.set(onReactionListItemClick: { messageReaction, baseMessage in + // Handle reaction list item click }) ``` - - -*** +--- -##### 4. set(onError:) +#### 4. set(onError:) -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatMessageList. +This method proves helpful when you need to customize the action taken upon encountering an error in CometChatMessageList. ```swift cometChatGroupMembers.set(onError: { error in - // Override on error + // Handle error }) ``` - - -*** +--- -##### 5. set(onEmpty:) +#### 5. set(onEmpty:) -This `set(onEmpty:)` method is triggered when the message list is empty in CometChatMessageList. +The `set(onEmpty:)` method is triggered when the message list is empty in CometChatMessageList. @@ -132,16 +122,14 @@ cometChatMessageList.set(onEmpty: { // Handle empty state }) ``` - - -*** +--- -##### 6. setOnLoad +#### 6. setOnLoad -This set(onLoad:) method is triggered when messages are successfully loaded in CometChatMessageList. +The `set(onLoad:)` method is triggered when messages are successfully loaded in CometChatMessageList. @@ -150,62 +138,55 @@ cometChatMessageList.set(onLoad: { messages in // Handle loaded messages }) ``` - - -*** +--- ### Filters You can adjust the `MessagesRequestBuilder` in the MessageList Component to customize your message list. Numerous options are available to alter the builder to meet your specific needs. For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/ios/additional-message-filtering). -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed +In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed: ```swift -let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() +// Create message request builder with filters +let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() .set(uid: "YOUR_UID") .set(types: ["Text"]) .set(searchKeyword: "sure") +// Apply to CometChatMessages let cometChatMessages = CometChatMessages() cometChatMessages.set(user: user) -cometChatMessages.set(messagesRequestBuilder:messageRequestBuilder) +cometChatMessages.set(messagesRequestBuilder: messageRequestBuilder) ``` - - - -The following parameters in messageRequestBuilder will always be altered inside the message list - +The following parameters in messageRequestBuilder will always be altered inside the message list: 1. UID 2. GUID 3. types 4. categories - - Ensure to include the `uid` and `name` of the User in the implementation. - -*** +--- ### Events -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. The MessageList Component does not emit any events of its own. -*** +--- ## Customization @@ -213,11 +194,11 @@ To fit your app's design requirements, you can customize the appearance of the c ### Style -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. -##### 1. MessageList Style +#### 1. MessageList Style -To customize the appearance, you can assign a `MessageListStyle` object to the `MessageList` component +To customize the appearance, you can assign a `MessageListStyle` object to the `MessageList` component. **Global level styling** @@ -227,9 +208,7 @@ To customize the appearance, you can assign a `MessageListStyle` object to the ` CometChatMessageList.style.backgroundColor = UIColor(hex: "#FBAA75") CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor(hex: "#F76808") ``` - - **Instance level styling** @@ -237,137 +216,136 @@ CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor(hex: ```swift +// Create custom message list style let messageListStyle = MessageListStyle() messageListStyle.backgroundColor = UIColor(hex: "#FBAA75") - + +// Apply to instance let messageList = CometChatMessageList() messageList.messageBubbleStyle.outgoing.backgroundColor = UIColor(hex: "#F76808") messageList.style = messageListStyle ``` - - -List of properties exposed by MessageListStyle - -| **Property** | **Description** | **Code** | -| ------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | -| **Background Color** | Background color with dynamic support for light and dark mode. | `CometChatMessageList.style.backgroundColor = UIColor.dynamicColor(lightModeColor: ..., darkModeColor: ...)` | -| **Border Width** | Border width for the component. | `CometChatMessageList.style.borderWidth = 0` | -| **Border Color** | Border color for the component. | `CometChatMessageList.style.borderColor = .clear` | -| **Corner Radius** | Corner radius for the component. | `CometChatMessageList.style.cornerRadius = CometChatCornerStyle?` | -| **Shimmer Gradient Color 1** | First color of the shimmer gradient. | `CometChatMessageList.style.shimmerGradientColor1 = CometChatTheme.backgroundColor04` | -| **Shimmer Gradient Color 2** | Second color of the shimmer gradient. | `CometChatMessageList.style.shimmerGradientColor2 = CometChatTheme.backgroundColor03` | -| **Empty State Title Color** | Text color for the title in the empty state. | `CometChatMessageList.style.emptyStateTitleColor = CometChatTheme.textColorPrimary` | -| **Empty State Title Font** | Font for the title in the empty state. | `CometChatMessageList.style.emptyStateTitleFont = CometChatTypography.Heading3.bold` | -| **Empty State Subtitle Color** | Text color for the subtitle in the empty state. | `CometChatMessageList.style.emptyStateSubtitleColor = CometChatTheme.textColorSecondary` | -| **Empty State Subtitle Font** | Font for the subtitle in the empty state. | `CometChatMessageList.style.emptyStateSubtitleFont = CometChatTypography.Body.regular` | -| **Error State Title Color** | Text color for the title in the error state. | `CometChatMessageList.style.errorStateTitleColor = CometChatTheme.textColorPrimary` | -| **Error State Title Font** | Font for the title in the error state. | `CometChatMessageList.style.errorStateTitleFont = CometChatTypography.Heading3.bold` | -| **Error State Subtitle Color** | Text color for the subtitle in the error state. | `CometChatMessageList.style.errorStateSubtitleColor = CometChatTheme.textColorSecondary` | -| **Error State Subtitle Font** | Font for the subtitle in the error state. | `CometChatMessageList.style.errorStateSubtitleFont = CometChatTypography.Body.regular` | -| **Threaded Message Image** | Icon image for threaded messages. | `CometChatMessageList.style.threadedMessageImage = UIImage(systemName: "arrow.turn.down.right")` | -| **Error Image** | Icon image for error state. | `CometChatMessageList.style.errorImage = UIImage(named: "error-icon")` | -| **Empty Image** | Icon image for empty state. | `CometChatMessageList.style.emptyImage = UIImage(named: "empty-icon")` | -| **New Message Indicator Image** | Icon image for new message indicator. | `CometChatMessageList.style.newMessageIndicatorImage = UIImage?` | -| **New Message Indicator Text Color** | Text color for unread messages indicator. | `CometChatMessageList.style.newMessageIndicatorTextColor = UIColor?` | -| **New Message Indicator Text Font** | Text font for unread messages indicator. | `CometChatMessageList.style.newMessageIndicatorTextFont = UIFont?` | -| **New Message Indicator Background Color** | Background color for unread messages indicator. | `CometChatMessageList.style.newMessageIndicatorBackgroundColor = UIColor?` | - - - -*** + +List of properties exposed by MessageListStyle: + +| Property | Description | Code | +|----------|-------------|------| +| **Background Color** | Background color with dynamic support for light and dark mode | `CometChatMessageList.style.backgroundColor = UIColor.dynamicColor(lightModeColor: ..., darkModeColor: ...)` | +| **Border Width** | Border width for the component | `CometChatMessageList.style.borderWidth = 0` | +| **Border Color** | Border color for the component | `CometChatMessageList.style.borderColor = .clear` | +| **Corner Radius** | Corner radius for the component | `CometChatMessageList.style.cornerRadius = CometChatCornerStyle?` | +| **Shimmer Gradient Color 1** | First color of the shimmer gradient | `CometChatMessageList.style.shimmerGradientColor1 = CometChatTheme.backgroundColor04` | +| **Shimmer Gradient Color 2** | Second color of the shimmer gradient | `CometChatMessageList.style.shimmerGradientColor2 = CometChatTheme.backgroundColor03` | +| **Empty State Title Color** | Text color for the title in the empty state | `CometChatMessageList.style.emptyStateTitleColor = CometChatTheme.textColorPrimary` | +| **Empty State Title Font** | Font for the title in the empty state | `CometChatMessageList.style.emptyStateTitleFont = CometChatTypography.Heading3.bold` | +| **Empty State Subtitle Color** | Text color for the subtitle in the empty state | `CometChatMessageList.style.emptyStateSubtitleColor = CometChatTheme.textColorSecondary` | +| **Empty State Subtitle Font** | Font for the subtitle in the empty state | `CometChatMessageList.style.emptyStateSubtitleFont = CometChatTypography.Body.regular` | +| **Error State Title Color** | Text color for the title in the error state | `CometChatMessageList.style.errorStateTitleColor = CometChatTheme.textColorPrimary` | +| **Error State Title Font** | Font for the title in the error state | `CometChatMessageList.style.errorStateTitleFont = CometChatTypography.Heading3.bold` | +| **Error State Subtitle Color** | Text color for the subtitle in the error state | `CometChatMessageList.style.errorStateSubtitleColor = CometChatTheme.textColorSecondary` | +| **Error State Subtitle Font** | Font for the subtitle in the error state | `CometChatMessageList.style.errorStateSubtitleFont = CometChatTypography.Body.regular` | +| **Threaded Message Image** | Icon image for threaded messages | `CometChatMessageList.style.threadedMessageImage = UIImage(systemName: "arrow.turn.down.right")` | +| **Error Image** | Icon image for error state | `CometChatMessageList.style.errorImage = UIImage(named: "error-icon")` | +| **Empty Image** | Icon image for empty state | `CometChatMessageList.style.emptyImage = UIImage(named: "empty-icon")` | +| **New Message Indicator Image** | Icon image for new message indicator | `CometChatMessageList.style.newMessageIndicatorImage = UIImage?` | +| **New Message Indicator Text Color** | Text color for unread messages indicator | `CometChatMessageList.style.newMessageIndicatorTextColor = UIColor?` | +| **New Message Indicator Text Font** | Text font for unread messages indicator | `CometChatMessageList.style.newMessageIndicatorTextFont = UIFont?` | +| **New Message Indicator Background Color** | Background color for unread messages indicator | `CometChatMessageList.style.newMessageIndicatorBackgroundColor = UIColor?` | + +--- ### Functionality These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ------------------------------- | ------------------------------------------------------------ | ------------------------------------------- | -| hideAvatar | Hides the avatar of the sender. | `hideAvatar = true` | -| hideGroupActionMessages | Hides group action messages (like join/leave notifications). | `hideGroupActionMessages = true` | -| hideReplyInThreadOption | Hides the reply in thread option. | `hideReplyInThreadOption = true` | -| hideTranslateMessageOption | Hides the message translation option. | `hideTranslateMessageOption = true` | -| hideEditMessageOption | Hides the edit message option. | `hideEditMessageOption = true` | -| hideDeleteMessageOption | Hides the delete message option. | `hideDeleteMessageOption = true` | -| hideReactionOption | Hides the reaction option on messages. | `hideReactionOption = true` | -| hideMessagePrivatelyOption | Hides the option to message privately. | `hideMessagePrivatelyOption = true` | -| hideCopyMessageOption | Hides the option to copy a message. | `hideCopyMessageOption = true` | -| hideMessageInfoOption | Hides the message info option. | `hideMessageInfoOption = true` | -| hideHeaderView | Hides the header view of the message list. | `hideHeaderView = true` | -| hideFooterView | Hides the footer view of the message list. | `hideFooterView = true` | -| hideDateSeparator | Hides the date separator between messages. | `hideDateSeparator = true` | -| scrollToBottomOnNewMessages | Scrolls to the bottom when new messages arrive. | `scrollToBottomOnNewMessages = true` | -| hideReceipts | Hides the message read receipts (ticks). | `hideReceipts = true` | -| disableSoundForMessages | Disables the sound when a new message arrives. | `disableSoundForMessages = true` | -| hideEmptyView | Hides the empty state view when no messages are available. | `hideEmptyView = true` | -| hideErrorView | Hides the error view when an error occurs. | `hideErrorView = true` | -| hideLoadingView | Hides the loading view when fetching messages. | `hideLoadingView = true` | -| hideNewMessageIndicator | Hides the "new message" indicator. | `hideNewMessageIndicator = true` | -| scrollToBottom(isAnimated:) | Scrolls to the bottom of the message list. | `scrollToBottom(isAnimated: true)` | -| set(messageAlignment:) | Sets the alignment of messages in the list. | `set(messageAlignment: .left)` | -| set(smartRepliesKeywords:) | Sets keywords for smart replies. | `set(smartRepliesKeywords: ["Hi", "Bye"])` | -| set(smartRepliesDelayDuration:) | Sets the delay duration for smart replies. | `set(smartRepliesDelayDuration: 2)` | -| set(user:parentMessage:) | Sets the user and an optional parent message. | `set(user: user, parentMessage: message)` | -| set(group:parentMessage:) | Sets the group and an optional parent message. | `set(group: group, parentMessage: message)` | -| set(messagesRequestBuilder:) | Sets the message request builder. | `set(messagesRequestBuilder: builder)` | -| set(reactionsRequestBuilder:) | Sets the reactions request builder. | `set(reactionsRequestBuilder: builder)` | -| set(parentMessageId:) | Sets the parent message ID. | `set(parentMessageId: 12345)` | -| hideModerationView | Hides the moderation view in the AI assistant chat. | `hideModerationView = true` | -|hideThreadView | Hides the thread view in the AI assistant chat. | `hideThreadView = true` | -| set(suggestedMessages:) | List of predefined replies shown in the AI assistant. | `suggestedMessages = ["Hello", "Hi"]` | -| hideSuggestedMessages | Hides the suggested message replies. | `hideSuggestedMessages = true` | -| set(emptyChatGreetingView:) | Custom view displayed when the AI assistant chat is empty. | `emptyChatGreetingView = { /* custom view */ }` | -| set(streamingSpeed:) | Sets the speed of streaming for AI assistant messages. | `streamingSpeed = 50` | -| goToMessage(withId:) | Scrolls the message list to a specific message, making it visible to the user based on the provided message ID | `goToMessage(messageId: Int)` | -| startFromUnreadMessages | Starts the message list from the first unread message.. | `startFromUnreadMessages = true` | -| showMarkAsUnreadOption | Sets the visibility of the “Mark as unread” option in the message actions menu. | `showMarkAsUnreadOption = true` | - - -*** - -### Advance - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +Below is a list of customizations along with corresponding code snippets: + +| Property | Description | Code | +|----------|-------------|------| +| hideAvatar | Hides the avatar of the sender | `hideAvatar = true` | +| hideGroupActionMessages | Hides group action messages (like join/leave notifications) | `hideGroupActionMessages = true` | +| hideReplyInThreadOption | Hides the reply in thread option | `hideReplyInThreadOption = true` | +| hideTranslateMessageOption | Hides the message translation option | `hideTranslateMessageOption = true` | +| hideEditMessageOption | Hides the edit message option | `hideEditMessageOption = true` | +| hideDeleteMessageOption | Hides the delete message option | `hideDeleteMessageOption = true` | +| hideReactionOption | Hides the reaction option on messages | `hideReactionOption = true` | +| hideMessagePrivatelyOption | Hides the option to message privately | `hideMessagePrivatelyOption = true` | +| hideCopyMessageOption | Hides the option to copy a message | `hideCopyMessageOption = true` | +| hideMessageInfoOption | Hides the message info option | `hideMessageInfoOption = true` | +| hideHeaderView | Hides the header view of the message list | `hideHeaderView = true` | +| hideFooterView | Hides the footer view of the message list | `hideFooterView = true` | +| hideDateSeparator | Hides the date separator between messages | `hideDateSeparator = true` | +| scrollToBottomOnNewMessages | Scrolls to the bottom when new messages arrive | `scrollToBottomOnNewMessages = true` | +| hideReceipts | Hides the message read receipts (ticks) | `hideReceipts = true` | +| disableSoundForMessages | Disables the sound when a new message arrives | `disableSoundForMessages = true` | +| hideEmptyView | Hides the empty state view when no messages are available | `hideEmptyView = true` | +| hideErrorView | Hides the error view when an error occurs | `hideErrorView = true` | +| hideLoadingView | Hides the loading view when fetching messages | `hideLoadingView = true` | +| hideNewMessageIndicator | Hides the "new message" indicator | `hideNewMessageIndicator = true` | +| scrollToBottom(isAnimated:) | Scrolls to the bottom of the message list | `scrollToBottom(isAnimated: true)` | +| set(messageAlignment:) | Sets the alignment of messages in the list | `set(messageAlignment: .left)` | +| set(smartRepliesKeywords:) | Sets keywords for smart replies | `set(smartRepliesKeywords: ["Hi", "Bye"])` | +| set(smartRepliesDelayDuration:) | Sets the delay duration for smart replies | `set(smartRepliesDelayDuration: 2)` | +| set(user:parentMessage:) | Sets the user and an optional parent message | `set(user: user, parentMessage: message)` | +| set(group:parentMessage:) | Sets the group and an optional parent message | `set(group: group, parentMessage: message)` | +| set(messagesRequestBuilder:) | Sets the message request builder | `set(messagesRequestBuilder: builder)` | +| set(reactionsRequestBuilder:) | Sets the reactions request builder | `set(reactionsRequestBuilder: builder)` | +| set(parentMessageId:) | Sets the parent message ID | `set(parentMessageId: 12345)` | +| hideModerationView | Hides the moderation view in the AI assistant chat | `hideModerationView = true` | +| hideThreadView | Hides the thread view in the AI assistant chat | `hideThreadView = true` | +| set(suggestedMessages:) | List of predefined replies shown in the AI assistant | `suggestedMessages = ["Hello", "Hi"]` | +| hideSuggestedMessages | Hides the suggested message replies | `hideSuggestedMessages = true` | +| set(emptyChatGreetingView:) | Custom view displayed when the AI assistant chat is empty | `emptyChatGreetingView = { /* custom view */ }` | +| set(streamingSpeed:) | Sets the speed of streaming for AI assistant messages | `streamingSpeed = 50` | +| goToMessage(withId:) | Scrolls the message list to a specific message based on the provided message ID | `goToMessage(messageId: Int)` | +| startFromUnreadMessages | Starts the message list from the first unread message | `startFromUnreadMessages = true` | +| showMarkAsUnreadOption | Sets the visibility of the "Mark as unread" option in the message actions menu | `showMarkAsUnreadOption = true` | + +--- + +### Advanced + +For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. #### Date Time Formatter -The **CometChatMessageList** component supports full customization of how date and time are displayed using the [CometChatDateTimeFormatter](/ui-kit/ios/localize#datetimeformatter). +The `CometChatMessageList` component supports full customization of how date and time are displayed using the [CometChatDateTimeFormatter](/ui-kit/ios/localize#datetimeformatter). -This enables developers to localize, format, or personalize the date and time strings shown next to each message such as “Today”, “Yesterday”, “12:45 PM”, etc. +This enables developers to localize, format, or personalize the date and time strings shown next to each message such as "Today", "Yesterday", "12:45 PM", etc. -1. Component-Level (Global) +**1. Component-Level (Global)** ```swift +// Customize time format CometChatMessageList.dateTimeFormatter.time = { timestamp in return "at " + DateFormatter.localizedString(from: Date(timeIntervalSince1970: TimeInterval(timestamp)), dateStyle: .none, timeStyle: .short) } +// Customize today format CometChatMessageList.dateTimeFormatter.today = { timestamp in return "Today • \(formattedTime(from: timestamp))" } -CometChatMessageList.dateTimeFormatter.otherDay = { timestamp in // This will display older dates as "24 Apr 2025" instead of the default relative format. +// Customize older dates format +CometChatMessageList.dateTimeFormatter.otherDay = { timestamp in let formatter = DateFormatter() formatter.dateFormat = "dd MMM yyyy" return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) } ``` - - -2. Instance-Level (Local) +**2. Instance-Level (Local)** @@ -377,32 +355,30 @@ messageList.dateTimeFormatter.yesterday = { timestamp in return "Yesterday at " + formattedTime(from: timestamp) } ``` - - -##### Available closures +##### Available Closures -| Property | Description | Code | -| --------- | ------------------------------------------------------------------- | ------------------------------------------------------------ | -| time | Called to format a timestamp as a standard time (e.g., "12:30 PM"). | `CometChatMessageList.dateTimeFormatter.time = { ... }` | -| today | Called when rendering messages sent today. | `CometChatMessageList.dateTimeFormatter.today = { ... }` | -| yesterday | Called for yesterday's messages. | `CometChatMessageList.dateTimeFormatter.yesterday = { ... }` | -| lastweek | Called for messages within the last week. | `CometChatMessageList.dateTimeFormatter.lastweek = { ... }` | -| otherDay | Called for dates older than last week. | `CometChatMessageList.dateTimeFormatter.otherDay = { ... }` | -| minute | Called when referring to "a minute ago". | `CometChatMessageList.dateTimeFormatter.minute = { ... }` | -| minutes | Called for "x minutes ago". | `CometChatMessageList.dateTimeFormatter.minutes = { ... }` | -| hour | Called for "an hour ago". | `CometChatMessageList.dateTimeFormatter.hour = { ... }` | -| hours | Called for "x hours ago". | `CometChatMessageList.dateTimeFormatter.hours = { ... }` | +| Property | Description | Code | +|----------|-------------|------| +| time | Called to format a timestamp as a standard time (e.g., "12:30 PM") | `CometChatMessageList.dateTimeFormatter.time = { ... }` | +| today | Called when rendering messages sent today | `CometChatMessageList.dateTimeFormatter.today = { ... }` | +| yesterday | Called for yesterday's messages | `CometChatMessageList.dateTimeFormatter.yesterday = { ... }` | +| lastweek | Called for messages within the last week | `CometChatMessageList.dateTimeFormatter.lastweek = { ... }` | +| otherDay | Called for dates older than last week | `CometChatMessageList.dateTimeFormatter.otherDay = { ... }` | +| minute | Called when referring to "a minute ago" | `CometChatMessageList.dateTimeFormatter.minute = { ... }` | +| minutes | Called for "x minutes ago" | `CometChatMessageList.dateTimeFormatter.minutes = { ... }` | +| hour | Called for "an hour ago" | `CometChatMessageList.dateTimeFormatter.hour = { ... }` | +| hours | Called for "x hours ago" | `CometChatMessageList.dateTimeFormatter.hours = { ... }` | Each closure receives a timestamp (Int, representing UNIX time) and must return a String representing the formatted time. -*** +--- #### SetHeaderView -You can set custom headerView to the Message List component using the following method. +You can set a custom headerView to the Message List component using the following method: @@ -410,17 +386,17 @@ You can set custom headerView to the Message List component using the following let messageListView = CometChatMessageList() messageListView.set(headerView: CustomHeaderView) ``` - - -Following is the code of CustomHeaderView - UIView Class +Following is the code of CustomHeaderView - UIView Class: + + ```swift import UIKit @@ -448,7 +424,6 @@ class CustomHeaderView: UIViewController, UICollectionViewDelegate, UICollection return collectionView }() - override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.95, alpha: 1) @@ -522,7 +497,7 @@ class CustomHeaderViewCell: UICollectionViewCell { } private func setupUI() { - backgroundColor = UIColor(white: 0.95, alpha: 1) // Light purple background + backgroundColor = UIColor(white: 0.95, alpha: 1) layer.cornerRadius = 18 clipsToBounds = true @@ -547,14 +522,15 @@ class CustomHeaderViewCell: UICollectionViewCell { } } ``` + + -*** -#### SetFooterView +--- -You can set custom footerView to the Message List component using the following method. +#### SetFooterView -Example +You can set a custom footerView to the Message List component using the following method: @@ -562,17 +538,17 @@ Example let messageListView = CometChatMessageList(frame: .null) messageListView.set(footerView: CustomFooterView) ``` - - -Following is the code of CustomFooterView UIView Class +Following is the code of CustomFooterView UIView Class: + + ```swift import UIKit @@ -600,7 +576,6 @@ class CustomFooterView: UIViewController, UICollectionViewDelegate, UICollection return collectionView }() - override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0.95, alpha: 1) @@ -674,7 +649,7 @@ class CustomFooterViewCell: UICollectionViewCell { } private func setupUI() { - backgroundColor = UIColor(white: 0.95, alpha: 1) // Light purple background + backgroundColor = UIColor(white: 0.95, alpha: 1) layer.cornerRadius = 18 clipsToBounds = true @@ -699,20 +674,21 @@ class CustomFooterViewCell: UICollectionViewCell { } } ``` + + -*** +--- #### SetDateSeparatorPattern You can modify the date pattern of the message list date separator to your requirement using `setDateSeparatorPattern()`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. -**Example** - ```swift let messageListView = CometChatMessageList() -.set(user: user) + .set(user: user) + messageListView.set(dateSeparatorPattern: { timestamp in guard let timestamp = timestamp else { return "" @@ -723,24 +699,18 @@ messageListView.set(dateSeparatorPattern: { timestamp in return formatter.string(from: date) }) ``` - - - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- #### SetDatePattern -You can modify the date pattern to your requirement using .set(datePattern:). This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - -**Example** +You can modify the date pattern to your requirement using `.set(datePattern:)`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. @@ -748,7 +718,7 @@ You can modify the date pattern to your requirement using .set(datePattern:). Th let messageListView = CometChatMessageList() messageListView.set(datePattern: { timestamp in guard let timestamp = timestamp else { - return "" + return "" } let date = Date(timeIntervalSince1970: TimeInterval(timestamp/1000)) let formatter = DateFormatter() @@ -756,19 +726,15 @@ messageListView.set(datePattern: { timestamp in return formatter.string(from: date) }) ``` - - -*** +--- #### SetTimePattern You can modify the date pattern to your requirement using `.set(timePattern:)`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. -**Example** - ```swift @@ -780,43 +746,42 @@ messageListView.set(timePattern: { timestamp in return formatter.string(from: time) }) ``` - - -*** +--- #### SetTextFormatters This functionality dynamically assigns a list of text formatters. If a custom list is provided, it uses that list. Otherwise, it gracefully falls back to the default text formatters retrieved from the data source for seamless integration. -**Example** - -This code customizes a CometChat text formatter to identify and style the word "sure", with handling options for interactions like string search, scrolling, and item clicks. The custom formatter is then applied to CometChat messages. +This code customizes a CometChat text formatter to identify and style the word "sure", with handling options for interactions like string search, scrolling, and item clicks. The custom formatter is then applied to CometChat messages: -```ruby Swift + + +```swift let myCustomTextFormatter = MyCustomTextFormatter(trackingCharacter: "#") -let cometChatMessages = CometChatMessages() +let cometChatMessages = CometChatMessages() .set(user: user) .set(textFormatter: [myCustomTextFormatter]) ``` + + -Demonstration: +**Demonstration:** ```swift - import Foundation import CometChatSDK import CometChatUIKitSwift class MyCustomTextFormatter: CometChatTextFormatter { -override func getRegex() -> String { -return "(\\bsure\\b)" - + + override func getRegex() -> String { + return "(\\bsure\\b)" } override func getTrackingCharacter() -> Character { @@ -825,33 +790,32 @@ return "(\\bsure\\b)" override func search(string: String, suggestedItems: ((_: [SuggestionItem]) -> ())? = nil) { // This function would call an API or perform a local search - // For now, it does nothing } override func onScrollToBottom(suggestionItemList: [SuggestionItem], listItem: ((_: [SuggestionItem]) -> ())?) { // This function would call the next page of an API - // For now, it does nothing } override func onItemClick(suggestedItem: SuggestionItem, user: User?, group: Group?) { - // Do something with the clicked item + // Handle clicked item } override func handlePreMessageSend(baseMessage: BaseMessage, suggestionItemList: [SuggestionItem]) { - // This function would modify the message before it's sent - // For now, it does nothing + // Modify the message before it's sent } override func prepareMessageString( - baseMessage: BaseMessage, - regexString: String, - alignment: MessageBubbleAlignment = .left, - formattingType: FormattingType + baseMessage: BaseMessage, + regexString: String, + alignment: MessageBubbleAlignment = .left, + formattingType: FormattingType ) -> NSAttributedString { let attrString = NSMutableAttributedString(string: "SURE") - if alignment == .left { // Received message + if alignment == .left { + // Received message styling attrString.addAttribute(.foregroundColor, value: UIColor.blue, range: NSRange(location: 0, length: attrString.length)) - } else { // Sent message + } else { + // Sent message styling attrString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: 0, length: attrString.length)) } attrString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 18), range: NSRange(location: 0, length: attrString.length)) @@ -859,80 +823,71 @@ return "(\\bsure\\b)" } override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) { - // Your Action + // Handle text tap action } - } ``` - - -*** +--- #### SetTemplate and AddTemplate [CometChatMessageTemplate](/ui-kit/ios/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/ios/message-template). -*** +--- #### SetLoadingView -You can set a custom loading view using .set(loadingView:). This method accepts a UIView to display while data is being fetched. +You can set a custom loading view using `.set(loadingView:)`. This method accepts a UIView to display while data is being fetched. ```swift -let loadingIndicator = UIActivityIndicatorView(style: .medium) -loadingIndicator.startAnimating() -cometChatMessageList.set(loadingView: loadingIndicator) +let loadingIndicator = UIActivityIndicatorView(style: .medium) +loadingIndicator.startAnimating() +cometChatMessageList.set(loadingView: loadingIndicator) ``` - - -*** +--- #### SetErrorView -You can customize the error view using .set(errorView:). This method accepts a UIView that appears when an error occurs. +You can customize the error view using `.set(errorView:)`. This method accepts a UIView that appears when an error occurs. ```swift -let errorLabel = UILabel() -errorLabel.text = "Something went wrong!" -errorLabel.textColor = .red -cometChatMessageList.set(errorView: errorLabel) +let errorLabel = UILabel() +errorLabel.text = "Something went wrong!" +errorLabel.textColor = .red +cometChatMessageList.set(errorView: errorLabel) ``` - - -*** +--- #### SetEmptyView -You can customize the empty state view using .set(emptyView:). This method accepts a UIView that appears when no conversations are available. +You can customize the empty state view using `.set(emptyView:)`. This method accepts a UIView that appears when no conversations are available. ```swift -let emptyLabel = UILabel() -emptyLabel.text = "No conversations found" -emptyLabel.textColor = .gray -emptyLabel.textAlignment = .center -cometChatMessageList.set(emptyView: emptyLabel) +let emptyLabel = UILabel() +emptyLabel.text = "No conversations found" +emptyLabel.textColor = .gray +emptyLabel.textAlignment = .center +cometChatMessageList.set(emptyView: emptyLabel) ``` - - -*** +--- #### SetNewMessageIndicatorView @@ -941,37 +896,39 @@ Set a custom view for the unread message indicator. ```swift -let newMessageIndicatorView = NewUnreadMessageIndicator() -cometChatMessageList.set(newMessageIndicatorView:: newMessageIndicatorView) +let newMessageIndicatorView = NewUnreadMessageIndicator() +cometChatMessageList.set(newMessageIndicatorView: newMessageIndicatorView) class NewUnreadMessageIndicator: UIView { - // Your custom view + // Your custom view implementation } ``` - - -*** +--- - To ensure that the `MessageList` is properly configured, passing the controller is mandatory. -* Swift - ```swift let messageListView = CometChatMessageList() messageListView.set(controller: UIViewController) // Passing the controller is required ``` - -*** +--- - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - + +--- + +## Next Steps + +- [Message Composer](/ui-kit/ios/message-composer) — Customize the message input component +- [Message Header](/ui-kit/ios/message-header) — Display user/group details in the header +- [Message Template](/ui-kit/ios/message-template) — Create custom message bubble templates + +--- diff --git a/ui-kit/ios/message-template.mdx b/ui-kit/ios/message-template.mdx index 6a7b1ea46..79a18cfdf 100644 --- a/ui-kit/ios/message-template.mdx +++ b/ui-kit/ios/message-template.mdx @@ -1,12 +1,16 @@ --- title: "Message Template" +sidebarTitle: "Message Template" +description: "Define and customize the structure and behavior of message bubbles using CometChat UI Kit for iOS" --- ## Overview -A MessageTemplate provides you with the capability to define and customize both the structure and the behavior of the [MessageBubble](/ui-kit/ios/message-bubble-styling). It acts as a schema or design blueprint for the creation of a variety of [MessageBubble](/ui-kit/ios/message-bubble-styling) components, allowing you to manage the appearance and interactions of [MessageBubble](/ui-kit/ios/message-bubble-styling) within your application effectively and consistently. +A MessageTemplate provides you with the capability to define and customize both the structure and the behavior of the [MessageBubble](/ui-kit/ios/message-bubble-styling). It acts as a schema or design blueprint for creating a variety of message bubble components, allowing you to manage their appearance and interactions within your application effectively and consistently. -### Structure +--- + +## Structure @@ -24,216 +28,232 @@ The MessageBubble structure can typically be broken down into the following view 5. **Bottom view**: This view can be used to extend the MessageBubble with additional elements, such as link previews or a 'load more' button for long messages. It's typically placed beneath the Content view. -6. **Thread view**:This is where the thread reply icon and reply counts are displayed. It's located below the footer view. +6. **Thread view**: This is where the thread reply icon and reply counts are displayed. It's located below the footer view. 7. **Footer view**: This is where the timestamp of the message and its delivery or read status are displayed. It's located at the bottom of the MessageBubble. 8. **Status Info view**: This is where the timestamp of the message and its delivery or read status are displayed. It's located inside the MessageBubble just below the content view. -### Properties - -MessageTemplate provides you with methods that allow you to alter various properties of the MessageBubble. These properties include aspects such as the `type` and `category` of a message, the appearance and behavior of the header, content, and footer sections of the message bubble, - -1. **Type** +--- - Using `setType()` you can set the type of CometChatMessage, This will map your MessageTemplate to the corresponding CometChatMessage. You can set the MessageTemplates Type using the following code snippet. +## Properties - ```csharp +MessageTemplate provides you with methods that allow you to alter various properties of the MessageBubble. These properties include aspects such as the `type` and `category` of a message, the appearance and behavior of the header, content, and footer sections of the message bubble. - let type = "custom_template"//replace this with your own custom type +### 1. Type - //Creating a custom message template - let customMessageTemplate = - CometChatMessageTemplate(category: category, type: type, contentView: { message, alignment, controller in - return UIView() //replace this with your own UI for message list +Using `setType()` you can set the type of CometChatMessage. This will map your MessageTemplate to the corresponding CometChatMessage. You can set the MessageTemplate's Type using the following code snippet: - }, bubbleView: nil, headerView: nil, footerView: nil) { message, alignment, controller in - return UIView() //replace this with your own UI for message composer - } options: { message, group, controller in - return [CometChatMessageOption]() //replace this with your own options - } - ``` +```swift +let type = "custom_template" // Replace with your own custom type + +// Creating a custom message template +let customMessageTemplate = CometChatMessageTemplate( + category: category, + type: type, + contentView: { message, alignment, controller in + return UIView() // Replace with your own UI for message list + }, + bubbleView: nil, + headerView: nil, + footerView: nil +) { message, alignment, controller in + return UIView() // Replace with your own UI for message composer +} options: { message, group, controller in + return [CometChatMessageOption]() // Replace with your own options +} +``` -2. **Category** +### 2. Category Using `.setCategory()` you can set the category of a MessageTemplate. This will create a MessageTemplate with the specified category and link it with a CometChatMessage of the same category. Please refer to our guide on [Message Categories](/sdk/ios/message-structure-and-hierarchy) for a deeper understanding of message categories. -```csharp -let category = "custom_category"//replace this with your own category - -//Creating a custom message template -//You can also set UI for bubbleView, headerView and footerView instead of nil -let customMessageTemplate = - CometChatMessageTemplate(category: category, type: type, contentView: { message, alignment, controller in - return UIView() //replace this with your own UI for message list - - }, bubbleView: nil, headerView: nil, footerView: nil) { message, alignment, controller in - return UIView() //replace this with your own UI for message composer - } options: { message, group, controller in - return [CometChatMessageOption]() //replace this with your own options - } +```swift +let category = "custom_category" // Replace with your own category + +// Creating a custom message template +// You can also set UI for bubbleView, headerView and footerView instead of nil +let customMessageTemplate = CometChatMessageTemplate( + category: category, + type: type, + contentView: { message, alignment, controller in + return UIView() // Replace with your own UI for message list + }, + bubbleView: nil, + headerView: nil, + footerView: nil +) { message, alignment, controller in + return UIView() // Replace with your own UI for message composer +} options: { message, group, controller in + return [CometChatMessageOption]() // Replace with your own options +} ``` -3. **Header View** - - The .`template.headerView` method allows you to assign a custom header view to the MessageBubble. By default, it is configured to display the sender's name. +### 3. Header View - ```swift - var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() +The `template.headerView` method allows you to assign a custom header view to the MessageBubble. By default, it is configured to display the sender's name. - for (index, template) in allTemplates.enumerated() { - var template = template - template.headerView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - return UIView() +```swift +var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - } - } - ``` +for (index, template) in allTemplates.enumerated() { + var template = template + template.headerView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + return UIView() + } +} +``` -4. **Content View** +### 4. Content View - The `template.contentView` method allows you to assign a custom content view to the MessageBubble. By default, it displays the [Text Bubble](/ui-kit/ios/message-bubble-styling#text-bubble), [Image Bubble](/ui-kit/ios/message-bubble-styling-styling#image-bubble), [File Bubble](/ui-kit/ios/message-bubble-styling-styling), [Audio Bubble](/ui-kit/ios/message-bubble-styling-styling#audio-bubble), or [Video Bubble](/ui-kit/ios/message-bubble-styling#video-bubble), depending on the message type. +The `template.contentView` method allows you to assign a custom content view to the MessageBubble. By default, it displays the [Text Bubble](/ui-kit/ios/message-bubble-styling#text-bubble), [Image Bubble](/ui-kit/ios/message-bubble-styling#image-bubble), [File Bubble](/ui-kit/ios/message-bubble-styling), [Audio Bubble](/ui-kit/ios/message-bubble-styling#audio-bubble), or [Video Bubble](/ui-kit/ios/message-bubble-styling#video-bubble), depending on the message type. - ```swift - var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() +```swift +var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.contentView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - return UIView() +for (index, template) in allTemplates.enumerated() { + var template = template + template.contentView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + return UIView() } - } - ``` +} +``` -5. **Footer View** +### 5. Footer View - The `template.footerView` method allows you to assign a custom Footer view to the MessageBubble. By default, it displays the receipt and timestamp. +The `template.footerView` method allows you to assign a custom Footer view to the MessageBubble. By default, it displays the receipt and timestamp. - ```swift - var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() +```swift +var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.footerView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - return UIView() +for (index, template) in allTemplates.enumerated() { + var template = template + template.footerView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + return UIView() } - } - ``` +} +``` -6. **Bottom View** +### 6. Bottom View - The `template.bottomView` method allows you to assign a custom Bottom view to the MessageBubble.By defuault is has buttons such as link previews or a 'load more' button for long messages. +The `template.bottomView` method allows you to assign a custom Bottom view to the MessageBubble. By default, it has buttons such as link previews or a 'load more' button for long messages. - ```swift - var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() +```swift +var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.bottomView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - return UIView() +for (index, template) in allTemplates.enumerated() { + var template = template + template.bottomView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + return UIView() } - } - ``` +} +``` -7. **Bubble View** +### 7. Bubble View - The `template.bubbleView` method allows you to assign a custom Bubble view to the MessageBubble. By default, headerView, contentView, and footerView together form a message bubble. +The `template.bubbleView` method allows you to assign a custom Bubble view to the MessageBubble. By default, headerView, contentView, and footerView together form a message bubble. - ```swift - var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() +```swift +var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.bubbleView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - return UIView() +for (index, template) in allTemplates.enumerated() { + var template = template + template.bubbleView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + return UIView() } - } - ``` +} +``` -8. **Options** +### 8. Options - The `template.options` lets you set the list of actions that a user can perform on a message. This includes actions like reacting to, editing, or deleting a message. +The `template.options` lets you set the list of actions that a user can perform on a message. This includes actions like reacting to, editing, or deleting a message. - ```csharp - var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.options = { message, group, controller in - let loggedInUser = CometChat.getLoggedInUser() - let options = CometChatUIKit.getDataSource().getMessageOptions(loggedInUser: loggedInUser!, messageObject: message!, controller: controller, group: group) +```swift +var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - return options +for (index, template) in allTemplates.enumerated() { + var template = template + template.options = { message, group, controller in + let loggedInUser = CometChat.getLoggedInUser() + let options = CometChatUIKit.getDataSource().getMessageOptions( + loggedInUser: loggedInUser!, + messageObject: message!, + controller: controller, + group: group + ) + return options } - allTemplates[index] = template - } - ``` + allTemplates[index] = template +} +``` -*** +--- ## Customization Let's dive into how you can use the [properties](#properties) of MessageTemplate to customize an existing template or add a new one to the [MessageList](/ui-kit/ios/message-list) component. -The First step is to fetch the list of existing templates when you want to modify or add to them. This can be done using the getAllMessageTemplates() method from the DataSource of the CometChatUIKit class. +The first step is to fetch the list of existing templates when you want to modify or add to them. This can be done using the `getAllMessageTemplates()` method from the DataSource of the CometChatUIKit class: -```javascript -var messageTemplates : [CometChatMessageTemplate] = CometChatUIKit.getDataSource().getAllMessageTemplates() +```swift +var messageTemplates: [CometChatMessageTemplate] = CometChatUIKit.getDataSource().getAllMessageTemplates() ``` +--- + ### Existing Templates -You will need to first get the MessageTemplates object for the type of message you want to customize. You will be customizing the TextMessage Bubble here. The code snippet to get the Text MessageTemplate is as follows. +You will need to first get the MessageTemplates object for the type of message you want to customize. In this example, we'll customize the TextMessage Bubble. The code snippet to get the Text MessageTemplate is as follows: ```swift -var messageTemplates : [CometChatMessageTemplate] = CometChatUIKit.getDataSource().getAllMessageTemplates() +var messageTemplates: [CometChatMessageTemplate] = CometChatUIKit.getDataSource().getAllMessageTemplates() for i in 0.. - -You will be using `CometChatMessageBubble` Component for example here so to apply Template to Messages you will have to use [MessageList](/ui-kit/ios/message-list) component. +You will be using the `CometChatMessageBubble` Component for this example. To apply Template to Messages, you will have to use the [MessageList](/ui-kit/ios/message-list) component. -By utilizing this code snippet, you will retrieve `text templates`. +By utilizing this code snippet, you will retrieve text templates: ```swift -let messageTemplates : CometChatMessageTemplate = CometChatUIKit.getDataSource().getTextMessageTemplate() +// Get text message template +let messageTemplates: CometChatMessageTemplate = CometChatUIKit.getDataSource().getTextMessageTemplate() +// Configure message list with template let messageListConfiguration = MessageListConfiguration() .set(templates: [messageTemplates]) - +// Apply to CometChatMessages let cometChatMessages = CometChatMessages() .set(user: user) .set(messageListConfiguration: messageListConfiguration) ``` - - @@ -241,14 +261,12 @@ let cometChatMessages = CometChatMessages() - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- -#### Header view +#### Header View The `template.headerView` method of MessageTemplate allows you to add custom views to the header of your message bubbles. In the example below, we will add a custom UIView `custom_header_view` to the header view of every text message in the MessageList. @@ -256,10 +274,12 @@ The `template.headerView` method of MessageTemplate allows you to add custom vie -```swift custom_header_view + + + +```swift import UIKit import CometChatUIKitSwift -import UIKit class HeaderViewStyled: UIView { @@ -322,37 +342,36 @@ class HeaderViewStyled: UIView { } } ``` + + -```swift Swift +```swift var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { + +for (index, template) in allTemplates.enumerated() { var template = template template.headerView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in let customHeaderView = HeaderViewStyled() return customHeaderView - } - allTemplates[index] = template -} + } + allTemplates[index] = template +} let cometChatMessages = CometChatMessageList() cometChatMessages.set(templates: allTemplates) ``` - - - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- -#### Content view +#### Content View The `template.contentView` method of MessageTemplate allows you to add a custom view to the content of your message bubbles. In the example below, we will add a custom `custom_message_view_file` to the content view of every text message in the MessageList. @@ -361,9 +380,8 @@ The `template.contentView` method of MessageTemplate allows you to add a custom - - -```swift custom_message_view_file + +```swift import UIKit import CometChatSDK import CometChatUIKitSwift @@ -375,7 +393,7 @@ class ContentViewStyled: UIView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true - imageView.layer.cornerRadius = 8 // For rounded corners + imageView.layer.cornerRadius = 8 imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() @@ -411,7 +429,7 @@ class ContentViewStyled: UIView { // MARK: - Setup View private func setupView() { - backgroundColor = UIColor.systemGray6 // Light gray background + backgroundColor = UIColor.systemGray6 layer.cornerRadius = 12 layer.masksToBounds = true @@ -425,11 +443,10 @@ class ContentViewStyled: UIView { // MARK: - Constraints private func setupConstraints() { NSLayoutConstraint.activate([ - // Product Image View Constraints productImageView.topAnchor.constraint(equalTo: topAnchor, constant: 16), productImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), productImageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), - productImageView.heightAnchor.constraint(equalTo: productImageView.widthAnchor), // Keep it square + productImageView.heightAnchor.constraint(equalTo: productImageView.widthAnchor), buyNowButton.topAnchor.constraint(equalTo: productImageView.bottomAnchor, constant: 16), buyNowButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), @@ -450,49 +467,46 @@ class ContentViewStyled: UIView { } } ``` - - -```swift Swift +```swift var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.contentView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - let customView = ContentViewStyled() - return customView - } - allTemplates[index] = template -} + +for (index, template) in allTemplates.enumerated() { + var template = template + template.contentView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + let customView = ContentViewStyled() + return customView + } + allTemplates[index] = template +} let cometChatMessages = CometChatMessageList() cometChatMessages.set(templates: allTemplates) ``` - - - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- #### Bottom View -The `template.bottomView `method of MessageTemplate allows you to add a custom button view to your message bubbles. In the example below, we will add a custom UIView `custom_bottom_view_file` to the bottom view of every text message in the MessageList. +The `template.bottomView` method of MessageTemplate allows you to add a custom button view to your message bubbles. In the example below, we will add a custom UIView `custom_bottom_view_file` to the bottom view of every text message in the MessageList. -```swift custom_bottom_view_file + + +```swift import UIKit class BottomViewStyled: UIView { @@ -549,35 +563,34 @@ class BottomViewStyled: UIView { } } ``` + + -```swift Swift +```swift var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.bottomView = { (baseMessage: BaseMessage?, bubbleAlignment:MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - let customView = BottomViewStyled() - return customView - } - allTemplates[index] = template -} + +for (index, template) in allTemplates.enumerated() { + var template = template + template.bottomView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + let customView = BottomViewStyled() + return customView + } + allTemplates[index] = template +} let cometChatMessages = CometChatMessageList() cometChatMessages.set(templates: allTemplates) ``` - - - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- #### Footer View @@ -587,7 +600,9 @@ The `template.footerView` method of MessageTemplate allows you to add a footer v -```swift custom_footer_view + + +```swift import UIKit class FooterViewStyled: UIView { @@ -613,7 +628,6 @@ class FooterViewStyled: UIView { addSubview(reactionsStackView) NSLayoutConstraint.activate([ - reactionsStackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), reactionsStackView.topAnchor.constraint(equalTo: topAnchor, constant: 8), reactionsStackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), @@ -633,39 +647,47 @@ class FooterViewStyled: UIView { } } ``` + + -```swift Swiftjavascript + + +```swift var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.footerView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - let customView = FooterViewStyled() - return customView - } - allTemplates[index] = template -} + +for (index, template) in allTemplates.enumerated() { + var template = template + template.footerView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + let customView = FooterViewStyled() + return customView + } + allTemplates[index] = template +} let cometChatMessages = CometChatMessageList() cometChatMessages.set(templates: allTemplates) ``` + + - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** + +--- #### Bubble View -The` template.bubbleView` method of MessageTemplate allows you to add a bubble view to your message bubbles. In the example below, we will add a custom UIView `custom_bubble_view` to the bubble view of every text message in the MessageList. +The `template.bubbleView` method of MessageTemplate allows you to add a bubble view to your message bubbles. In the example below, we will add a custom UIView `custom_bubble_view` to the bubble view of every text message in the MessageList. -```swift custom_bubble_view + + +```swift import UIKit class CustomMessageView: UIView { @@ -691,7 +713,7 @@ class CustomMessageView: UIView { private let doubleTickImageView: UIImageView = { let imageView = UIImageView() - imageView.image = UIImage(named: "double_tick") // Add your double tick image here + imageView.image = UIImage(named: "double_tick") imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView @@ -717,6 +739,7 @@ class CustomMessageView: UIView { // MARK: - Initialization init(message: BaseMessage) { super.init(frame: .zero) + // Add subviews addSubview(bubbleView) addSubview(timeStackView) @@ -748,10 +771,13 @@ class CustomMessageView: UIView { doubleTickImageView.widthAnchor.constraint(equalToConstant: 16), doubleTickImageView.heightAnchor.constraint(equalToConstant: 16) ]) + + // Configure with message data if let textMessage = message as? TextMessage { messageLabel.text = textMessage.text var status = "Sent" doubleTickImageView.image = UIImage(named: "single-tick") + if textMessage.readAt > 0 { status = "Read" doubleTickImageView.image = UIImage(named: "message-read") @@ -766,7 +792,6 @@ class CustomMessageView: UIView { timeLabel.text = "\(time)" } - } required init?(coder: NSCoder) { @@ -774,29 +799,34 @@ class CustomMessageView: UIView { } } ``` + + -```swift Swiftjavascript + + +```swift var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.bubbleView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in - let customBubbleView = CustomBubbleView() - return customBubbleView - } - allTemplates[index] = template + +for (index, template) in allTemplates.enumerated() { + var template = template + template.bubbleView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> (UIView)? in + let customBubbleView = CustomBubbleView() + return customBubbleView + } + allTemplates[index] = template } let cometChatMessages = CometChatMessages() cometChatMessages.set(templates: allTemplates) ``` + + - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- #### Options List @@ -808,16 +838,25 @@ However, if you wish to override or modify these options, you can use the `templ -```swift Swiftphp + + +```swift var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() + for (index, template) in allTemplates.enumerated() { var template = template template.options = { message, group, controller in let loggedInUser = CometChat.getLoggedInUser() - var options = CometChatUIKit.getDataSource().getMessageOptions(loggedInUser: loggedInUser!, messageObject: message!, controller: controller, group: group) + var options = CometChatUIKit.getDataSource().getMessageOptions( + loggedInUser: loggedInUser!, + messageObject: message!, + controller: controller, + group: group + ) + for (index, option) in (options ?? []).enumerated() { if option.id == "replyInThread" { - + // Create custom options let forwardOption = CometChatMessageOption(id: "customOptionId", title: "Forward", icon: UIImage(systemName: "chevron.right")) let favoriteOption = CometChatMessageOption(id: "favoriteOptionId", title: "Mark as Favorite", icon: UIImage(systemName: "star")) let deleteOption = CometChatMessageOption(id: "deleteOptionId", title: "Delete", icon: UIImage(systemName: "trash")) @@ -826,22 +865,21 @@ for (index, template) in allTemplates.enumerated() { } } return options ?? [] - } allTemplates[index] = template -} +} let cometChatMessages = CometChatMessageList() cometChatMessages.set(templates: allTemplates) ``` + + - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- #### Status Info View @@ -853,7 +891,9 @@ In the example below, we will integrate a custom UIView file named `custom_statu -```swift custom_status_view + + +```swift import UIKit import CometChatSDK import CometChatUIKitSwift @@ -871,7 +911,7 @@ class StatusInfoView: UIView { private let doubleTickImageView: UIImageView = { let imageView = UIImageView() - imageView.image = UIImage(named: "double_tick") // Add your double tick image here + imageView.image = UIImage(named: "double_tick") imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView @@ -889,6 +929,7 @@ class StatusInfoView: UIView { // MARK: - Initialization init(baseMessage: BaseMessage) { super.init(frame: .zero) + // Add subviews addSubview(timeStackView) timeStackView.addArrangedSubview(timeLabel) @@ -906,9 +947,11 @@ class StatusInfoView: UIView { doubleTickImageView.heightAnchor.constraint(equalToConstant: 16) ]) + // Configure with message data if let textMessage = baseMessage as? TextMessage { var status = "Sent" doubleTickImageView.image = UIImage(named: "single-tick") + if textMessage.readAt > 0 { status = "Read" doubleTickImageView.image = UIImage(named: "message-read") @@ -930,103 +973,114 @@ class StatusInfoView: UIView { } } ``` + + -```swift Swift + + +```swift var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() - for (index, template) in allTemplates.enumerated() { - var template = template - template.statusInfoView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> UIView? in - if let baseMessage = baseMessage { - return CustomStatusView(baseMessage: baseMessage) - } - return nil + +for (index, template) in allTemplates.enumerated() { + var template = template + template.statusInfoView = { (baseMessage: BaseMessage?, bubbleAlignment: MessageBubbleAlignment, viewController: UIViewController?) -> UIView? in + if let baseMessage = baseMessage { + return CustomStatusView(baseMessage: baseMessage) } + return nil + } allTemplates[index] = template } let cometChatMessages = CometChatMessages() cometChatMessages.set(templates: allTemplates) ``` + + - Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- ### New Template -You can create an entirely new template for custom messages is one of the powerful features of CometChat's MessageTemplate. To add a new template, you can create a new one and then add it to the list of existing templates. +Creating an entirely new template for custom messages is one of the powerful features of CometChat's MessageTemplate. To add a new template, you can create a new one and then add it to the list of existing templates. First, let's see how to send a custom message: -```swift Swift -//Creating a text template -let textTemplate = CometChatUIKit.getDataSource() - .getTextMessageTemplate() + + +```swift +// Creating a text template +let textTemplate = CometChatUIKit.getDataSource().getTextMessageTemplate() -// set content view for TextMessage template +// Set content view for TextMessage template textTemplate.contentView = { message, alignment, controller in - // Create your own content view and return - return UIView() + // Create your own content view and return + return UIView() } -// set bubble view for TextMessage template +// Set bubble view for TextMessage template textTemplate.bubbleView = { message, alignment, controller in - // Create your own bubble view and return - return UIView() + // Create your own bubble view and return + return UIView() } -//Creating an audio template -let audioTemplate = CometChatUIKit.getDataSource() - .getAudioMessageTemplate() +// Creating an audio template +let audioTemplate = CometChatUIKit.getDataSource().getAudioMessageTemplate() -// set content view for AudioMessage template +// Set content view for AudioMessage template audioTemplate.contentView = { message, alignment, controller in - // Create your own content view and return - return UIView() + // Create your own content view and return + return UIView() } -// set bubble view for AudioMessage template +// Set bubble view for AudioMessage template audioTemplate.bubbleView = { message, alignment, controller in - // Create your own bubble view and return - return UIView() + // Create your own bubble view and return + return UIView() } +let type = "custom_template" // Replace with your own custom type +let category = "custom_category" // Replace with your own category + +// Creating a custom message template +// You can also set UI for bubbleView, headerView and footerView instead of nil +let customMessageTemplate = CometChatMessageTemplate( + category: category, + type: type, + contentView: { message, alignment, controller in + return UIView() // Replace with your own UI for message list + }, + bubbleView: nil, + headerView: nil, + footerView: nil +) { message, alignment, controller in + return UIView() // Replace with your own UI for message composer +} options: { message, group, controller in + return [CometChatMessageOption]() // Replace with your own options +} -let type = "custom_template"//replace this with your own custom type -let category = "custom_category"//replace this with your own category - -//Creating a custom message template -//You can also set UI for bubbleView, headerView and footerView instead of nil -let customMessageTemplate = - CometChatMessageTemplate(category: category, type: type, contentView: { message, alignment, controller in - return UIView() //replace this with your own UI for message list - - }, bubbleView: nil, headerView: nil, footerView: nil) { message, alignment, controller in - return UIView() //replace this with your own UI for message composer - } options: { message, group, controller in - return [CometChatMessageOption]() //replace this with your own options - } - -//custom list of templates +// Custom list of templates let messageTypes = [ - textTemplate, - audioTemplate, - customMessageTemplate - ] + textTemplate, + audioTemplate, + customMessageTemplate +] var templates = [(type: String, template: CometChatMessageTemplate)]() for template in messageTypes { - templates.append((type: template.type, template: template)) + templates.append((type: template.type, template: template)) } -//passing template list to cometchatMessages - let messageList = CometChatMessageList() - messageList.set(templates: templates) +// Passing template list to message list +let messageList = CometChatMessageList() +messageList.set(templates: templates) ``` + + Find the example below: @@ -1034,7 +1088,9 @@ Find the example below: -```swift Swift + + +```swift import UIKit class CustomBubbleView: UIView { @@ -1044,9 +1100,9 @@ class CustomBubbleView: UIView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true - imageView.layer.cornerRadius = 25 // Half of width/height to make it circular + imageView.layer.cornerRadius = 25 imageView.translatesAutoresizingMaskIntoConstraints = false - imageView.image = UIImage(named: "profile_placeholder") // Replace with your image + imageView.image = UIImage(named: "profile_placeholder") return imageView }() @@ -1072,7 +1128,7 @@ class CustomBubbleView: UIView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false - imageView.image = UIImage(named: "double_tick") // Replace with your double-tick image + imageView.image = UIImage(named: "double_tick") return imageView }() @@ -1200,9 +1256,19 @@ class CustomBubbleView: UIView { } } ``` + + +Make sure to set new type and category in the message Request builder in order to fetch those respective messages as shown in the example above. + -Make sure to set new type and category in to the message Request builder in order to fetch those respective messages as shown in the example below. +--- - +## Next Steps + +- [Message List](/ui-kit/ios/message-list) — Display and customize the message list +- [Message Bubble Styling](/ui-kit/ios/message-bubble-styling) — Customize message bubble appearance +- [Message Composer](/ui-kit/ios/message-composer) — Customize the message input component + +--- From db92552fd0827646d08929d9071f0b4e37d26c2d Mon Sep 17 00:00:00 2001 From: Aditya Date: Fri, 13 Feb 2026 15:51:13 +0530 Subject: [PATCH 014/106] modified methods , ongoing-call, outgoing-call, overview, property-changes --- ui-kit/ios/methods.mdx | 118 ++--- ui-kit/ios/ongoing-call.mdx | 95 ++-- ui-kit/ios/outgoing-call.mdx | 163 +++---- ui-kit/ios/overview.mdx | 64 +-- ui-kit/ios/property-changes.mdx | 816 ++++++++++---------------------- 5 files changed, 422 insertions(+), 834 deletions(-) diff --git a/ui-kit/ios/methods.mdx b/ui-kit/ios/methods.mdx index 9e57c6f5d..6004762f5 100644 --- a/ui-kit/ios/methods.mdx +++ b/ui-kit/ios/methods.mdx @@ -4,29 +4,25 @@ title: "Methods" ## Overview -The UI Kit's core function is to extend the [CometChat SDK](/sdk/ios/overview), essentially translating the raw data and functionality provided by the underlying methods into visually appealing and easy-to-use UI components. +The UI Kit's core function is to extend the [CometChat SDK](/sdk/ios/overview), translating raw data and functionality into visually appealing, easy-to-use UI components. -To effectively manage and synchronize the UI elements and data across all components in the UI Kit, we utilize internal events. These internal events enable us to keep track of changes in real-time and ensure that the UI reflects the most current state of data. +To effectively manage and synchronize UI elements and data across all components, the UI Kit uses internal events. These events enable real-time change tracking and ensure the UI reflects the most current state of data. -The CometChat UI Kit has thoughtfully encapsulated the critical [CometChat SDK](/sdk/ios/overview) methods within its wrapper to efficiently manage internal eventing. This layer of abstraction simplifies interaction with the underlying CometChat SDK, making it more user-friendly for developers. +The CometChat UI Kit encapsulates critical [CometChat SDK](/sdk/ios/overview) methods within its wrapper to efficiently manage internal eventing. This abstraction layer simplifies interaction with the underlying SDK, making it more developer-friendly. ## Methods -You can access the methods using the `CometChatUIKit` class. This class provides access to all the public methods exposed by the CometChat UI Kit. +Access all public methods exposed by the CometChat UI Kit through the `CometChatUIKit` class. ### Init -As a developer, you need to invoke this method every time before you use any other methods provided by the UI Kit. - -This initialization is a critical step that ensures the UI Kit and Chat SDK function correctly and as intended in your application. Typical practice is to make this one of the first lines of code executed in your application's lifecycle when it comes to implementing CometChat. +You must invoke this method before using any other UI Kit methods. This initialization ensures the UI Kit and Chat SDK function correctly in your application. Best practice is to make this one of the first lines of code executed in your application's lifecycle. - -Make sure you replace the **APP\_ID**, **REGION** and **AUTH\_KEY** with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#login-using-auth-token) to log in securely. - +Replace **APP_ID**, **REGION**, and **AUTH_KEY** with your CometChat App ID, Region, and Auth Key. The `Auth Key` is an optional property of the `UIKitSettings` class, intended primarily for proof-of-concept (POC) development or early stages of application development. For production, use [Auth Token](#login-using-auth-token) instead. -Here's the table format for the properties available in `UIKitSettings`: +#### UIKitSettings Properties | Method | Type | Description | | ------------------------------------ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | @@ -40,9 +36,7 @@ Here's the table format for the properties available in `UIKitSettings`: | **setAIFeatures** | `List` | Sets the AI Features that need to be added in UI Kit | | **setExtensions** | `List` | Sets the list of extension that need to be added in UI Kit | -*** - -The concluding code block: +#### Example @@ -63,18 +57,14 @@ CometChatUIKit.init(uiKitSettings: uikitSettings) { result in } } ``` - - -*** +--- ### Login using Auth Key -Only the `UID` of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, we suggest you use [AuthToken](#login-using-auth-token) instead of Auth Key. - -The concluding code block: +Only the `UID` of a user is needed to log in. This simple authentication procedure is useful for POC or development phases. For production apps, use [AuthToken](#login-using-auth-token) instead. @@ -88,23 +78,19 @@ CometChatUIKit.login(uid: "uid") { (result) in } } ``` - - -*** +--- ### Login using Auth Token -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. +This advanced authentication procedure does not use the Auth Key directly in your client code, ensuring better security. 1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. 2. [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database. 3. Load the Auth Token in your client and pass it to the `login(authToken:)` method. -The concluding code block: - ```swift @@ -117,18 +103,14 @@ CometChatUIKit.login(authToken: "your_authToken") { (result) in } } ``` - - -*** +--- ### Logout -The CometChat UI Kit and Chat SDK effectively handle the session of the logged-in user within the framework. Before a new user logs in, it is crucial to clean this data to avoid potential conflicts or unexpected behavior. This can be achieved by invoking the `.logout(user:)` function. - -The concluding code block: +The CometChat UI Kit and Chat SDK handle the session of the logged-in user within the framework. Before a new user logs in, clean this data to avoid potential conflicts or unexpected behavior by invoking the `.logout(user:)` function. @@ -144,18 +126,14 @@ CometChatUIKit.logout(user: user) { (result) in } } ``` - - -*** +--- ### Create User -As a developer, you can dynamically create users on CometChat using the `.create(user:)` function. This can be extremely useful for situations where users are registered or authenticated by your system and then need to be created on CometChat. - -The concluding code block: +Dynamically create users on CometChat using the `.create(user:)` function. This is useful when users are registered or authenticated by your system and need to be created on CometChat. @@ -171,20 +149,16 @@ CometChatUIKit.create(user: user) { result in } } ``` - - -*** +--- ### Base Message #### Text Message -As a developer, if you need to send a text message to a single user or a group, you'll need to utilize the `sendTextMessage()` function. This function requires a `TextMessage` object as its argument, which contains the necessary information for delivering the message. - -The concluding code block: +To send a text message to a single user or a group, use the `sendTextMessage()` function. This function requires a `TextMessage` object containing the necessary information for delivering the message. @@ -198,20 +172,18 @@ textMessage.parentMessageId = parentMessageId CometChatUIKit.sendTextMessage(message: textMessage) ``` - - -> It's essential to understand the difference between `CometChatUIKit.sendTextMessage()` and `CometChat.sendTextMessage()`. When you use `CometChatUIKit.sendTextMessage()`, it automatically adds the message to the [MessagesComponent](/ui-kit/android/message-header) and [ConversationsComponent](/ui-kit/android/conversations), taking care of all related cases for you. On the other hand, `CometChat.sendTextMessage()` only sends the message and doesn't automatically update these components in the UI Kit. + +`CometChatUIKit.sendTextMessage()` automatically adds the message to the [MessagesComponent](/ui-kit/ios/message-list) and [ConversationsComponent](/ui-kit/ios/conversations), handling all related cases for you. In contrast, `CometChat.sendTextMessage()` only sends the message without updating these UI Kit components. + -*** +--- #### Media Message -As a developer, if you need to send a media message to a single user or a group, you'll need to utilize the `sendMediaMessage()` function. This function requires a `MediaMessage` object as its argument, which contains the necessary information for delivering the message. - -The concluding code block: +To send a media message to a single user or a group, use the `sendMediaMessage()` function. This function requires a `MediaMessage` object containing the necessary information for delivering the message. @@ -226,20 +198,18 @@ mediaMessage.parentMessageId = parentMessageId CometChatUIKit.sendMediaMessage(message: MediaMessage) ``` - - -> It's essential to understand the difference between `CometChatUIKit.sendMediaMessage()` and `CometChat.sendMediaMessage()`. When you use `CometChatUIKit.sendMediaMessage()`, it automatically adds the message to the [MessagesComponent](/ui-kit/ios/message-header) and [ConversationsComponent](/ui-kit/ios/conversations), taking care of all related cases for you. On the other hand, `CometChat.sendMediaMessage()` only sends the message and doesn't automatically update these components in the UI Kit. + +`CometChatUIKit.sendMediaMessage()` automatically adds the message to the [MessagesComponent](/ui-kit/ios/message-list) and [ConversationsComponent](/ui-kit/ios/conversations), handling all related cases for you. In contrast, `CometChat.sendMediaMessage()` only sends the message without updating these UI Kit components. + -*** +--- #### Custom Message -As a developer, if you need to send a custom message to a single user or a group, you'll need to utilize the `sendCustomMessage()` function. This function requires a `CustomMessage` object as its argument, which contains the necessary information for delivering the message. - -The concluding code block: +To send a custom message to a single user or a group, use the `sendCustomMessage()` function. This function requires a `CustomMessage` object containing the necessary information for delivering the message. @@ -254,22 +224,20 @@ customMessage.sender = CometChat.getLoggedInUser() CometChatUIKit.sendCustomMessage(message: CustomMessage) ``` - - -> It's essential to understand the difference between `CometChatUIKit.sendCustomMessage()` and `CometChat.sendCustomMessage()`. When you use `CometChatUIKit.sendCustomMessage()`, it automatically adds the message to the [MessagesComponent](/ui-kit/ios/message-header) and [ConversationsComponent](/ui-kit/ios/conversations), taking care of all related cases for you. On the other hand, `CometChat.sendCustomMessage()` only sends the message and doesn't automatically update these components in the UI Kit. + +`CometChatUIKit.sendCustomMessage()` automatically adds the message to the [MessagesComponent](/ui-kit/ios/message-list) and [ConversationsComponent](/ui-kit/ios/conversations), handling all related cases for you. In contrast, `CometChat.sendCustomMessage()` only sends the message without updating these UI Kit components. + -*** +--- ### Interactive Message #### Form Message -As a developer, if you need to send a Form message to a single user or a group, you'll need to utilize the `sendFormMessage()` function. This function requires a `FormMessage` object as its argument, which contains the necessary information to create a form bubble for that messages - -The concluding code block: +To send a Form message to a single user or a group, use the `sendFormMessage()` function. This function requires a `FormMessage` object containing the necessary information to create a form bubble for that message. @@ -295,18 +263,14 @@ CometChatUIKit.sendFormMessage(formMessage) { form in print("CometChat exception: \(error)") } ``` - - -*** +--- #### Card Message -As a developer, if you need to send a Card message to a single user or a group, you'll need to utilize the `sendCardMessage()` function. This function requires a `CardMessage` object as its argument, which contains the necessary information to create a card bubble for the messages. - -The concluding code block: +To send a Card message to a single user or a group, use the `sendCardMessage()` function. This function requires a `CardMessage` object containing the necessary information to create a card bubble for the message. @@ -328,18 +292,14 @@ CometChatUIKit.sendCardMessage(cardMessage) { success in print("CometChat exception: \(error)") } ``` - - -*** +--- #### Scheduler Message -As a developer, if you need to send a Scheduler message to a single user or a group, you'll need to utilize the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object as its argument, which contains the necessary information to create a SchedulerMessage bubble for the messages. - -The concluding code block: +To send a Scheduler message to a single user or a group, use the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object containing the necessary information to create a scheduler bubble for the message. @@ -355,9 +315,7 @@ CometChatUIKit.sendSchedulerMessage(schedulerMessage: schedulerMessage) { schedu print("CometChat exception: \(error)") } ``` - - -*** +--- diff --git a/ui-kit/ios/ongoing-call.mdx b/ui-kit/ios/ongoing-call.mdx index f7715039e..1870f8ba7 100644 --- a/ui-kit/ios/ongoing-call.mdx +++ b/ui-kit/ios/ongoing-call.mdx @@ -10,13 +10,13 @@ The `Ongoing Call` is a [Component](/ui-kit/ios/components-overview#components) -*** +--- ## Usage ### Integration -`CometChatOngoingCall` being a custom **view controller**, offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. +`CometChatOngoingCall` is a custom view controller that offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. @@ -29,50 +29,43 @@ cometChatOngoingCall.set(sessionID: sessionID) cometChatOngoingCall.modalPresentationStyle = .fullScreen self.present(cometChatOngoingCall, animated: true) ``` - - - If you are already using a navigation controller, you can use the `pushViewController` function instead of presenting the view controller. - ### Actions [Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. -##### 1. SetOnCallEnded +#### 1. SetOnCallEnded -The `setOnCallEnded` action is typically triggered when the call is ended, carrying out default actions. However, with the following code snippet, you can effortlessly customize or override this default behavior to meet your specific needs. +The `setOnCallEnded` action is typically triggered when the call ends, carrying out default actions. You can customize or override this default behavior using the following code snippet: ```swift let cometChatOngoingCall = CometChatOngoingCall() .setOnCallEnded { call in - //Perform Your Action - + // Perform your action } ``` - - -*** +--- ### Filters -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria for a more customized experience. Filters can be applied using RequestBuilders of the Chat SDK. -You can adjust the `callSettingsBuilder` in the `OnGoing Call` Component to customize the OnGoing Call. Numerous options are available to alter the builder to meet your specific needs. For additional details on `CallSettingsBuilder`, please visit [CallSettingsBuilder](/sdk/ios/direct-calling). +You can adjust the `callSettingsBuilder` in the OnGoing Call Component to customize the call. Numerous options are available to alter the builder to meet your specific needs. For additional details on `CallSettingsBuilder`, visit [CallSettingsBuilder](/sdk/ios/direct-calling). -##### 1. CallSettingsBuilder +#### 1. CallSettingsBuilder -The [CallSettingsBuilder](/sdk/ios/direct-calling) enables you to filter and customize the call list based on available parameters in CallSettingsBuilder. This feature allows you to create more specific and targeted queries during the call. The following are the parameters available in [CallSettingsBuilder](/sdk/ios/direct-calling) +The [CallSettingsBuilder](/sdk/ios/direct-calling) enables you to filter and customize the call list based on available parameters. This feature allows you to create more specific and targeted queries during the call. | Methods | Description | Code | | -------------------------------- | -------------------------------------------- | ----------------------------------------- | @@ -98,9 +91,9 @@ The [CallSettingsBuilder](/sdk/ios/direct-calling) enables you to filter and cus | **setVideoContainer** | Set the video container | `.setVideoContainer(NSMutableDictionary)` | | **setVideoSettings** | Set the video settings | `.setVideoSettings(NSMutableDictionary)` | -**Example** +#### Example -In the example below, we are applying a filter to the calls. +In the example below, we are applying a filter to the calls: @@ -116,24 +109,18 @@ let cometChatOngoingCall = CometChatOngoingCall() cometChatOngoingCall.modalPresentationStyle = .fullScreen self.present(cometChatOngoingCall, animated: true) ``` - - - -Ensure to include an `NSMicrophoneUsageDescription` key with a descriptive string value in the app's Info.plist - +Ensure to include an `NSMicrophoneUsageDescription` key with a descriptive string value in the app's Info.plist. -*** +--- ### Events -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -Events emitted by the Ongoing Call component is as follows. +[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events, you can extend existing functionality. Being global events, they can be applied in multiple locations and can be added or removed as needed. | Event | Description | | --------------- | ------------------------------------------------ | @@ -142,67 +129,61 @@ Events emitted by the Ongoing Call component is as follows. ```swift -// View controller from your project where you want to listen events. +// View controller from your project where you want to listen to events public class ViewController: UIViewController { public override func viewDidLoad() { super.viewDidLoad() - // Subscribing for the listener to listen events from user module + // Subscribe to the listener for call events CometChatCallEvents.addListener("UNIQUE_ID", self as CometChatCallEventListener) } - } - // Listener events from user module -extension ViewController: CometChatCallEventListener { + +// Listener for call events +extension ViewController: CometChatCallEventListener { func onCallEnded(call: Call) { - // Do Stuff + // Handle call ended } } ``` -```swift Emitting Group Events -//emit this when logged in user cancels a call +```swift Emitting Call Events +// Emit this when logged in user ends a call CometChatCallEvents.emitOnCallEnded(call: Call) ``` - - -*** - -```swift View Controller +```swift public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from user module + // Unsubscribe from the listener CometChatCallEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") } ``` - - -*** +--- ## Customization -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +To fit your app's design requirements, you can customize the appearance of the component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. ### Style -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Using Style, you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. The OngoingCall component does not have any exposed Styles. -*** +--- ### Functionality -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +These are small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. @@ -214,28 +195,22 @@ let cometChatOngoingCall = CometChatOngoingCall() cometChatOngoingCall.modalPresentationStyle = .fullScreen self.present(cometChatOngoingCall, animated: true) ``` - - - -If you are already using a navigation controller, you can use the pushViewController function instead of presenting the view controller. - +If you are already using a navigation controller, you can use the `pushViewController` function instead of presenting the view controller. -Below is a list of customizations along with corresponding code snippets - | Property | Description | Code | | ---------------- | ---------------------------------------------- | ------------------------- | -| **CallWorkFlow** | Sets the call type to default and direct. | `CallWorkFlow` | -| **Session Id** | Sets the user object for CometChatOngoingCall. | `.set(sessionId: String)` | +| **CallWorkFlow** | Sets the call type to default or direct. | `CallWorkFlow` | +| **Session Id** | Sets the session ID for CometChatOngoingCall. | `.set(sessionId: String)` | ### Advanced -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. The `OngoingCall` component does not provide additional functionalities beyond this level of customization. -*** +--- diff --git a/ui-kit/ios/outgoing-call.mdx b/ui-kit/ios/outgoing-call.mdx index 11519e75e..822de157b 100644 --- a/ui-kit/ios/outgoing-call.mdx +++ b/ui-kit/ios/outgoing-call.mdx @@ -4,19 +4,19 @@ title: "Outgoing Call" ## Overview -The `Outgoing Call` [Component](/ui-kit/ios/components-overview#components) is a visual representation of a user-initiated call, whether it's a voice or video call. It serves as an interface for managing outgoing calls, providing users with essential options to control the call experience. This component typically includes information about the call recipient, call controls for canceling the call, and feedback on the call status, such as indicating when the call is in progress. +The `Outgoing Call` [Component](/ui-kit/ios/components-overview#components) is a visual representation of a user-initiated call, whether voice or video. It serves as an interface for managing outgoing calls, providing users with essential options to control the call experience. This component typically includes information about the call recipient, call controls for canceling the call, and feedback on the call status, such as indicating when the call is in progress. -*** +--- ## Usage ### Integration -`CometChatOutgoingCall` being a custom **view controller**, offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. +`CometChatOutgoingCall` is a custom view controller that offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. @@ -27,74 +27,62 @@ cometChatOutgoingCall.set(call: call) cometChatOutgoingCall.modalPresentationStyle = .fullScreen self.present(cometChatOutgoingCall, animated: true) ``` - - - If you are already using a navigation controller, you can use the `pushViewController` function instead of presenting the view controller. - ### Actions [Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. -##### 1. SetOnCancelClick +#### 1. SetOnCancelClick -The `setOnCancelClick` action is typically triggered when the call is ended, carrying out default actions. However, with the following code snippet, you can effortlessly customize or override this default behavior to meet your specific needs. +The `setOnCancelClick` action is typically triggered when the call is canceled, carrying out default actions. You can customize or override this default behavior using the following code snippet: ```swift let cometChatOutgoingCall = CometChatOutgoingCall() cometChatOutgoingCall.set(onCancelClick: { call, controller in -//Perform Your Action + // Perform your action }) ``` - - -*** +--- -##### 2. OnError +#### 2. OnError -You can customize this behavior by using the provided code snippet to override the `On Error` and improve error handling. +You can customize error handling behavior by using the provided code snippet to override the `onError` callback: ```swift - let incomingCallConfiguration = CometChatOutgoingCall() -.set(onError:{ error in -//Perform Your Action - +.set(onError: { error in + // Perform your action }) ``` - - -*** +--- ### Filters -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria for a more customized experience. Filters can be applied using RequestBuilders of the Chat SDK. The OutgoingCall component does not have any exposed filters. -*** +--- ### Events -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -Events emitted by the Outgoing call component is as follows. +[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events, you can extend existing functionality. Being global events, they can be applied in multiple locations and can be added or removed as needed. | Event | Description | | -------------------------- | -------------------------------------------- | @@ -104,70 +92,64 @@ Events emitted by the Outgoing call component is as follows. ```swift -// View controller from your project where you want to listen events. +// View controller from your project where you want to listen to events public class ViewController: UIViewController { public override func viewDidLoad() { super.viewDidLoad() - // Subscribing for the listener to listen events from user module + // Subscribe to the listener for call events CometChatCallEvents.addListener("UNIQUE_ID", self as CometChatCallEventListener) } - } - // Listener events from user module -extension ViewController: CometChatCallEventListener { + +// Listener for call events +extension ViewController: CometChatCallEventListener { func onOutgoingCallAccepted(call: Call) { - // Do Stuff + // Handle call accepted } - func onOutgoingCallRejected(call: Call){ - // Do Stuff + func onOutgoingCallRejected(call: Call) { + // Handle call rejected } } ``` -```swift Emitting Group Events -//emit this when the other user accepts the call +```swift Emitting Call Events +// Emit this when the other user accepts the call CometChatCallEvents.emitOnOutgoingCallAccepted(call: Call) -//emit this when the other user rejects a call +// Emit this when the other user rejects a call CometChatCallEvents.emitOnOutgoingCallRejected(call: Call) ``` - - -*** - -```swift View Controller +```swift public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from user module + // Unsubscribe from the listener CometChatCallEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") } ``` - - -*** +--- ## Customization -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +To fit your app's design requirements, you can customize the appearance of the component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. ### Style -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Using Style, you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. -##### 1. OutgoingCall Style +#### 1. OutgoingCall Style -You can customize the appearance of the `OutgoingCall` Component by applying the `OutgoingCallStyle` to it using the following code snippet. +You can customize the appearance of the `OutgoingCall` Component by applying the `OutgoingCallStyle` to it. **Global level styling** @@ -183,9 +165,7 @@ CometChatOutgoingCall.style.callLabelFont = UIFont(name: "Times-New-Roman", size CometChatOutgoingCall.style.declineButtonCornerRadius = .init(cornerRadius: 8) CometChatOutgoingCall.avatarStyle = customAvatarStyle ``` - - **Instance level styling** @@ -206,16 +186,14 @@ let outgoingCall = CometChatOutgoingCall() outgoingCall.style = outgoingCallStyle outgoingCall.avatarStyle = customAvatarStyle ``` - - -List of properties exposed by OutgoingCallStyle +#### OutgoingCallStyle Properties | Property | Description | Code | | ------------------------------ | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | @@ -230,15 +208,15 @@ List of properties exposed by OutgoingCallStyle | `declineButtonBackgroundColor` | Sets the background color for the decline button in the outgoing call view. | `CometChatOutgoingCall.style.declineButtonBackgroundColor = UIColor()` | | `declineButtonIconTint` | Sets the tint color for the decline button icon. | `CometChatOutgoingCall.style.declineButtonIconTint = UIColor()` | | `declineButtonIcon` | Sets the icon for the decline button. | `CometChatOutgoingCall.style.declineButtonIcon = UIImage(systemName: "phone.down.fill")` | -| `declineButtonCornerRadius` | Sets the corner radius for decline button. | `CometChatOutgoingCall.style.declineButtonCornerRadius: CometChatCornerStyle?` | -| `declineButtonBorderColor` | Sets the border color for decline button. | `CometChatOutgoingCall.style.declineButtonBorderColor: UIColor?` | -| `declineButtonBorderWidth` | Sets the border width for decline button. | `CometChatOutgoingCall.style.declineButtonBorderWidth: CGFloat?` | +| `declineButtonCornerRadius` | Sets the corner radius for the decline button. | `CometChatOutgoingCall.style.declineButtonCornerRadius: CometChatCornerStyle?` | +| `declineButtonBorderColor` | Sets the border color for the decline button. | `CometChatOutgoingCall.style.declineButtonBorderColor: UIColor?` | +| `declineButtonBorderWidth` | Sets the border width for the decline button. | `CometChatOutgoingCall.style.declineButtonBorderWidth: CGFloat?` | -*** +--- ### Functionality -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. +These are small functional customizations that allow you to fine-tune the overall experience of the component. | Property | Description | Code | | ---------------------- | --------------------------------------- | ------------------------------- | @@ -247,11 +225,11 @@ These are a set of small functional customizations that allow you to fine-tune t ### Advanced -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. -#### SetAvatarVieww +#### SetAvatarView -With this function, you can assign a custom view to the avatar of OutgoingCall Component. +With this function, you can assign a custom view to the avatar of the OutgoingCall Component. @@ -261,20 +239,20 @@ cometChatOutgoingCall.set(avatarView: { call in return customView }) ``` - - -Demonstration +**Demonstration** -You can create a CustomAvatarView as a custom `UIView`. +You can create a `CustomAvatarView` as a custom `UIView`: -```swift swift + + +```swift import UIKit class CustomAvatarView: UIView { @@ -339,12 +317,14 @@ class CustomAvatarView: UIView { } } ``` + + -*** +--- #### SetCancelView -You can modify the cancel call view of a Outgoing call component using the property below. +You can modify the cancel call view of the Outgoing call component using the property below: @@ -354,18 +334,16 @@ cometChatOutgoingCall.set(cancelView: { call in return view }) ``` - - -Demonstration +**Demonstration** -You can create a CustomCancelView as a custom `UIView`. +You can create a `CustomCancelView` as a custom `UIView`: @@ -420,38 +398,34 @@ class EndCallButton: UIButton { } } ``` - - -*** +--- #### SetTitleView -You can customize the title view of a outgoing call component using the property below. +You can customize the title view of the outgoing call component using the property below: ```swift cometChatOutgoingCall.set(titleView: { call in let view = CustomTitleView() - view.configure(call:call) + view.configure(call: call) return view }) ``` - - -Demonstration +**Demonstration** -You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()` +You can create a `CustomTitleView` as a custom `UIView`: @@ -471,27 +445,24 @@ class CustomTitleView: UILabel { } private func setupView() { - font = UIFont.boldSystemFont(ofSize: 22) textAlignment = .center translatesAutoresizingMaskIntoConstraints = false } - func configure(call:Call){ - text = "\(call.callInitiator <> \(call.receiver))" + func configure(call: Call) { + text = "\(call.callInitiator) <> \(call.receiver)" } } ``` - - -*** +--- #### SetSubtitleView -You can modify the subtitle view of a outgoing call component using the property below. +You can modify the subtitle view of the outgoing call component using the property below: @@ -501,18 +472,16 @@ cometChatOutgoingCall.set(subtitleView: { call in return view }) ``` - - -Demonstration +**Demonstration** -You can create a CustomSubtitleView as a custom `UIView`. +You can create a `CustomSubtitleView` as a custom `UIView`: @@ -558,9 +527,7 @@ class CustomSubtitleView: UIStackView { } } ``` - - -*** +--- diff --git a/ui-kit/ios/overview.mdx b/ui-kit/ios/overview.mdx index aa00a339f..3d54a09be 100644 --- a/ui-kit/ios/overview.mdx +++ b/ui-kit/ios/overview.mdx @@ -1,32 +1,33 @@ --- title: "CometChat UI Kit For iOS" sidebarTitle: "Overview" +description: "Integrate chat functionality into iOS applications with prebuilt, modular, and customizable UI components" --- -The **CometChat UI Kit** for iOS provides a seamless solution to integrate chat functionality into your iOS applications. With prebuilt, modular, and customizable UI components, it accelerates development and ensures your chat application is robust, scalable, and tailored to your needs. +The CometChat UI Kit for iOS provides a seamless solution to integrate chat functionality into your iOS applications. With prebuilt, modular, and customizable UI components, it accelerates development and ensures your chat application is robust, scalable, and tailored to your needs. -*** +--- -## **Why Choose CometChat UI Kit?** +## Why Choose CometChat UI Kit? -* **Effortless Integration** – Ready-to-use SwiftUI components for rapid implementation. -* **Highly Customizable** – Adapt UI components easily to match your brand and user experience requirements. -* **Built on Core SDK** – Leverages the powerful [CometChat iOS SDK](/sdk/ios/overview) for reliable performance. -* **Scalable & Reliable** – Optimized for enterprise-grade applications. +- Effortless Integration: Ready-to-use SwiftUI components for rapid implementation +- Highly Customizable: Adapt UI components to match your brand and user experience requirements +- Built on Core SDK: Leverages the powerful [CometChat iOS SDK](/sdk/ios/overview) for reliable performance +- Scalable & Reliable: Optimized for enterprise-grade applications -*** +--- -## **User Interface Preview** +## User Interface Preview -*** +--- -## **Download the CometChat Demo App** +## Download the CometChat Demo App -Get started with the **CometChat UI Kit** on your mobile device: +Get started with the CometChat UI Kit on your mobile device: **Download from the App Store** @@ -39,36 +40,35 @@ Get started with the **CometChat UI Kit** on your mobile device: -**Tip:** On iOS, simply open the camera app and scan the QR code to install directly. - +On iOS, open the camera app and scan the QR code to install directly. -*** +--- -## **Getting Started** +## Getting Started -Before integrating the CometChat UI Kit, familiarize yourself with the key concepts and features offered by CometChat’s platform. +Before integrating the CometChat UI Kit, familiarize yourself with the key concepts and features offered by CometChat's platform: -* Review the [Key Concepts](/fundamentals/key-concepts) to understand essential terminology and features. -* Follow the [Getting Started Guide](/ui-kit/ios/getting-started) for detailed steps on initial setup and integration. +- Review the [Key Concepts](/fundamentals/key-concepts) to understand essential terminology and features +- Follow the [Getting Started Guide](/ui-kit/ios/getting-started) for detailed steps on initial setup and integration -*** +--- -## **Integration and Customization** +## Integration and Customization The CometChat UI Kit consists of modular SwiftUI components that can be integrated effortlessly into your app, offering flexible customization: -* **Prebuilt UI Components:** Ready-to-use chat UI elements. -* **Modular Structure:** Easy to integrate and modify. -* **Customization Options:** Highly configurable to fit your brand and UI requirements. +- Prebuilt UI Components: Ready-to-use chat UI elements +- Modular Structure: Easy to integrate and modify +- Customization Options: Highly configurable to fit your brand and UI requirements Explore more about UI customization in the [Customization Guide](/ui-kit/ios/theme-introduction). -*** +--- -## **Helpful Resources** +## Helpful Resources -Explore these essential resources to gain a deeper understanding of **CometChat UI Kits** and streamline your integration process. +Explore these essential resources to gain a deeper understanding of CometChat UI Kits and streamline your integration process. #### 🚀 iOS Sample App @@ -88,13 +88,13 @@ UI design resources for customization and prototyping. [View on Figma](https://www.figma.com/community/file/1444325479486807899/cometchat-ui-kit-for-ios) -*** +--- -## **💡 Need Help?** +## Need Help? If you need assistance, check out: -* 💬 [Developer Community](http://community.cometchat.com/) -* ❓ [Support Portal](https://help.cometchat.com/hc/en-us/requests/new) +- 💬 [Developer Community](http://community.cometchat.com/) +- ❓ [Support Portal](https://help.cometchat.com/hc/en-us/requests/new) -*** +--- diff --git a/ui-kit/ios/property-changes.mdx b/ui-kit/ios/property-changes.mdx index 42d568992..695f1d34a 100644 --- a/ui-kit/ios/property-changes.mdx +++ b/ui-kit/ios/property-changes.mdx @@ -1,8 +1,12 @@ --- title: "Property Changes" +sidebarTitle: "Property Changes" +description: "Migration guide for property changes between UI Kit versions for iOS" --- +This document outlines the property changes between v4 and v5 of the CometChat UI Kit for iOS. Use this guide to update your implementation when migrating to the latest version. +--- ## Conversations @@ -15,23 +19,23 @@ title: "Property Changes" | hideLoadingState | Bool | Hides the loading state indicator. | | hideDeleteConversationOption | Bool | Hides the option to delete a conversation. | | hideGroupType | Bool | Hides the group type indicator (private/public). | -| backgroundDrawable | UIImage | Used to set a background image for the conversation screen. | -| separatorColor | UIColor | Used to set the color of separators in the conversation list. | -| separatorWidth | CGFloat | Used to set the width of separators in the conversation list. | -| errorTextColor | UIColor | Used to set the color of error messages in the conversation UI. | -| lastMessageTextColor | UIColor | Used to set the color of the last message text in the conversation list. | -| typingIndicatorColor | UIColor | Used to set the color of the typing indicator in the conversation UI. | -| lastMessageAppearance | UIFont | Used to customize the appearance of the last message text in the list. | -| threadIndicatorAppearance | UIFont | Used to customize the appearance of thread indicators in the list. | -| dateTimeFormatter.time | Closure | Called to format a timestamp as a standard time (e.g., "12:30 PM"). | -| dateTimeFormatter.today | Closure | Called when rendering messages sent today. | -| dateTimeFormatter.yesterday | Closure | Called for yesterday's messages. | -| dateTimeFormatter.lastweek | Closure | Called for messages within the last week. | -| dateTimeFormatter.otherDay | Closure | Called for dates older than last week. | -| dateTimeFormatter.minute | Closure | Called when referring to "a minute ago". | -| dateTimeFormatter.minutes | Closure | Called for "x minutes ago". | -| dateTimeFormatter.hour | Closure | Called for "an hour ago". | -| dateTimeFormatter.hours | Closure | Called for "x hours ago". | +| backgroundDrawable | UIImage | Sets a background image for the conversation screen. | +| separatorColor | UIColor | Sets the color of separators in the conversation list. | +| separatorWidth | CGFloat | Sets the width of separators in the conversation list. | +| errorTextColor | UIColor | Sets the color of error messages in the conversation UI. | +| lastMessageTextColor | UIColor | Sets the color of the last message text in the conversation list. | +| typingIndicatorColor | UIColor | Sets the color of the typing indicator in the conversation UI. | +| lastMessageAppearance | UIFont | Customizes the appearance of the last message text in the list. | +| threadIndicatorAppearance | UIFont | Customizes the appearance of thread indicators in the list. | +| dateTimeFormatter.time | Closure | Formats a timestamp as a standard time (e.g., "12:30 PM"). | +| dateTimeFormatter.today | Closure | Formats messages sent today. | +| dateTimeFormatter.yesterday | Closure | Formats yesterday's messages. | +| dateTimeFormatter.lastweek | Closure | Formats messages within the last week. | +| dateTimeFormatter.otherDay | Closure | Formats dates older than last week. | +| dateTimeFormatter.minute | Closure | Formats "a minute ago". | +| dateTimeFormatter.minutes | Closure | Formats "x minutes ago". | +| dateTimeFormatter.hour | Closure | Formats "an hour ago". | +| dateTimeFormatter.hours | Closure | Formats "x hours ago". | | set(OnItemLongClick:) | Method | Triggered when you long press on a ListItem of the Conversations component. | | set(onEmpty:) | Method | Triggered when the conversations list is empty. | @@ -48,44 +52,47 @@ title: "Property Changes" | setOnSelection | set(onSelection:) | Method | Triggered upon completion of selection. | | setOnError | set(onError:) | Method | Override action when an error occurs. | + ### Removed Properties | Name | Type | Description | | -------------------- | ------------ | ----------------------------------------------------------------------------------- | -| hide(separator: Bool) | Bool | Used to control visibility of separators in the list view (replaced by style properties). | -| disable(typing: Bool) | Bool | Used to toggle visibility of typing indicator. | -| setDatePattern | Method | Method to set custom date pattern (replaced by dateTimeFormatter object). | +| hide(separator: Bool) | Bool | Controlled visibility of separators (replaced by style properties). | +| disable(typing: Bool) | Bool | Toggled visibility of typing indicator. | +| setDatePattern | Method | Set custom date pattern (replaced by dateTimeFormatter object). | | protectedGroupIcon | UIImage | Icon shown for password protected groups. | | sentIcon | UIImage | Receipt icon shown when message status is sent. | | deliveredIcon | UIImage | Receipt icon shown when message status is delivered. | | readIcon | UIImage | Receipt icon shown when message status is read. | +--- + ## Users ### New Properties | Name | Type | Description | | -------------------------------- | --------------------------------- | -------------------------------------------------------------------------------------------------- | -| set(options:) | (User) -> [CometChatUserOption] | Used to define custom options for each user. | -| add(options:) | [CometChatUserOption] | Used to dynamically add options to users. | -| set(leadingView:) | (User) -> UIView | Custom leading view to be rendered for each user in the fetched list. | -| set(titleView:) | (User) -> UIView | Custom title view to be rendered for each user in the fetched list. | -| set(trailView:) | (User) -> UIView | Custom trailing view to be rendered for each user in the fetched list. | +| set(options:) | (User) -> [CometChatUserOption] | Defines custom options for each user. | +| add(options:) | [CometChatUserOption] | Dynamically adds options to users. | +| set(leadingView:) | (User) -> UIView | Custom leading view for each user in the fetched list. | +| set(titleView:) | (User) -> UIView | Custom title view for each user in the fetched list. | +| set(trailView:) | (User) -> UIView | Custom trailing view for each user in the fetched list. | | set(onEmpty:) | () -> Void | Triggered when the users list is empty. | | hideErrorView | Bool | Hides the error state view. | | hideNavigationBar | Bool | Hides or shows the navigation bar. | | hideBackButton | Bool | Hides the back button. | | hideLoadingState | Bool | Hides the loading state indicator. | | hideUserStatus | Bool | Hides the online/offline status of users. | -| hideSectionHeader | Bool | Hides the section header for table view indicating initials of users. | +| hideSectionHeader | Bool | Hides the section header indicating initials of users. | | hideSearch | Bool | Hides the search bar. | | set(searchKeyword:) | String | Sets a search keyword for filtering users. | | set(userRequestBuilder:) | UsersRequest.UsersRequestBuilder | Sets a custom request builder for fetching users. | | set(searchRequestBuilder:) | UsersRequest.UsersRequestBuilder | Sets a custom request builder for searching users. | | listItemSelectedImage | UIImage | Image shown when a list item is selected. | | listItemDeSelectedImage | UIImage | Image shown when a list item is deselected. | -| searchIconTintColor | UIColor | Tint color for the search icon in the search bar. | -| searchBarStyle | UISearchBar.Style | Style of the search bar (e.g., default, prominent). | +| searchIconTintColor | UIColor | Tint color for the search icon. | +| searchBarStyle | UISearchBar.Style | Style of the search bar. | | searchTintColor | UIColor? | Tint color for the search bar elements. | | searchBarTintColor | UIColor? | Background color for the search bar (excluding text input). | | searchBarPlaceholderTextColor | UIColor? | Color of the placeholder text in the search bar. | @@ -99,23 +106,23 @@ title: "Property Changes" | borderWidth | CGFloat | Border width for the search bar or container. | | borderColor | UIColor | Color of the border. | | cornerRadius | CometChatCornerStyle | Corner radius for search bar or other elements. | -| titleColor | UIColor | Text color for title elements within the list or navigation bar. | +| titleColor | UIColor | Text color for title elements. | | titleFont | UIFont | Font for title text. | | largeTitleColor | UIColor | Text color for large titles. | | largeTitleFont | UIFont? | Font for large titles. | | navigationBarTintColor | UIColor | Tint color for the navigation bar background. | -| navigationBarItemsTintColor | UIColor | Tint color for navigation bar items (buttons, icons). | -| errorTitleTextFont | UIFont | Font for the error title displayed in UI. | +| navigationBarItemsTintColor | UIColor | Tint color for navigation bar items. | +| errorTitleTextFont | UIFont | Font for the error title. | | errorTitleTextColor | UIColor | Text color for the error title. | | errorSubTitleFont | UIFont | Font for the subtitle of error messages. | | errorSubTitleTextColor | UIColor | Text color for the subtitle of error messages. | -| retryButtonTextColor | UIColor | Text color for the retry button in error states. | +| retryButtonTextColor | UIColor | Text color for the retry button. | | retryButtonTextFont | UIFont | Font for the retry button text. | | retryButtonBackgroundColor | UIColor | Background color for the retry button. | | retryButtonBorderColor | UIColor | Border color for the retry button. | | retryButtonBorderWidth | CGFloat | Border width for the retry button. | | retryButtonCornerRadius | CometChatCornerStyle? | Corner radius for the retry button. | -| emptyTitleTextFont | UIFont | Font for the empty state title (when no users/items are present). | +| emptyTitleTextFont | UIFont | Font for the empty state title. | | emptyTitleTextColor | UIColor | Text color for the empty state title. | | emptySubTitleFont | UIFont | Font for the subtitle in the empty state. | | emptySubTitleTextColor | UIColor | Text color for the subtitle in the empty state. | @@ -131,39 +138,42 @@ title: "Property Changes" | listItemSelectionImageTint | UIColor | Tint color for selection indicator in list items. | | listItemSelectedBackground | UIColor | Background color for selected list items. | | listItemDeSelectedImageTint | UIColor | Tint color for the deselected state image. | -| headerTitleColor | UIColor | Text color for section header titles in the list. | +| headerTitleColor | UIColor | Text color for section header titles. | | headerTitleFont | UIFont | Font for section header titles. | ### Renamed Properties | Name | Type | Description | Old Name | | ---------------------- | ------------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------- | -| set(listItemView:) | (User) -> UIView | Custom list item view to be rendered for each user in the list. | setListItemView | -| set(subtitleView:) | (User) -> UIView | Custom subtitle view to be rendered for each user in the fetched list. | setSubtitleView | -| set(emptyView:) | UIView | Custom empty state view to be displayed when the user list is empty. | setEmptyStateView | -| set(errorView:) | UIView | Custom error state view to be displayed when an error occurs while fetching users. | setErrorStateView | -| set(onItemClick:) | (User) -> Void | Triggered when you click on a ListItem of the users component. | setOnItemClick | -| set(onItemLongClick:) | (User) -> Void | Triggered when you long press on a ListItem of the users component. | setOnItemLongClick | -| set(onBack:) | () -> Void | Triggered when the back button is pressed in the users component. | setOnBack | -| set(onSelection:) | ([User]) -> Void | Triggered on every selection when selection mode is set to multiple or single. | setOnSelection | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs in the users component. | setOnError | +| set(listItemView:) | (User) -> UIView | Custom list item view for each user in the list. | setListItemView | +| set(subtitleView:) | (User) -> UIView | Custom subtitle view for each user in the fetched list. | setSubtitleView | +| set(emptyView:) | UIView | Custom empty state view when the user list is empty. | setEmptyStateView | +| set(errorView:) | UIView | Custom error state view when an error occurs while fetching users. | setErrorStateView | +| set(onItemClick:) | (User) -> Void | Triggered when you click on a ListItem. | setOnItemClick | +| set(onItemLongClick:) | (User) -> Void | Triggered when you long press on a ListItem. | setOnItemLongClick | +| set(onBack:) | () -> Void | Triggered when the back button is pressed. | setOnBack | +| set(onSelection:) | ([User]) -> Void | Triggered on every selection when selection mode is set. | setOnSelection | +| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | setOnError | ### Removed Properties | Name | Type | Description | | ------------------------ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| set(loadingStateView:) | UIActivityIndicatorView.Style | Used to set size of loading view icon while fetching the list of users. | -| hide(errorText:) | Bool | Used to hide error text on fetching users. | -| show(backButton:) | Bool | Used to toggle visibility for back button. | -| set(searchIcon:) | UIImage? | Used to set search Icon in the search field. | -| hide(search:) | Bool | Used to toggle visibility for search box. | -| hide(separator:) | Bool | Used to hide the divider separating the user items. | -| disable(userPresence:) | Bool | Used to control visibility of user indicator shown if user is online. | -| set(emptyStateText:) | String | Used to set a custom text response when fetching the users has returned an empty list. | -| set(errorStateText:) | String | Used to set a custom text response when some error occurs on fetching the list of users. | -| set(searchPlaceholder:) | String | Used to set search placeholder text. | -| set(title:mode:) | String, UINavigationItem.LargeTitleDisplayMode | Used to set title in the app with display mode. | -| setOnLoad | ([User]) -> Void | Gets triggered when a user list is fully fetched and displayed on the screen. | +| set(loadingStateView:) | UIActivityIndicatorView.Style | Set size of loading view icon while fetching users. | +| hide(errorText:) | Bool | Hide error text on fetching users. | +| show(backButton:) | Bool | Toggle visibility for back button. | +| set(searchIcon:) | UIImage? | Set search icon in the search field. | +| hide(search:) | Bool | Toggle visibility for search box. | +| hide(separator:) | Bool | Hide the divider separating user items. | +| disable(userPresence:) | Bool | Control visibility of user online indicator. | +| set(emptyStateText:) | String | Set custom text when fetching users returns an empty list. | +| set(errorStateText:) | String | Set custom text when an error occurs fetching users. | +| set(searchPlaceholder:) | String | Set search placeholder text. | +| set(title:mode:) | String, UINavigationItem.LargeTitleDisplayMode | Set title with display mode. | +| setOnLoad | ([User]) -> Void | Triggered when a user list is fully fetched and displayed. | + + +--- ## Groups @@ -171,62 +181,62 @@ title: "Property Changes" | Name | Type | Description | | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -| set(onSelection:) | Closure | Gets triggered when selection mode is set to multiple or single. Triggers on every selection and returns the list of selected groups. | -| set(onEmpty:) | Closure | Gets triggered when the groups list is empty in CometChatGroups. | -| setOnLoad | Closure | Gets triggered when a group list is fully fetched and going to be displayed on the screen. Returns the list of groups to be displayed. | +| set(onSelection:) | Closure | Triggered when selection mode is set. Returns the list of selected groups. | +| set(onEmpty:) | Closure | Triggered when the groups list is empty. | +| setOnLoad | Closure | Triggered when a group list is fully fetched and displayed. | | listItemSelectedImage | UIImage | Check box image when a list item is selected. | | listItemDeSelectedImage | UIImage | Check box image when a list item is deselected. | -| searchIconTintColor | UIColor | Tint color for the search icon, defaults to the secondary icon color from CometChatTheme. | -| searchBarStyle | UISearchBarStyle | Style of the search bar, defaulting to the standard style. | -| searchTintColor | UIColor | Tint color for the search bar, defaults to the primary color from CometChatTheme. | -| searchBarTintColor | UIColor | Background color of the search bar, defaulting to clear. | -| searchBarPlaceholderTextColor | UIColor | Placeholder text color for the search bar, defaults to the tertiary text color from CometChatTheme. | -| searchBarPlaceholderTextFont | UIFont | Font used for the placeholder text in the search bar, defaults to regular body font. | -| searchBarTextColor | UIColor | Color of the text entered in the search bar, defaults to the primary text color from CometChatTheme. | -| searchBarTextFont | UIFont | Font used for the text in the search bar, defaults to regular body font. | -| searchBarBackgroundColor | UIColor | Background color of the search bar, defaults to a specific background color from CometChatTheme. | -| searchBarCancelIconTintColor | UIColor | Tint color for the cancel icon in the search bar, defaults to the primary color from CometChatTheme. | -| searchBarCrossIconTintColor | UIColor | Tint color for the cross icon in the search bar, defaults to the secondary icon color from CometChatTheme. | -| backgroundColor | UIColor | Background color of the overall view, defaults to a specific background color from CometChatTheme. | -| borderWidth | CGFloat | Width of the border around the view, defaults to 0 (no border). | -| borderColor | UIColor | Color of the border around the view, defaults to clear. | -| cornerRadius | CometChatCornerStyle | Corner radius settings for the view, defaults to no corner radius. | -| titleColor | UIColor | Color for the title text, defaults to the primary text color from CometChatTheme. | -| titleFont | UIFont | Font used for the title text, defaults to nil (not set). | -| largeTitleColor | UIColor | Color for the large title text, defaults to the primary text color from CometChatTheme. | -| largeTitleFont | UIFont | Font used for the large title text, defaults to nil (not set). | -| navigationBarTintColor | UIColor | Background color of the navigation bar, defaults to a specific background color from CometChatTheme. | -| navigationBarItemsTintColor | UIColor | Tint color for items in the navigation bar, defaults to the highlight color from CometChatTheme. | -| errorTitleTextFont | UIFont | Font used for the error title text, defaults to a bold heading 3 font from CometChatTypography. | -| errorTitleTextColor | UIColor | Color of the error title text, defaults to the primary text color from CometChatTheme. | -| errorSubTitleFont | UIFont | Font used for the error subtitle text, defaults to regular body font. | -| errorSubTitleTextColor | UIColor | Color of the error subtitle text, defaults to the secondary text color from CometChatTheme. | -| retryButtonTextColor | UIColor | Color for the retry button text, defaults to button text color from CometChatTheme. | -| retryButtonTextFont | UIFont | Font used for the retry button text, defaults to medium button font from CometChatTypography. | -| retryButtonBackgroundColor | UIColor | Background color for the retry button, defaults to the primary color from CometChatTheme. | -| retryButtonBorderColor | UIColor | Border color for the retry button, defaults to clear. | -| retryButtonBorderWidth | CGFloat | Width of the border around the retry button, defaults to 0 (no border). | -| retryButtonCornerRadius | CometChatCornerStyle | Corner radius settings for the retry button, defaults to a specific corner radius from CometChatSpacing. | -| emptyTitleTextFont | UIFont | Font used for the empty state title text, defaults to a bold heading 3 font from CometChatTypography. | -| emptyTitleTextColor | UIColor | Color of the empty state title text, defaults to the primary text color from CometChatTheme. | -| emptySubTitleFont | UIFont | Font used for the empty state subtitle text, defaults to regular body font. | -| emptySubTitleTextColor | UIColor | Color of the empty state subtitle text, defaults to the secondary text color from CometChatTheme. | -| tableViewSeparator | UIColor | Color of the table view separator, defaults to clear. | -| listItemTitleTextColor | UIColor | Color of the title text in list items, defaults to the primary text color from CometChatTheme. | -| listItemTitleFont | UIFont | Font used for the title text in list items, defaults to medium heading 4 font from CometChatTypography. | -| listItemSubTitleTextColor | UIColor | Color of the subtitle text in list items, defaults to the secondary text color from CometChatTheme. | -| listItemSubTitleFont | UIFont | Font used for the subtitle text in list items, defaults to regular body font. | -| listItemBackground | UIColor | Background color for list items, defaults to clear. | -| listItemSelectedBackground | UIColor | Background color for list items if selected, defaults to clear. | -| listItemBorderWidth | CGFloat | Width of the border around list items, defaults to 0 (no border). | -| listItemBorderColor | UIColor | Color of the border around list items, defaults to the light border color from CometChatTheme. | -| listItemCornerRadius | CometChatCornerStyle | Corner radius settings for list items, defaults to no corner radius. | -| listItemSelectionImageTint | UIColor | Tint color for the selection image in list items, defaults to the highlight color from CometChatTheme. | +| searchIconTintColor | UIColor | Tint color for the search icon. | +| searchBarStyle | UISearchBarStyle | Style of the search bar. | +| searchTintColor | UIColor | Tint color for the search bar. | +| searchBarTintColor | UIColor | Background color of the search bar. | +| searchBarPlaceholderTextColor | UIColor | Placeholder text color for the search bar. | +| searchBarPlaceholderTextFont | UIFont | Font for the placeholder text in the search bar. | +| searchBarTextColor | UIColor | Color of the text entered in the search bar. | +| searchBarTextFont | UIFont | Font for the text in the search bar. | +| searchBarBackgroundColor | UIColor | Background color of the search bar. | +| searchBarCancelIconTintColor | UIColor | Tint color for the cancel icon in the search bar. | +| searchBarCrossIconTintColor | UIColor | Tint color for the cross icon in the search bar. | +| backgroundColor | UIColor | Background color of the overall view. | +| borderWidth | CGFloat | Width of the border around the view. | +| borderColor | UIColor | Color of the border around the view. | +| cornerRadius | CometChatCornerStyle | Corner radius settings for the view. | +| titleColor | UIColor | Color for the title text. | +| titleFont | UIFont | Font for the title text. | +| largeTitleColor | UIColor | Color for the large title text. | +| largeTitleFont | UIFont | Font for the large title text. | +| navigationBarTintColor | UIColor | Background color of the navigation bar. | +| navigationBarItemsTintColor | UIColor | Tint color for items in the navigation bar. | +| errorTitleTextFont | UIFont | Font for the error title text. | +| errorTitleTextColor | UIColor | Color of the error title text. | +| errorSubTitleFont | UIFont | Font for the error subtitle text. | +| errorSubTitleTextColor | UIColor | Color of the error subtitle text. | +| retryButtonTextColor | UIColor | Color for the retry button text. | +| retryButtonTextFont | UIFont | Font for the retry button text. | +| retryButtonBackgroundColor | UIColor | Background color for the retry button. | +| retryButtonBorderColor | UIColor | Border color for the retry button. | +| retryButtonBorderWidth | CGFloat | Width of the border around the retry button. | +| retryButtonCornerRadius | CometChatCornerStyle | Corner radius settings for the retry button. | +| emptyTitleTextFont | UIFont | Font for the empty state title text. | +| emptyTitleTextColor | UIColor | Color of the empty state title text. | +| emptySubTitleFont | UIFont | Font for the empty state subtitle text. | +| emptySubTitleTextColor | UIColor | Color of the empty state subtitle text. | +| tableViewSeparator | UIColor | Color of the table view separator. | +| listItemTitleTextColor | UIColor | Color of the title text in list items. | +| listItemTitleFont | UIFont | Font for the title text in list items. | +| listItemSubTitleTextColor | UIColor | Color of the subtitle text in list items. | +| listItemSubTitleFont | UIFont | Font for the subtitle text in list items. | +| listItemBackground | UIColor | Background color for list items. | +| listItemSelectedBackground | UIColor | Background color for selected list items. | +| listItemBorderWidth | CGFloat | Width of the border around list items. | +| listItemBorderColor | UIColor | Color of the border around list items. | +| listItemCornerRadius | CometChatCornerStyle | Corner radius settings for list items. | +| listItemSelectionImageTint | UIColor | Tint color for the selection image in list items. | | listItemDeSelectedImageTint | UIColor | Tint color for the deselected image in list items. | -| passwordGroupImageTintColor | UIColor | Tint color for the password group image, defaults to the background color from CometChatTheme. | -| passwordGroupImageBackgroundColor | UIColor | Background color for the password group image, defaults to the warning color from CometChatTheme. | -| privateGroupImageTintColor | UIColor | Tint color for the private group image, defaults to the background color from CometChatTheme. | -| privateGroupImageBackgroundColor | UIColor | Background color for the private group image, defaults to the success color from CometChatTheme. | +| passwordGroupImageTintColor | UIColor | Tint color for the password group image. | +| passwordGroupImageBackgroundColor | UIColor | Background color for the password group image. | +| privateGroupImageTintColor | UIColor | Tint color for the private group image. | +| privateGroupImageBackgroundColor | UIColor | Background color for the private group image. | | privateGroupIcon | UIImage | Image for a private group icon. | | protectedGroupIcon | UIImage | Image for a protected group icon. | | set(groupsRequestBuilder:) | GroupsRequest.GroupsRequestBuilder | Sets the request builder for fetching groups. | @@ -241,27 +251,30 @@ title: "Property Changes" | hideDeleteConversationOption | Bool | Hides the option to delete a conversation. | | hideUserStatus | Bool | Hides the online/offline status of users. | | hideGroupType | Bool | Hides the group type (private/public). | -| set(options:) | (Group?) -> [CometChatGroupOption] | Allows you to define custom options for each group. Returns an array of CometChatGroupOption based on the group object. | -| add(options:) | (Group?) -> [CometChatGroupOption] | Dynamically adds options to groups. Returns additional CometChatGroupOption elements. | -| set(leadingView:) | (Group?) -> UIView | Allows you to modify the leading view of a group cell. | -| set(titleView:) | (Group?) -> UIView | Allows you to customize the title view of a group cell. | -| set(trailView:) | (Group?) -> UIView | Allows you to modify the trailing view of a group cell. | +| set(options:) | (Group?) -> [CometChatGroupOption] | Defines custom options for each group. | +| add(options:) | (Group?) -> [CometChatGroupOption] | Dynamically adds options to groups. | +| set(leadingView:) | (Group?) -> UIView | Modifies the leading view of a group cell. | +| set(titleView:) | (Group?) -> UIView | Customizes the title view of a group cell. | +| set(trailView:) | (Group?) -> UIView | Modifies the trailing view of a group cell. | ### Renamed Properties | Name | Type | Description | Old Name | | --------------------- | --------------------- | ------------------------------------------------------------------- | --------------------- | -| set(onItemClick:) | Closure | Triggered when you click on a ListItem of the groups component. | SetOnItemClick | -| set(OnItemLongClick:) | Closure | Triggered when you long press on a ListItem of the groups component. | SetOnItemLongClick | -| set(onError:) | Closure | Triggered when an error occurs in CometChatGroups. | SetOnError | -| set(onBack:) | Closure | Triggered when the back button is pressed in CometChatGroups. | SetOnBack | +| set(onItemClick:) | Closure | Triggered when you click on a ListItem. | SetOnItemClick | +| set(OnItemLongClick:) | Closure | Triggered when you long press on a ListItem. | SetOnItemLongClick | +| set(onError:) | Closure | Triggered when an error occurs. | SetOnError | +| set(onBack:) | Closure | Triggered when the back button is pressed. | SetOnBack | | SetListItemView | (Group?) -> UIView | Assigns a custom ListItem to the Groups Component. | setListItemView | -| SetSubTitleView | (Group?) -> UIView | Allows you to customize the subtitle view for each group item. | setSubtitleView | +| SetSubTitleView | (Group?) -> UIView | Customizes the subtitle view for each group item. | setSubtitleView | ### Removed Properties No properties were removed in v5. All v4 properties have been retained (with some renamed) and additional functionality has been added. + +--- + ## Group Members ### New Properties @@ -342,7 +355,6 @@ No properties were removed in v5. All v4 properties have been retained (with som | backgroundColor | UIColor | Sets the background color for the component. | background | | hideUserStatus | Bool | Hides/disables the online/offline status of users. | disable(userPresence:) | | hideSearch | Bool | Hides the search bar. | hide(search:) | -| hideUserStatus | Bool | Hide user presence. If set to true, the status indicator is not displayed. | disableUsersPresence | | set(onItemClick:) | (GroupMember, IndexPath) -> Void | Triggered when you click on a ListItem. | setOnItemClick | | set(onItemLongClick:) | (GroupMember, IndexPath) -> Void | Triggered when you long press on a ListItem. | setOnItemLongClick | | set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | setOnError | @@ -352,20 +364,20 @@ No properties were removed in v5. All v4 properties have been retained (with som | Name | Type | Description | | ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| backIconTint | UIColor | Sets the back button tint color. | -| searchIconTint | UIColor | Sets the search icon tint color. | -| searchTextFont | UIFont | Sets the search text font. | -| searchTextColor | UIColor | Sets the search text color. | -| searchCancelButtonTint | UIColor | Sets the search cancel icon tint. | -| searchPlaceholderFont | UIFont | Sets the search placeholder font. | -| searchPlaceholderColor | UIColor | Sets the search placeholder color. | -| addButtonTint | UIColor | Sets add button color. | -| addButtonFont | UIFont | Sets add button font. | -| avatarStyle | AvatarStyle | Styles to apply to the avatar component of the default list item view. | -| statusIndicatorStyle | CSSProperties | Styles to apply to the status indicator component of the default list item view. | -| listItemStyle | ListItemStyle | Styles to apply to the default list item view. | -| groupScopeStyle | ChangeScopeStyle | Styles to apply to the change scope component. | -| groupMembersStyle | GroupMembersStyle | Styles to apply to this component. | +| backIconTint | UIColor | Back button tint color. | +| searchIconTint | UIColor | Search icon tint color. | +| searchTextFont | UIFont | Search text font. | +| searchTextColor | UIColor | Search text color. | +| searchCancelButtonTint | UIColor | Search cancel icon tint. | +| searchPlaceholderFont | UIFont | Search placeholder font. | +| searchPlaceholderColor | UIColor | Search placeholder color. | +| addButtonTint | UIColor | Add button color. | +| addButtonFont | UIFont | Add button font. | +| avatarStyle | AvatarStyle | Styles for the avatar component. | +| statusIndicatorStyle | CSSProperties | Styles for the status indicator component. | +| listItemStyle | ListItemStyle | Styles for the default list item view. | +| groupScopeStyle | ChangeScopeStyle | Styles for the change scope component. | +| groupMembersStyle | GroupMembersStyle | Styles for this component. | | set(title:mode:) | String, UINavigationItem.LargeTitleDisplayMode | Custom title for the component. | | set(backButtonTitle:) | String? | Custom text for the back button. | | set(searchPlaceholder:) | String | Custom placeholder text for search field. | @@ -374,9 +386,9 @@ No properties were removed in v5. All v4 properties have been retained (with som | set(backButtonIcon:) | UIImage | Custom back button icon. | | set(passwordPlaceholderText:) | String | Custom placeholder text for password. | | hide(continueButton:) | Bool | Whether to hide the continue button. | -| set(searchIcon:) | UIImage | Sets the icon for the search bar. | -| set(searchClearIcon:) | UIImage | Sets the clear icon for the search bar. | -| set(searchBarHeight:) | CGFloat | Set the height for the search bar. | +| set(searchIcon:) | UIImage | Icon for the search bar. | +| set(searchClearIcon:) | UIImage | Clear icon for the search bar. | +| set(searchBarHeight:) | CGFloat | Height for the search bar. | | selectionMode(mode:) | SelectionMode | Enables selection mode (.single, .multiple). | | hide(separator:) | Bool | Hide/unhide the separator. | | clearList() | - | Clears the users locally. | @@ -384,9 +396,9 @@ No properties were removed in v5. All v4 properties have been retained (with som | remove(groupMember:) | GroupMember | Removes member object locally. | | size() | - | Returns the count of members displayed. | | title | String | Title of the component. | -| searchPlaceholder | String | Text to be displayed when the search input has no value. | +| searchPlaceholder | String | Text displayed when search input has no value. | | fetchTimeOut | any | Timeout reference for fetching users. | -| userPresencePlacement | UserPresencePlacement | Placement of user presence information within the user interface. | +| userPresencePlacement | UserPresencePlacement | Placement of user presence information. | | backButtonIconURL | String | Image URL for the back button. | | showBackButton | Bool | Show back button. | | closeButtonIconURL | String | Image URL for the close button. | @@ -396,39 +408,41 @@ No properties were removed in v5. All v4 properties have been retained (with som | loadingIconURL | String | Image URL for the default loading view. | | hideSeparator | Bool | Hide the separator at the bottom of the default list item view. | | titleAlignment | TitleAlignment | Alignment of the title text. | -| searchIconURL | String | Image URL for the search icon to use in the search bar. | +| searchIconURL | String | Image URL for the search icon. | | fetchingUsers | Bool | Flag to indicate whether users are currently being fetched. | | onClose | () -> Void | Function to call when the close button is clicked. | -| headerView | UIView | Custom header view which will replace the title as well. | +| headerView | UIView | Custom header view which will replace the title. | +--- + ## Message Header ### New Properties | Name | Type | Description | | ---------------------------------------- | --------- | -------------------------------------------------------------------- | -| titleTextColor | UIColor | Used to set the text color of the header title. | -| titleTextFont | UIFont | Used to set the font style of the header title. | -| subtitleTextColor | UIColor | Used to set the text color of the subtitle in the header. | -| subtitleTextFont | UIFont | Used to set the font style of the subtitle in the header. | -| backButtonImageTintColor | UIColor | Used to set the tint color of the back button image in the header. | -| privateGroupBadgeImageTintColor | UIColor | Used to set the tint color of the private group badge in the header. | -| passwordProtectedGroupBadgeImageTintColor | UIColor | Used to set the tint color of the password-protected group badge in the header. | -| privateGroupImageBackgroundColor | UIColor | Used to set the background color of the private group badge. | -| passwordGroupImageBackgroundColor | UIColor | Used to set the background color of the password-protected group badge. | -| groupImageBackgroundColor | UIColor | Used to set the background color for group icons in the header. | -| avatarStyle | AvatarStyle | Used to customize the appearance of the avatar in the header. | -| backgroundColor | UIColor | Used to set the background color of the header. | -| cornerRadius | CometChatCornerStyle | Used to set the corner radius of the header. | -| borderWidth | CGFloat | Used to set the border width of the header. | -| borderColor | UIColor | Used to set the border color of the header. | -| backButtonIcon | UIImage | Used to set a custom icon for the back button. | -| privateGroupIcon | UIImage | Used to set a custom icon for private groups. | -| protectedGroupIcon | UIImage | Used to set a custom icon for password-protected groups. | -| backgroundImage | UIImage | Used to set a background image for the header. | +| titleTextColor | UIColor | Text color of the header title. | +| titleTextFont | UIFont | Font style of the header title. | +| subtitleTextColor | UIColor | Text color of the subtitle in the header. | +| subtitleTextFont | UIFont | Font style of the subtitle in the header. | +| backButtonImageTintColor | UIColor | Tint color of the back button image in the header. | +| privateGroupBadgeImageTintColor | UIColor | Tint color of the private group badge in the header. | +| passwordProtectedGroupBadgeImageTintColor | UIColor | Tint color of the password-protected group badge in the header. | +| privateGroupImageBackgroundColor | UIColor | Background color of the private group badge. | +| passwordGroupImageBackgroundColor | UIColor | Background color of the password-protected group badge. | +| groupImageBackgroundColor | UIColor | Background color for group icons in the header. | +| avatarStyle | AvatarStyle | Customizes the appearance of the avatar in the header. | +| backgroundColor | UIColor | Background color of the header. | +| cornerRadius | CometChatCornerStyle | Corner radius of the header. | +| borderWidth | CGFloat | Border width of the header. | +| borderColor | UIColor | Border color of the header. | +| backButtonIcon | UIImage | Custom icon for the back button. | +| privateGroupIcon | UIImage | Custom icon for private groups. | +| protectedGroupIcon | UIImage | Custom icon for password-protected groups. | +| backgroundImage | UIImage | Background image for the header. | | hideBackButton | Bool | Hides the back button of message header. | -| hideUserStatus | Bool | Hides or shows the user status of user (online/offline/last active at). | +| hideUserStatus | Bool | Hides or shows the user status (online/offline/last active at). | | hideVideoCallButton | Bool | Hides the video call button. | | hideVoiceCallButton | Bool | Hides the voice call button. | | set(onBack:) | () -> Void | Triggered when back button is pressed. | @@ -444,10 +458,10 @@ No properties were removed in v5. All v4 properties have been retained (with som | Name | Type | Description | Old Name | | -------------------- | -------------- | ----------------------------------------------- | ----------- | -| backgroundColor | UIColor | Sets the background color for the component. | background | -| backButtonImageTintColor | UIColor | Sets the tint color of the back button image in the header. | backIconTint | +| backgroundColor | UIColor | Background color for the component. | background | +| backButtonImageTintColor | UIColor | Tint color of the back button image in the header. | backIconTint | | hideBackButton | Bool | Hides the back button of message header. | hide(backButton:) | -| hideUserStatus | Bool | Hides or shows the user status of user. | set(disableUsersPresence:) | +| hideUserStatus | Bool | Hides or shows the user status. | set(disableUsersPresence:) | | set(menus:) | (User?, Group?) -> UIView | Sets custom menus to add more options. | setMenus | | set(subtitleView:) | (User?, Group?) -> UIView | Sets a custom subtitle view for message header. | setSubtitleView | @@ -455,15 +469,18 @@ No properties were removed in v5. All v4 properties have been retained (with som | Name | Type | Description | | ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| typingIndicatorTextFont | UIFont | Sets the typing indicator text font. | -| typingIndicatorTextColor | UIColor | Sets the typing indicator text color. | -| detailIconTint | UIColor | Sets the tint color for detail icon for message header. | -| onlineStatusColor | UIColor | Sets the online status color for message header. | -| privateGroupIconBackgroundColor | UIColor | Sets the private group background color for message header (replaced by privateGroupImageBackgroundColor). | -| protectedGroupIconBackgroundColor | UIColor | Sets the protected group background color for message header (replaced by passwordGroupImageBackgroundColor). | -| set(protectedGroupIcon:) | UIImage | Used to set custom protected group icon. | -| set(privateGroupIcon:) | UIImage | Used to set custom private group icon. | -| disable(typing:) | Bool | Used to enable/disable typing indicators. | +| typingIndicatorTextFont | UIFont | Typing indicator text font. | +| typingIndicatorTextColor | UIColor | Typing indicator text color. | +| detailIconTint | UIColor | Tint color for detail icon. | +| onlineStatusColor | UIColor | Online status color. | +| privateGroupIconBackgroundColor | UIColor | Private group background color (replaced by privateGroupImageBackgroundColor). | +| protectedGroupIconBackgroundColor | UIColor | Protected group background color (replaced by passwordGroupImageBackgroundColor). | +| set(protectedGroupIcon:) | UIImage | Custom protected group icon. | +| set(privateGroupIcon:) | UIImage | Custom private group icon. | +| disable(typing:) | Bool | Enable/disable typing indicators. | + + +--- ## Message List @@ -519,8 +536,8 @@ No properties were removed in v5. All v4 properties have been retained (with som | set(messagesRequestBuilder:) | MessagesRequest.MessageRequestBuilder | Sets the message request builder. | | set(reactionsRequestBuilder:) | ReactionsRequest.ReactionsRequestBuilder | Sets the reactions request builder. | | set(parentMessageId:) | Int | Sets the parent message ID. | -| set(onThreadRepliesClick:) | (BaseMessage, CometChatMessageTemplate) -> Void | Triggered when you click on the thread indicator of message bubble. | -| set(onReactionClick:) | (CometChat.ReactionCount, BaseMessage) -> Void | Triggered when you click on a reaction on a message bubble. | +| set(onThreadRepliesClick:) | (BaseMessage, CometChatMessageTemplate) -> Void | Triggered when you click on the thread indicator. | +| set(onReactionClick:) | (CometChat.ReactionCount, BaseMessage) -> Void | Triggered when you click on a reaction. | | set(onReactionListItemClick:) | (CometChat.Reaction, BaseMessage) -> Void | Triggered when you click on the list item of CometChatReactionList. | | set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | | set(onEmpty:) | () -> Void | Triggers when the message list is empty. | @@ -531,9 +548,9 @@ No properties were removed in v5. All v4 properties have been retained (with som | set(datePattern:) | (Int?) -> String | Sets the date pattern using a closure. | | set(timePattern:) | (Int?) -> String | Sets the time pattern using a closure. | | set(textFormatter:) | [CometChatTextFormatter] | Sets the list of text formatters. | -| set(loadingView:) | UIView | Sets a custom loading view displayed while data is being fetched. | -| set(errorView:) | UIView | Sets a custom error view that appears when an error occurs. | -| set(emptyView:) | UIView | Sets a custom empty state view when no messages are available. | +| set(loadingView:) | UIView | Sets a custom loading view. | +| set(errorView:) | UIView | Sets a custom error view. | +| set(emptyView:) | UIView | Sets a custom empty state view. | | set(templates:) | [CometChatMessageTemplate] | Sets message templates to MessageList. | | dateTimeFormatter | CometChatDateTimeFormatter | Supports full customization of how date and time are displayed. | | set(controller:) | UIViewController | Sets the controller (mandatory for proper configuration). | @@ -544,37 +561,40 @@ No properties were removed in v5. All v4 properties have been retained (with som | -------------------- | -------------- | ----------------------------------------------- | ----------- | | hideReceipts | Bool | Hides the message read receipts. | hide(receipt:) | | hideAvatar | Bool | Shows/hides the avatar of the sender. | show(avatar:) | -| backgroundColor | UIColor | Sets the background color for the component. | background | +| backgroundColor | UIColor | Background color for the component. | background | | set(messageAlignment:) | MessageListAlignment | Sets the alignment of messages in the list. | alignment | ### Removed Properties | Name | Type | Description | | ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| loadingIconTint | UIColor | Used to set loading icon tint. | -| emptyTextFont | UIFont | Used to set empty state text font. | -| errorTextFont | UIFont | Used to set error text font. | -| emptyTextColor | UIColor | Used to set empty state text color. | -| errorTextColor | UIColor | Used to set error state text color. | -| nameTextColor | UIColor | Used to set sender/receiver name text color on a message bubble. | -| nameTextFont | UIFont | Used to set sender/receiver name text appearance on a message bubble. | -| timestampTextColor | UIColor | Used to set time stamp text color. | -| threadReplySeperatorColor | UIColor | Used to set thread reply separator color. | -| threadReplyTextColor | UIColor | Used to set thread reply text color. | -| threadReplyTextFont | UIFont | Used to set thread reply text appearance. | -| hide(error:) | Bool | Used to hide the error view. | +| loadingIconTint | UIColor | Loading icon tint. | +| emptyTextFont | UIFont | Empty state text font. | +| errorTextFont | UIFont | Error text font. | +| emptyTextColor | UIColor | Empty state text color. | +| errorTextColor | UIColor | Error state text color. | +| nameTextColor | UIColor | Sender/receiver name text color on a message bubble. | +| nameTextFont | UIFont | Sender/receiver name text appearance on a message bubble. | +| timestampTextColor | UIColor | Time stamp text color. | +| threadReplySeperatorColor | UIColor | Thread reply separator color. | +| threadReplyTextColor | UIColor | Thread reply text color. | +| threadReplyTextFont | UIFont | Thread reply text appearance. | +| hide(error:) | Bool | Hide the error view. | | messageInformationConfiguration | MessageInformationConfiguration | Configuration for message information component. | | reactionsConfiguration | ReactionsConfiguration | Configuration for reactions component. | -| setDateSeparatorPattern | (Int?) -> String | Used to modify the date pattern of the message list date separator. | -| setDatePattern | (Int?) -> String | Used to modify the date pattern. | -| setHeaderView | UIView | Used to set custom header view (now set(headerView:)). | -| setFooterView | UIView | Used to set custom footer view (now set(footerView:)). | -| setTextFormatters | [CometChatTextFormatter] | Used to set text formatters (now set(textFormatter:)). | -| setMentionsFormatters | [CometChatTextFormatter] | Used to set mentions formatters (merged into set(textFormatter:)). | -| setErrorStateView | UIView | Used to set custom error view (now set(errorView:)). | -| setEmptyStateView | UIView | Used to set custom empty state view (now set(emptyView:)). | +| setDateSeparatorPattern | (Int?) -> String | Modify the date pattern of the message list date separator. | +| setDatePattern | (Int?) -> String | Modify the date pattern. | +| setHeaderView | UIView | Set custom header view (now set(headerView:)). | +| setFooterView | UIView | Set custom footer view (now set(footerView:)). | +| setTextFormatters | [CometChatTextFormatter] | Set text formatters (now set(textFormatter:)). | +| setMentionsFormatters | [CometChatTextFormatter] | Set mentions formatters (merged into set(textFormatter:)). | +| setErrorStateView | UIView | Set custom error view (now set(errorView:)). | +| setEmptyStateView | UIView | Set custom empty state view (now set(emptyView:)). | | setOnThreadRepliesClick | Closure | Callback for thread replies click (now set(onThreadRepliesClick:)). | + +--- + ## Message Composer ### New Properties @@ -646,7 +666,7 @@ No properties were removed in v5. All v4 properties have been retained (with som | set(customSoundForMessages:) | URL? | Sets a custom sound for sending messages. | | disableSoundForMessages | Bool | Disables sound while sending messages. | | set(onSendButtonClick:) | (BaseMessage) -> Void | Override the action triggered upon pressing the send button. | -| set(onTextChanged:) | (String) -> Void | Gets activated when the user starts typing in message composer. | +| set(onTextChanged:) | (String) -> Void | Activated when the user starts typing in message composer. | | set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | | set(attachmentOptions:) | (User?, Group?, UIViewController?) -> [CometChatMessageComposerAction] | Sets a list of custom MessageComposerActions. | | set(sendButtonView:) | (User?, Group?) -> UIView | Sets a custom send button for the MessageComposer Component. | @@ -661,9 +681,9 @@ No properties were removed in v5. All v4 properties have been retained (with som | Name | Type | Description | Old Name | | -------------------- | -------------- | ----------------------------------------------- | ----------- | -| backgroundColor | UIColor | Sets the background color for the component. | background | +| backgroundColor | UIColor | Background color for the component. | background | | hideVoiceRecordingButton | Bool | Hides the voice recording button. | hide(voiceRecording:) | -| disableTypingEvents | Bool | Disables sending typing indicators when the user types. | disable(disableTypingEvents:) | +| disableTypingEvents | Bool | Disables sending typing indicators. | disable(disableTypingEvents:) | | disableSoundForMessages | Bool | Disables sound while sending messages. | disable(disableSoundForMessages:) | | set(textFormatter:) | [CometChatTextFormatter] | Assigns the list of text formatters. | setMentionsFormatters | @@ -671,371 +691,39 @@ No properties were removed in v5. All v4 properties have been retained (with som | Name | Type | Description | | ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| inputBackground | UIColor | Sets the input background color of message composer. | -| textFont | UIFont | Sets the input text font of message composer. | -| inputBoxPlaceholderFont | UIFont | Sets the placeholder text font for message composer input field. | -| placeHolderTextColor | UIColor | Sets the placeholder text color for message composer input field (renamed with different casing). | -| attachmentIconTint | UIColor | Sets the attachment icon tint color. | -| sendIconTint | UIColor | Sets send button icon tint color. | -| separatorTint | UIColor | Sets the separator color for message composer. | -| inputBorderWidth | CGFloat | Sets the border width for message composer input view. | -| inputBorderColor | UIColor | Sets the border color for message composer input view. | -| actionSheetTitleColor | UIColor | Sets the title color for action sheet of message composer. | -| actionSheetTitleFont | UIFont | Sets the title font for action sheet of message composer. | -| actionSheetLayoutModelIconTint | UIColor | Sets action sheet layout mode icon tint color for message composer. | -| actionSheetCancelButtonIconTint | UIColor | Sets action sheet cancel button icon tint color for message composer. | -| actionSheetCancelButtonIconFont | UIFont | Sets the action sheet cancel button icon font color for message composer. | -| actionSheetSeparatorTint | UIColor | Sets the separator color for action sheet items. | -| actionSheetBackground | UIColor | Sets the background color of action sheet. | -| voiceRecordingIconTint | UIColor | Sets the voice recorder icon tint color. | -| aiIconTint | UIColor | Sets the ai icon tint color. | -| infoTextColor | UIColor | Sets the text color for info message displayed (now part of style). | -| infoIconTintColor | UIColor | Sets the tint color for info icon. | -| infoBackgroundColor | UIColor | Sets the background color for info message view (now part of style). | -| infoSeparatorColor | UIColor | Sets the separator color for info view (now part of style). | -| set(background:) | UIColor | Sets background color for message composer. | -| set(placeholderText:) | String | Sets message composer's placeholder text. | -| set(maxLines:) | Int | Sets limit for lines of text to be displayed in input field. | -| set(auxiliaryButtonAlignment:) | AuxiliaryButtonAlignment | Sets position for auxiliary buttons view. | -| set(customSoundForMessage:) | URL | Sets custom sounds for outgoing messages. | -| set(liveReactionIconURL:) | UIImage | Sets custom live reaction icon. | +| inputBackground | UIColor | Input background color of message composer. | +| textFont | UIFont | Input text font of message composer. | +| inputBoxPlaceholderFont | UIFont | Placeholder text font for message composer input field. | +| attachmentIconTint | UIColor | Attachment icon tint color. | +| sendIconTint | UIColor | Send button icon tint color. | +| separatorTint | UIColor | Separator color for message composer. | +| inputBorderWidth | CGFloat | Border width for message composer input view. | +| inputBorderColor | UIColor | Border color for message composer input view. | +| actionSheetTitleColor | UIColor | Title color for action sheet of message composer. | +| actionSheetTitleFont | UIFont | Title font for action sheet of message composer. | +| actionSheetLayoutModelIconTint | UIColor | Action sheet layout mode icon tint color. | +| actionSheetCancelButtonIconTint | UIColor | Action sheet cancel button icon tint color. | +| actionSheetCancelButtonIconFont | UIFont | Action sheet cancel button icon font color. | +| actionSheetSeparatorTint | UIColor | Separator color for action sheet items. | +| actionSheetBackground | UIColor | Background color of action sheet. | +| voiceRecordingIconTint | UIColor | Voice recorder icon tint color. | +| aiIconTint | UIColor | AI icon tint color. | +| set(background:) | UIColor | Background color for message composer. | +| set(placeholderText:) | String | Message composer's placeholder text. | +| set(maxLines:) | Int | Limit for lines of text in input field. | +| set(auxiliaryButtonAlignment:) | AuxiliaryButtonAlignment | Position for auxiliary buttons view. | +| set(customSoundForMessage:) | URL | Custom sounds for outgoing messages. | +| set(liveReactionIconURL:) | UIImage | Custom live reaction icon. | | set(disableMentions:) | Bool | Enables/Disables user mentions in message composer input field. | -| set(infoIcon:) | UIImage | Sets image for info icon (now part of style). | -| set(attachmentIcon:) | UIImage | Sets image for attachment button on message composer. | -| set(aiAuxiliaryIcon:) | UIImage | Sets image for ai auxillary button. | -| setOnSendButtonClick | Closure | Sets custom actions for send button click. | +| set(infoIcon:) | UIImage | Image for info icon (now part of style). | +| set(attachmentIcon:) | UIImage | Image for attachment button on message composer. | +| set(aiAuxiliaryIcon:) | UIImage | Image for AI auxiliary button. | +| setOnSendButtonClick | Closure | Custom actions for send button click. | | hide(liveReaction:) | Bool | Toggles visibility for live reaction component. | | hide(footerView:) | Bool | Toggles visibility for footer view of message composer. | | hide(headerView:) | Bool | Toggles visibility for header view of message composer. | | hide(sendButton:) | Bool | Toggles visibility for send button. | -| setAttachmentOptions | Closure | Sets a list of custom MessageComposerActions. | -| setAuxilaryButtonView | Closure | Sets custom auxiliary button view. | -| setSecondaryButtonView | Closure | Sets custom secondary button view. | -| setSendButtonView | Closure | Sets custom send button view. | - -## Call Logs - -### New Properties - -| Name | Type | Description | -| ---------------------------------------- | --------- | -------------------------------------------------------------------- | -| listItemTitleTextColor | UIColor | Text color for the list item title. | -| listItemTitleFont | UIFont | Font for the list item title. | -| listItemSubTitleTextColor | UIColor | Text color for the list item subtitle. | -| listItemSubTitleFont | UIFont | Font for the list item subtitle. | -| listItemBackground | UIColor | Background color for the list item. | -| listItemSelectedBackground | UIColor | Background color for the selected list item. | -| listItemBorderWidth | CGFloat | Border width for the list item. | -| listItemBorderColor | UIColor | Border color for the list item. | -| listItemCornerRadius | CometChatCornerStyle | Corner radius for the list item. | -| listItemSelectionImageTint | UIColor | Tint color for the selection image. | -| listItemDeSelectedImageTint | UIColor | Tint color for the deselected image. | -| listItemSelectedImage | UIImage | Image for the selected list item. | -| listItemDeSelectedImage | UIImage | Image for the deselected list item. | -| backgroundColor | UIColor | Background color. | -| borderWidth | CGFloat | Border width. | -| borderColor | UIColor | Border color. | -| cornerRadius | CometChatCornerStyle | Corner radius. | -| titleColor | UIColor | Text color for the title. | -| titleFont | UIFont | Font for the title. | -| largeTitleColor | UIColor | Text color for large titles. | -| largeTitleFont | UIFont | Font for large titles. | -| navigationBarTintColor | UIColor | Background color for the navigation bar. | -| navigationBarItemsTintColor | UIColor | Tint color for navigation bar items. | -| errorTitleTextFont | UIFont | Font for the error title. | -| errorTitleTextColor | UIColor | Text color for the error title. | -| errorSubTitleFont | UIFont | Font for the error subtitle. | -| errorSubTitleTextColor | UIColor | Text color for the error subtitle. | -| retryButtonTextColor | UIColor | Text color for the retry button. | -| retryButtonTextFont | UIFont | Font for the retry button text. | -| retryButtonBackgroundColor | UIColor | Background color for the retry button. | -| retryButtonBorderColor | UIColor | Border color for the retry button. | -| retryButtonBorderWidth | CGFloat | Border width for the retry button. | -| retryButtonCornerRadius | CometChatCornerStyle | Corner radius for the retry button. | -| emptyTitleTextFont | UIFont | Font for the empty state title. | -| emptyTitleTextColor | UIColor | Text color for the empty state title. | -| emptySubTitleFont | UIFont | Font for the empty state subtitle. | -| emptySubTitleTextColor | UIColor | Text color for the empty state subtitle. | -| tableViewSeparator | UIColor | Color for the table view separator. | -| backIcon | UIImage | Icon for the back button. | -| backIconTint | UIColor | Tint color for the back icon. | -| incomingCallIcon | UIImage | Icon for incoming calls. | -| incomingCallIconTint | UIColor | Tint color for the incoming call icon. | -| outgoingCallIcon | UIImage | Icon for outgoing calls. | -| outgoingCallIconTint | UIColor | Tint color for the outgoing call icon. | -| missedCallTitleColor | UIColor | Text color for missed call titles. | -| missedCallIcon | UIImage | Icon for missed calls. | -| missedCallIconTint | UIColor | Tint color for the missed call icon. | -| audioCallIcon | UIImage | Icon for audio calls. | -| audioCallIconTint | UIColor | Tint color for the audio call icon. | -| videoCallIcon | UIImage | Icon for video calls. | -| videoCallIconTint | UIColor | Tint color for the video call icon. | -| separatorColor | UIColor | Color for separators. | -| set(callRequestBuilder:) | CallLogsRequest.CallLogsBuilder | Sets the CallLogsBuilder instance for call logs. | -| hideError | Bool | Hides the error state view. | -| hideNavigationBar | Bool | Hides the navigation bar. | -| hideLoadingState | Bool | Hides the loading state view. | -| hideBackIcon | Bool | Hides the back icon in the navigation bar. | -| set(onItemClick:) | (CallLog, IndexPath) -> Void | Triggered when you click on a ListItem. | -| set(onItemLongClick:) | (CallLog, IndexPath) -> Void | Triggered when you long press on a ListItem. | -| set(onBack:) | () -> Void | Triggered when back button is pressed. | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | -| set(onEmpty:) | () -> Void | Triggers when the call logs list is empty. | -| set(onLoad:) | ([CallLog]) -> Void | Triggers when call logs are successfully loaded. | -| set(listItemView:) | (CallLog) -> UIView | Assigns a custom ListItem to the CallLogs component. | -| set(titleView:) | (CallLog) -> UIView | Sets a custom title view for call log cells. | -| set(leadingView:) | (CallLog) -> UIView | Sets a custom leading view for call log cells. | -| set(subtitleView:) | (CallLog) -> UIView | Sets a custom subtitle view for call log cells. | -| set(trailView:) | (CallLog) -> UIView | Sets a custom trailing view for call log cells. | -| set(emptyView:) | UIView | Sets a custom empty state view. | -| set(errorView:) | UIView | Sets a custom error view. | -| set(menus:) | [UIBarButtonItem] | Sets custom menus to add more options. | -| avatarStyle | AvatarStyle | Customizes the appearance of avatars. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| -------------------- | -------------- | ----------------------------------------------- | ----------- | -| set(onItemClick:) | (CallLog, IndexPath) -> Void | Triggered when you click on a ListItem. | setOnItemClick | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | set(onError:) | - -### Removed Properties - -| Name | Type | Description | -| ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| backButtonFont | UIFont | Sets the font for the back button. | -| backButtonIcon | UIImage | Sets the icon for the back button. | -| backButtonTint | UIColor | Sets the tint for the back button. | -| backButtonTitle | String? | Sets the title for the back button. | -| backButtonTitleColor | UIColor | Sets the title color for the back button. | -| background | [CGColor]? | Sets the background. | -| corner | CometChatCornerStyle | Sets the corner style. | -| emptyStateText | String | Sets the text for empty state. | -| emptyStateTextFont | UIFont | Sets the font for empty state text. | -| errorStateText | String | Sets the text for error state. | -| errorStateTextColor | UIColor | Sets the text color for error state. | -| errorStateTextFont | UIFont | Sets the font for error state text. | -| searchBackground | UIColor | Sets the background for the search bar. | -| searchBarHeight | CGFloat | Sets the height for the search bar. | -| searchBorderColor | UIColor | Sets the border color for the search bar. | -| searchCancelButtonFont | UIFont | Sets the font for the search cancel button. | -| searchCancelButtonTint | UIColor | Sets the tint for the search cancel button. | -| searchClearIcon | UIImage | Sets the icon for the search clear button. | -| searchCornerRadius | CometChatCornerStyle | Sets the corner radius for the search bar. | -| searchIcon | UIImage? | Sets the icon for the search bar. | -| searchPlaceholder | String | Sets the placeholder for the search bar. | -| searchTextColor | UIColor | Sets the color for the search text. | -| searchTextFont | UIFont | Sets the font for the search text. | -| set(title:mode:) | String, UINavigationItem.LargeTitleDisplayMode | Sets the title for the title bar. | -| titleColor | UIColor | Sets the color for the title (now part of style). | -| titleFont | UIFont | Sets the font for the title (now part of style). | -| hide(errorText:) | Bool | Hides the error text. | -| hide(search:) | Bool | Hides the search bar. | -| hide(separator:) | Bool | Hides the separator. | -| callStatusTextFont | UIFont | Sets the call status font. | -| missedCallTitleTint | UIColor | Sets the missed call color. | -| callTimeTextFont | UIFont | Sets the call time font. | -| dateSeparatorTextFont | UIFont | Sets the date separator font. | -| emptyStateTextFont | UIFont | Sets the empty state font (now emptyTitleTextFont). | -| errorStateTextFont | UIFont | Sets the error state font (now errorTitleTextFont). | -| callStatusTextColor | UIColor | Sets the call status color. | -| callStatusIconTint | UIColor | Sets the call status icon tint. | -| callTimeTextColor | UIColor | Sets the call time color. | -| dateSeparatorTextColor | UIColor | Sets the date separator color. | -| infoIconTint | UIColor | Sets the info icon tint. | -| listItemStyle | ListItemStyle | Styles to apply to each call log item. | - -## Call Buttons - -### New Properties - -| Name | Type | Description | -| ---------------------------------------- | --------- | -------------------------------------------------------------------- | -| videoCallIconTint | UIColor | Tint color for the video call icon. | -| videoCallTextFont | UIFont | Font for the video call button text. | -| videoCallTextColor | UIColor | Color for the video call button text. | -| videoCallButtonBackground | UIColor | Background color for the video call button. | -| videoCallButtonCornerRadius | CometChatCornerStyle | Corner radius for the video call button. | -| videoCallButtonBorder | CGFloat | Border width for the video call button. | -| videoCallButtonBorderColor | UIColor | Border color for the video call button. | -| videoCallIcon | UIImage | Icon for the video call button. | -| audioCallIconTint | UIColor | Tint color for the audio call icon. | -| audioCallTextFont | UIFont | Font for the audio call button text. | -| audioCallTextColor | UIColor | Color for the audio call button text. | -| audioCallButtonBackground | UIColor | Background color for the audio call button. | -| audioCallButtonCornerRadius | CometChatCornerStyle | Corner radius for the audio call button. | -| audioCallButtonBorder | CGFloat | Border width for the audio call button. | -| audioCallButtonBorderColor | UIColor | Border color for the audio call button. | -| audioCallIcon | UIImage | Icon for the audio call button. | -| hideVideoCallButton | Bool | Hides the video call button. | -| hideVoiceCallButton | Bool | Hides the voice call button. | -| set(user:) | User | Sets the User object for CometChatCallButtons. | -| set(group:) | Group | Sets the Group object for CometChatCallButtons. | -| set(outgoingCallConfiguration:) | OutgoingCallConfiguration | Sets the configuration for outgoing calls. | -| set(customSoundForCalls:) | URL | Sets a custom sound for incoming and outgoing calls. | -| set(callSettingBuilder:) | (CallType, [CallUser]) -> CallSettings | Function to build call settings based on call type and participants. | -| set(onVoiceCallClick:) | (User?, Group?) -> Void | Override the action triggered upon pressing the voice call button. | -| set(onVideoCallClick:) | (User?, Group?) -> Void | Override the action triggered upon pressing the video call button. | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | -| set(controller:) | UIViewController | Sets the controller (mandatory for proper configuration). | -| style | CallButtonStyle | Customizes the appearance of the CallButtons component. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| -------------------- | -------------- | ----------------------------------------------- | ----------- | -| hideVideoCallButton | Bool | Hides the video call button. | hide(videoCall:) | -| hideVoiceCallButton | Bool | Hides the voice call button. | hide(voiceCall:) | -| set(onVoiceCallClick:) | (User?, Group?) -> Void | Override the action triggered upon pressing the voice call button. | setOnVoiceCallClick | -| set(onVideoCallClick:) | (User?, Group?) -> Void | Override the action triggered upon pressing the video call button. | setOnVideoCallClick | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | setOnError | - -### Removed Properties - -| Name | Type | Description | -| ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| set(background:) | UIColor | Sets the background color. | -| set(textFont:) | UIFont | Sets the font of the text. | -| set(textColor:) | UIColor | Sets the color of the text. | -| set(cornerRadius:) | CometChatCornerStyle | Sets the corner radius. | -| set(borderColor:) | UIColor | Sets the color of the border. | -| set(borderWidth:) | CGFloat | Sets the width of the border. | -| set(iconBackground:) | UIColor | Sets the background of the icon. | -| set(iconBorder:) | CGFloat | Sets the border of the icon. | -| set(iconCornerRadius:) | CGFloat | Sets the corner radius of the icon. | -| set(iconTint:) | UIColor | Sets the tint of the icon. | -| set(callButtonsStyle:) | ButtonStyle | Sets the button style for call buttons. | -| set(isCenterAligned:) | Bool | Sets the alignment of the buttons. | -| set(videoCallIcon:) | UIImage | Sets the icon for the video call button (now part of style). | -| set(videoCallIconText:) | String | Sets the text for the video call button. | -| set(voiceCallIcon:) | UIImage | Sets the icon for the voice call button (now part of style). | -| set(voiceCallIconText:) | String | Sets the text for the voice call button. | - -## Incoming Call - -### New Properties - -| Name | Type | Description | -| ---------------------------------------- | --------- | -------------------------------------------------------------------- | -| overlayBackgroundColor | UIColor | Background color for the overlay. | -| acceptButtonBackgroundColor | UIColor | Background color for the accept button. | -| rejectButtonBackgroundColor | UIColor | Background color for the reject button. | -| acceptButtonTintColor | UIColor | Tint color for the accept button. | -| rejectButtonTintColor | UIColor | Tint color for the reject button. | -| acceptButtonImage | UIImage | Icon image for the accept button. | -| rejectButtonImage | UIImage | Icon image for the reject button. | -| acceptButtonCornerRadius | CometChatCornerStyle | Sets corner radius for accept button. | -| rejectButtonCornerRadius | CometChatCornerStyle | Sets corner radius for reject button. | -| acceptButtonBorderWidth | CGFloat | Sets border width for accept button. | -| rejectButtonBorderWidth | CGFloat | Sets border width for reject button. | -| acceptButtonBorderColor | UIColor | Sets border color for accept button. | -| rejectButtonBorderColor | UIColor | Sets border color for reject button. | -| backgroundColor | UIColor | Background color for the call view. | -| cornerRadius | CometChatCornerStyle | Corner radius for the view. | -| borderColor | UIColor | Border color for the view. | -| borderWidth | CGFloat | Border width for the view. | -| callLabelColor | UIColor | Text color for the call label. | -| callLabelFont | UIFont | Font for the call label. | -| nameLabelColor | UIColor | Text color for the name label. | -| nameLabelFont | UIFont | Font for the name label. | -| disableSoundForCalls | Bool | Disables sound for incoming calls. | -| set(customSoundForCalls:) | URL | Sets a custom sound for incoming calls. | -| set(call:) | Call | Sets the call object for the incoming call. | -| set(onAcceptClick:) | (Call, UIViewController?) -> Void | Override the action triggered upon pressing the accept button. | -| set(onCancelClick:) | (Call, UIViewController?) -> Void | Override the action triggered upon pressing the reject button. | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | -| set(listItemView:) | (Call) -> UIView | Assigns a custom view to the incoming call item view. | -| set(leadingView:) | (Call) -> UIView | Sets a custom leading view for incoming call. | -| set(titleView:) | (Call) -> UIView | Sets a custom title view for incoming call. | -| style | IncomingCallStyle | Customizes the appearance of the IncomingCall component. | -| avatarStyle | AvatarStyle | Customizes the appearance of avatars. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| -------------------- | -------------- | ----------------------------------------------- | ----------- | -| set(onAcceptClick:) | (Call, UIViewController?) -> Void | Override the action triggered upon pressing the accept button. | setOnAcceptClick | -| set(onCancelClick:) | (Call, UIViewController?) -> Void | Override the action triggered upon pressing the reject button. | setOnCancelClick | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | setOnError | - -### Removed Properties - -| Name | Type | Description | -| ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| set(background:) | UIColor | Sets the background color for IncomingCall. | -| set(cornerRadius:) | CometChatCornerStyle | Sets the corner radius for IncomingCall. | -| set(borderWidth:) | CGFloat | Sets the border width for IncomingCall. | -| set(borderColor:) | UIColor | Sets the border color for IncomingCall. | -| set(titleColor:) | UIColor | Sets the title color for IncomingCall. | -| set(titleFont:) | UIFont | Sets the title font for IncomingCall. | -| set(subtitleColor:) | UIColor | Sets the subtitle color for IncomingCall. | -| set(subtitleFont:) | UIFont | Sets the subtitle font for IncomingCall. | -| set(incomingCallStyle:) | IncomingCallStyle | Sets the incoming call style. | -| set(avatarStyle:) | AvatarStyle | Sets the avatar style. | -| set(user:) | User | Sets the user object for the incoming call. | -| set(acceptButtonIcon:) | UIImage | Sets the icon for the accept button (now part of style). | -| set(declineButtonIcon:) | UIImage | Sets the icon for the decline button (now part of style). | - -## Outgoing Call - -### New Properties - -| Name | Type | Description | -| ---------------------------------------- | --------- | -------------------------------------------------------------------- | -| backgroundColor | UIColor | Sets the background color for the outgoing call view. | -| borderColor | UIColor | Sets the border color for the outgoing call view. | -| borderWidth | CGFloat | Sets the border width for the outgoing call view. | -| cornerRadius | CometChatCornerStyle | Sets the corner radius for the outgoing call view. | -| nameTextColor | UIColor | Sets the text color for the name label in the outgoing call view. | -| nameTextFont | UIFont | Sets the font for the name label in the outgoing call view. | -| callTextColor | UIColor | Sets the text color for the call label in the outgoing call view. | -| callTextFont | UIFont | Sets the font for the call label in the outgoing call view. | -| declineButtonBackgroundColor | UIColor | Sets the background color for the decline button in the outgoing call view. | -| declineButtonIconTint | UIColor | Sets the tint color for the decline button icon. | -| declineButtonIcon | UIImage | Sets the icon for the decline button. | -| declineButtonCornerRadius | CometChatCornerStyle | Sets the corner radius for decline button. | -| declineButtonBorderColor | UIColor | Sets the border color for decline button. | -| declineButtonBorderWidth | CGFloat | Sets the border width for decline button. | -| nameLabel | UIFont | Sets the font for the name label. | -| callingLabel | UIFont | Sets the font for the call label. | -| disableSoundForCalls | Bool | Disables sound for outgoing calls. | -| set(customSoundForCalls:) | URL | Sets a custom sound for outgoing calls. | -| set(call:) | Call | Sets the Call object for CometChatOutgoingCall. | -| set(onCancelClick:) | (Call, UIViewController?) -> Void | Override the action triggered upon pressing the cancel button. | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | -| set(avatarView:) | (Call) -> UIView | Sets a custom avatar view for outgoing call. | -| set(cancelView:) | (Call) -> UIView | Sets a custom cancel button view for outgoing call. | -| set(titleView:) | (Call) -> UIView | Sets a custom title view for outgoing call. | -| set(subtitleView:) | (Call) -> UIView | Sets a custom subtitle view for outgoing call. | -| style | OutgoingCallStyle | Customizes the appearance of the OutgoingCall component. | -| avatarStyle | AvatarStyle | Customizes the appearance of avatars. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| -------------------- | -------------- | ----------------------------------------------- | ----------- | -| set(onCancelClick:) | (Call, UIViewController?) -> Void | Override the action triggered upon pressing the cancel button. | setOnCancelClick | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | setOnError | - -### Removed Properties - -| Name | Type | Description | -| ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| set(background:) | UIColor | Sets the background color. | -| set(cornerRadius:) | CometChatCornerStyle | Sets the corner radius. | -| set(borderWidth:) | CGFloat | Sets the border width. | -| set(borderColor:) | UIColor | Sets the border color. | -| set(titleColor:) | UIColor | Sets the title color. | -| set(titleFont:) | UIFont | Sets the title font. | -| set(subtitleColor:) | UIColor | Sets the subtitle color. | -| set(subtitleFont:) | UIFont | Sets the subtitle font. | -| set(outgoingCallStyle:) | OutgoingCallStyle | Sets the outgoing call style. | -| set(avatarStyle:) | AvatarStyle | Sets the avatar style. | -| set(buttonStyle:) | ButtonStyle | Sets the button style for outgoing call. | -| disable(soundForCalls:) | Bool | Disables the default sound for calls. | -| set(declineButtonIcon:) | UIImage | Sets the icon for the decline button (now part of style). | -| set(user:) | User | Sets the User object for CometChatOutgoingCall. | ---- - - - +| setAttachmentOptions | Closure | List of custom MessageComposerActions. | +| setAuxilaryButtonView | Closure | Custom auxiliary button view. | +| setSecondaryButtonView | Closure | Custom secondary button view. | +| setSendButtonView | Closure | Custom send button view. | \ No newline at end of file From 2b3b97b4012ee078710f51746ea31ba6f8aa4ae0 Mon Sep 17 00:00:00 2001 From: Aditya Date: Fri, 13 Feb 2026 16:05:09 +0530 Subject: [PATCH 015/106] modified search , shortcut-formatter-guide, sound-manager --- ui-kit/ios/search.mdx | 219 ++++++++++----------- ui-kit/ios/shortcut-formatter-guide.mdx | 250 ++++++++++++++---------- ui-kit/ios/sound-manager.mdx | 68 +++++-- 3 files changed, 296 insertions(+), 241 deletions(-) diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index 4b6c58285..f5aab7cbf 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -1,24 +1,26 @@ --- title: "Search" +sidebarTitle: "Search" +description: "Search across conversations and messages with customizable filters in CometChat UI Kit for iOS" --- ## Overview -The `CometChatSearch` component is a powerful and customizable search interface that allows users to search across conversations and messages in real time. It supports a wide variety of filters, scopes, and customization options. `CometChatSearch` helps users find messages, conversations, media, and more through an intuitive and filterable search experience. It can be embedded in multiple contexts — as part of the conversation list, message header, or as a full-screen search experience. +The `CometChatSearch` component is a powerful and customizable search interface that allows users to search across conversations and messages in real time. It supports a wide variety of filters, scopes, and customization options. + +`CometChatSearch` helps users find messages, conversations, media, and more through an intuitive and filterable search experience. It can be embedded in multiple contexts—as part of the conversation list, message header, or as a full-screen search experience. -*** +--- ## Usage ### Integration -`CometChatSearch`, as a composite Component, offers flexible integration options, allowing it to be launched directly via button clicks or any user-triggered action. - -The following code snippet exemplifies how you can seamlessly integrate the CometChatSearch component into your application. +`CometChatSearch` is a composite component that offers flexible integration options. It can be launched directly via button clicks or any user-triggered action. @@ -26,18 +28,18 @@ The following code snippet exemplifies how you can seamlessly integrate the Come let search = CometChatSearch() self.navigationController?.pushViewController(search, animated: true) ``` - - -*** +--- ### Actions +[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type to tailor the behavior to fit your specific needs. + #### 1. onConversationClicked -`onConversationClicked` is triggered when you click on a Conversation from the search result. The `onConversationClicked` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Triggered when you click on a Conversation from the search result. This action doesn't have a predefined behavior—you can override it using the following code snippet: @@ -46,15 +48,14 @@ search.onConversationClicked = { conversation in print("Conversation clicked:", conversation.conversationId) } ``` - -*** +--- #### 2. onMessageClicked -`onMessageClicked` is triggered when you click on a Message from the search result. The `onMessageClicked` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Triggered when you click on a Message from the search result. This action doesn't have a predefined behavior—you can override it using the following code snippet: @@ -63,16 +64,14 @@ search.onMessageClicked = { message in print("Message clicked:", message.id) } ``` - - -*** +--- #### 3. onBack -'onBack' is triggered when you click on the back button of the search component. +Triggered when you click on the back button of the search component. @@ -81,16 +80,14 @@ search.onBack = { self.navigationController?.popViewController(animated: true) } ``` - - -*** +--- #### 4. onError -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Search component. +Listens for any errors that occur in the Search component. This action doesn't change the component's behavior. @@ -99,16 +96,14 @@ search.set(onError: { error in print("Search error:", error.localizedDescription) }) ``` - - -*** +--- #### 5. onEmpty -This action doesn't change the behavior of the component but rather listens for the empty state of the Search component. +Listens for the empty state of the Search component. This action doesn't change the component's behavior. @@ -117,36 +112,35 @@ search.set(onEmpty: { print("No results found") }) ``` - - +--- + ### Filters +Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria using RequestBuilders of the Chat SDK. + #### 1. ConversationsRequestBuilder -You can set the `ConversationsRequestBuilder` in the Search Component to filter the search result. You can modify the builder as per your specific requirements with multiple options available to know more refer to [ConversationRequestBuilder](/sdk/ios/retrieve-conversations). +Set the `ConversationsRequestBuilder` in the Search Component to filter the search results. For more options, refer to [ConversationRequestBuilder](/sdk/ios/retrieve-conversations). -```swift +```swift let convBuilder = ConversationsRequest.ConversationsRequestBuilder() - .set(limit:20) + .set(limit: 20) search.set(conversationsRequestBuilder: convBuilder) - ``` - - -*** +--- #### 2. MessagesRequestBuilder -You can set the `MessagesRequestBuilder` in the Search Component to filter the search result. You can modify the builder as per your specific requirements with multiple options available to know more refer to [MessagesRequestBuilder](/sdk/ios/additional-message-filtering). +Set the `MessagesRequestBuilder` in the Search Component to filter the search results. For more options, refer to [MessagesRequestBuilder](/sdk/ios/additional-message-filtering). @@ -156,21 +150,19 @@ let msgBuilder = MessagesRequest.MessageRequestBuilder() .hide(deletedMessages: true) search.set(messagesRequestBuilder: msgBuilder) - ``` - -*** +--- ### Events -[Events](/ui-kit/ios/components-overview) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. +[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events, you can extend existing functionality. Being global events, they can be applied in multiple locations and can be added or removed as needed. The `CometChatSearch` component does not produce any events. -*** +--- ## Customization @@ -178,7 +170,7 @@ To fit your app's design requirements, you can customize the appearance of the ` ### Style -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Using Style, you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. @@ -187,21 +179,19 @@ Using Style you can customize the look and feel of the component in your app, Th ```swift - -// component level styling +// Instance-level styling let style = SearchStyle() style.backgroundColor = UIColor(hex: "#EDEAFA") style.listItemBackground = UIColor(hex: "#EDEAFA") style.listItemTitleFont = UIFont(name: "TimesNewRomanPS-Regular", size: 16) style.titleFont = UIFont(name: "TimesNewRomanPS-Bold", size: 12) style.searchBarPlaceholderTextFont = UIFont(name: "TimesNewRomanPS-Regular", size: 12) - + let searchVC = CometChatSearch() searchVC.style = style self?.navigationController?.pushViewController(searchVC, animated: true) - - -// global level styling + +// Global-level styling CometChatSearch.style.backgroundColor = UIColor(hex: "#EDEAFA") CometChatSearch.style.listItemBackground = UIColor(hex: "#EDEAFA") CometChatSearch.style.listItemTitleFont = UIFont(name: "TimesNewRomanPS-Regular", size: 16) @@ -211,54 +201,42 @@ CometChatSearch.style.searchBarPlaceholderTextFont = UIFont(name: "TimesNewRoman -*** +--- ### Functionality -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can toggle the visibility of UI elements. +These are small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can toggle the visibility of UI elements. + +| Property | Description | Example | +|---------------------------|-------------------------------------------------------|----------------------------------------------------------------------| +| user | Restrict search to a specific user chat | `search.user = user` | +| group | Restrict search to a group | `search.group = group` | +| hideUserStatus | Hide online/offline indicator | `search.hideUserStatus = true` | +| hideGroupType | Hide group type icon | `search.hideGroupType = true` | +| searchFilters | Filters like "Messages", "Media" | `search.set(searchFilters: [.unread, .groups, .photos])` | +| initialSearchFilter | Default tab/filter | `search.initialSearchFilter = .messages` | +| searchIn | Restrict search: messages / conversations / both | `search.set(searchIn: [.messages])` | +| loadingStateView | Custom loader | `search.set(loadingStateView: spinner)` | +| emptyStateView | Custom empty result view | `search.set(emptyStateView: emptyView)` | +| errorStateView | Custom error UI | `search.set(errorStateView: errorView)` | -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Example | -|---------------------------|-------------------------------------------------------|----------------------------------------------| -| **user** | Restrict search to a specific user chat | `search.user = user` | -| **group** | Restrict search to a group | `search.group = group` | -| **hideUserStatus** | Hide online/offline indicator | `search.hideUserStatus = true` | -| **hideGroupType** | Hide group type icon | `search.hideGroupType = true` | -| **searchFilters** | Filters like "Messages", "Media" | `search.set(searchFilters: [SearchFilter] = [.unread, .groups, .photos])` | -| **initialSearchFilter** | Default tab/filter | `search.initialSearchFilter = .messages` | -| **searchIn** | Restrict search: messages / conversations / both | `search.set(searchIn: [SearchScope] = [.messages]) | -| **loadingStateView** | Custom loader | `search.set(loadingStateView: spinner)` | -| **emptyStateView** | Custom empty result view | `search.set(emptyStateView: emptyView)` | -| **errorStateView** | Custom error UI | `search.set(errorStateView: errorView)` | +--- ### Advanced -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** - -#### conversationListItemView +For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. -With this function, you can assign a custom list item view to an conversation in the search result. For more information, refer to the [itemView](/ui-kit/ios/conversations) prop of the `CometChatConversations` component. +#### Conversation View Customization -#### conversationLeadingView +| Function | Description | +|-------------------------------|------------------------------------------------------------------------------------------------------------------| +| conversationListItemView | Assign a custom list item view to a conversation. See [itemView](/ui-kit/ios/conversations). | +| conversationLeadingView | Assign a custom leading view to a conversation. See [leadingView](/ui-kit/ios/conversations). | +| conversationTitleView | Assign a custom title view to a conversation. See [titleView](/ui-kit/ios/conversations). | +| conversationSubtitleView | Assign a custom subtitle view to a conversation. See [subtitleView](/ui-kit/ios/conversations#subtitleview). | +| conversationTrailingView | Assign a custom trailing view to a conversation. See [trailingView](/ui-kit/ios/conversations#trailingview). | -With this function, you can assign a custom leading view of an conversation in the search result. For more information, refer to the [leadingView](/ui-kit/ios/conversations) prop of the `CometChatConversations` component. - -#### conversationTitleView - -With this function, you can assign a custom title view to an conversation in the search result. For more information, refer to the [titleView](/ui-kit/ios/conversations) prop of the `CometChatConversations` component. - -#### conversationSubtitleView - -With this function, you can assign a custom subtitle view to an conversation in the search result. For more information, refer to the [subtitleView](/ui-kit/ios/conversations#subtitleview) prop of the `CometChatConversations` component. - -#### conversationTrailingView - -With this function, you can assign a custom trailing view to an conversation in the search result. For more information, refer to the [trailingView](/ui-kit/ios/conversations#trailingview) prop of the `CometChatConversations` component. - -#### messageListItemView +#### Message View Customization With message item view functions, you can assign custom views to different types of messages in the search result. For more information, refer to the [itemView](/ui-kit/ios/messages#itemview) prop of the `CometChatMessages` component. @@ -272,32 +250,32 @@ searchVC.set(listItemViewForMessage: { message in return SearchMessageItemView() }) ``` - -It should look like this in the app: - -- code for custom view: +Custom view implementation: + ```swift class SearchMessageItemView: UIView { + // MARK: - UI Components + private let containerView: UIView = { let view = UIView() - view.backgroundColor = UIColor(red: 0.95, green: 0.93, blue: 0.98, alpha: 1.0) // light purple + view.backgroundColor = UIColor(red: 0.95, green: 0.93, blue: 0.98, alpha: 1.0) return view }() private let senderLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 16) - label.textColor = UIColor(red: 0.37, green: 0.22, blue: 0.73, alpha: 1.0) // purple + label.textColor = UIColor(red: 0.37, green: 0.22, blue: 0.73, alpha: 1.0) return label }() @@ -312,7 +290,7 @@ class SearchMessageItemView: UIView { private let bottomLine: UIView = { let view = UIView() - view.backgroundColor = UIColor(red: 0.37, green: 0.22, blue: 0.73, alpha: 1.0) // purple border + view.backgroundColor = UIColor(red: 0.37, green: 0.22, blue: 0.73, alpha: 1.0) return view }() @@ -324,6 +302,7 @@ class SearchMessageItemView: UIView { return stack }() + // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) @@ -335,6 +314,8 @@ class SearchMessageItemView: UIView { setupUI() } + // MARK: - Setup + private func setupUI() { addSubview(containerView) containerView.translatesAutoresizingMaskIntoConstraints = false @@ -365,50 +346,51 @@ class SearchMessageItemView: UIView { ]) } - /// Configure view with sender + message (with bold keyword) + // MARK: - Configuration + + /// Configure view with sender name and message text + /// - Parameters: + /// - sender: The sender's name + /// - message: The message content + /// - boldKeyword: Optional keyword to highlight in bold func configure(sender: String, message: String, boldKeyword: String?) { - senderLabel.text = sender + ":" if let keyword = boldKeyword, message.contains(keyword) { let attributed = NSMutableAttributedString(string: message) let range = (message as NSString).range(of: keyword) - attributed.addAttribute(.font, - value: UIFont.boldSystemFont(ofSize: 16), - range: range) + attributed.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 16), range: range) messageLabel.attributedText = attributed } else { messageLabel.text = message } } } - ``` - +Available message item view functions for customization: -Bellow is the list of message item view functions available for customization: +| Function | Message Type | +|-----------------------------|----------------------| +| listItemViewForImage | Image Message | +| listItemViewForVideo | Video Message | +| listItemViewForAudio | Audio Message | +| listItemViewForDocument | Document Message | +| listItemViewForLink | Link Message | -| Function | Message Type | -| -------------------------------- | ---------------------| -| **listItemViewForImage** | Image Message | -| **listItemViewForVideo** | Video Message | -| **listItemViewForAudio** | Audio Message | -| **listItemViewForDocument** | Document Message | -| **listItemViewForLink** | Link Message | +--- #### DateTime Formatters -#### 1. setDateTimeFormatter - By providing a custom implementation of the DateTimeFormatterCallback, you can configure how time and date values are displayed. This ensures consistent formatting for labels such as "Today", "Yesterday", "X minutes ago", and more. ```swift -let searchVC = CometChatSearch() +let searchVC = CometChatSearch() + searchVC.dateTimeFormatter.today = { timestamp in return "Today • \(formattedTime(timestamp))" } @@ -418,24 +400,21 @@ searchVC.dateTimeFormatter.otherDay = { timestamp in df.dateFormat = "dd MMM yyyy" return df.string(from: Date(timeIntervalSince1970: timestamp)) } - ``` - - -*** +--- #### Text Formatters -#### setTextFormatters +The `setTextFormatters` method enables developers to define and apply text formatters that dynamically modify or transform message content before rendering it in the UI. Text formatters can be used for: -This method enables developers to define and apply text formatters that dynamically modify or transform message content before rendering it in the UI. Text formatters can be used for purposes such as: +- Automatically converting URLs into clickable links +- Applying Markdown or rich text styling +- Replacing certain words or patterns with emojis or predefined text +- Censoring specific words for moderation -* Automatically converting URLs into clickable links -* Applying Markdown or rich text styling -* Replacing certain words or patterns with emojis or predefined text -* Censoring specific words for moderation +By utilizing this method, developers can enhance readability, usability, and compliance with content guidelines. See the [MentionsFormatter Guide](/ui-kit/ios/mentions-formatter-guide) for more details. -By utilizing this method, developers can enhance readability, usability, and compliance with content guidelines. [MentionsFormatter Guide](/ui-kit/ios/mentions-formatter-guide) \ No newline at end of file +--- diff --git a/ui-kit/ios/shortcut-formatter-guide.mdx b/ui-kit/ios/shortcut-formatter-guide.mdx index e10d35e5c..9c6fb844e 100644 --- a/ui-kit/ios/shortcut-formatter-guide.mdx +++ b/ui-kit/ios/shortcut-formatter-guide.mdx @@ -1,250 +1,284 @@ --- title: "ShortCut Formatter" +sidebarTitle: "ShortCut Formatter" +description: "Implement message shortcuts using the ShortCutFormatter class in CometChat UI Kit for iOS" --- ## Introduction -The ShortCutFormatter class extends the CometChatTextFormatter class to provide a mechanism for handling shortcuts within messages. This guide will walk you through the process of using ShortCutFormatter to implement shortcut extensions in your CometChat application. +The `ShortCutFormatter` class extends the `CometChatTextFormatter` class to provide a mechanism for handling shortcuts within messages. This guide walks you through the process of using `ShortCutFormatter` to implement shortcut extensions in your CometChat application. + +--- ## Setup -1. **Create the ShortCutFormatter Class**: Define the `ShortCutFormatter` class by extending the `CometChatTextFormatter` class. +### 1. Create the ShortCutFormatter Class + +Define the `ShortCutFormatter` class by extending the `CometChatTextFormatter` class: ```swift class ShortcutFormatter: CometChatTextFormatter { - - private var messageShortcuts: [String: String] = [String: String]( ) + + // Store fetched shortcuts from the extension + private var messageShortcuts: [String: String] = [:] + + // Store suggestion items for display private var shortcuts: [CometChatUIKitSwift.SuggestionItem] = [] - } ``` - - -2. **initializer**: Sets the `trackingCharacter` to **'!'** in the initializer of the `ShortcutFormatter` class +### 2. Initialize with Tracking Character + +Set the `trackingCharacter` to `'!'` in the initializer: ```swift - override init(trackingCharacter: Character) { - super.init(trackingCharacter: "!") - } +override init(trackingCharacter: Character) { + super.init(trackingCharacter: "!") +} ``` - - -3. **Prepare Regex**: Set the regular expression for shortcut detection in the `getRegex()` method of `ShortcutFormatter` class. +### 3. Define the Regex Pattern + +Set the regular expression for shortcut detection in the `getRegex()` method: ```swift override func getRegex() -> String { - return "(^|\\s)!\\w+" + return "(^|\\s)!\\w+" } ``` - - -4. **Prepare TrackingCharacter**: Define the `getTrackingCharacter()` method to return **'!'** as the shortcut tracking character in `ShortcutFormatter` class. +### 4. Return the Tracking Character + +Define the `getTrackingCharacter()` method to return `'!'` as the shortcut tracking character: ```swift override func getTrackingCharacter() -> Character { - return "!" + return "!" } ``` - - -5. **Override Search Method**: Override the `search()` method to search for shortcuts based on the entered query. +### 5. Implement the Search Method + +Override the `search()` method to search for shortcuts based on the entered query: ```swift override func search(string: String, suggestedItems: (([CometChatUIKitSwift.SuggestionItem]) -> ())? = nil) { - - if messageShortcuts.isEmpty == true { - CometChat.callExtension(slug: "message-shortcuts", type: .get, endPoint: "v1/fetch", body: nil) { [weak self] extensionResponseData in - guard let this = self else { return } - if let shotCutData = extensionResponseData?["shortcuts"] as? [String: String] { - this.messageShortcuts = shotCutData - var suggestedItemsList = [CometChatUIKitSwift.SuggestionItem]() - this.messageShortcuts.forEach({ (key, value) in - if key.hasPrefix(string) { - suggestedItemsList.append(CometChatUIKitSwift.SuggestionItem(id: key, name: value, visibleText: value)) - } - }) - suggestedItems?(suggestedItemsList) - } - } onError: { error in - print("Error occured while fetcing shot cuts: \(error?.errorDescription)") + + // Fetch shortcuts from extension if not already cached + if messageShortcuts.isEmpty { + CometChat.callExtension( + slug: "message-shortcuts", + type: .get, + endPoint: "v1/fetch", + body: nil + ) { [weak self] extensionResponseData in + guard let self = self else { return } + + if let shortcutData = extensionResponseData?["shortcuts"] as? [String: String] { + self.messageShortcuts = shortcutData + + // Filter shortcuts matching the search string + let suggestedItemsList = self.messageShortcuts + .filter { $0.key.hasPrefix(string) } + .map { CometChatUIKitSwift.SuggestionItem(id: $0.key, name: $0.value, visibleText: $0.value) } + + suggestedItems?(suggestedItemsList) } - - } else { - var suggestedItemsList = [CometChatUIKitSwift.SuggestionItem]() - messageShortcuts.forEach({ (key, value) in - if key.hasPrefix(string) { - suggestedItemsList.append(CometChatUIKitSwift.SuggestionItem(id: key, name: value, visibleText: value)) - } - }) - suggestedItems?(suggestedItemsList) + } onError: { error in + print("Error occurred while fetching shortcuts: \(error?.errorDescription ?? "Unknown error")") + } + } else { + // Use cached shortcuts + let suggestedItemsList = messageShortcuts + .filter { $0.key.hasPrefix(string) } + .map { CometChatUIKitSwift.SuggestionItem(id: $0.key, name: $0.value, visibleText: $0.value) } + + suggestedItems?(suggestedItemsList) } - } ``` - - -6. **Handle prepareMessageString**: Implement the `prepareMessageString()` method to convert the base chat message into an attributed string for display in the `ShortcutFormatter` class. +### 6. Handle Message String Preparation + +Implement the `prepareMessageString()` method to convert the base chat message into an attributed string for display: ```swift -override func prepareMessageString(baseMessage: BaseMessage, regexString: String, alignment: MessageBubbleAlignment = .left, formattingType: FormattingType) -> NSAttributedString { -let message = (baseMessage as? TextMessage)?.text ?? "" -return NSAttributedString(string: message) +override func prepareMessageString( + baseMessage: BaseMessage, + regexString: String, + alignment: MessageBubbleAlignment = .left, + formattingType: FormattingType +) -> NSAttributedString { + let message = (baseMessage as? TextMessage)?.text ?? "" + return NSAttributedString(string: message) } ``` - - -7. **Handle onTextTapped**: Override the `onTextTapped()` method if needed. +### 7. Handle Text Tap Events + +Override the `onTextTapped()` method if you need to handle tap events on formatted text: ```swift override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) { - // Your code here + // Handle tap event on shortcut text } ``` - - -* Below is an example of how a `ShortcutFormatter` Swift file might look: +--- + +## Complete Implementation + +Here's the complete `ShortcutFormatter` class: -```swift ShortcutFormatter.swift + + +```swift import Foundation import CometChatSDK import CometChatUIKitSwift class ShortcutFormatter: CometChatTextFormatter { - - private var messageShortcuts: [String: String] = [String: String]() + + // MARK: - Properties + + private var messageShortcuts: [String: String] = [:] private var shortcuts: [CometChatUIKitSwift.SuggestionItem] = [] - + + // MARK: - Initialization + override init(trackingCharacter: Character) { super.init(trackingCharacter: "!") } - + + // MARK: - Override Methods + override func getRegex() -> String { return "(^|\\s)!\\w+" } - + override func getTrackingCharacter() -> Character { return "!" } - + override func search(string: String, suggestedItems: (([CometChatUIKitSwift.SuggestionItem]) -> ())? = nil) { - - if messageShortcuts.isEmpty == true { - CometChat.callExtension(slug: "message-shortcuts", type: .get, endPoint: "v1/fetch", body: nil) { [weak self] extensionResponseData in - guard let this = self else { return } - if let shotCutData = extensionResponseData?["shortcuts"] as? [String: String] { - this.messageShortcuts = shotCutData - var suggestedItemsList = [CometChatUIKitSwift.SuggestionItem]() - this.messageShortcuts.forEach({ (key, value) in - if key.hasPrefix(string) { - suggestedItemsList.append(CometChatUIKitSwift.SuggestionItem(id: key, name: value, visibleText: value)) - } - }) + + if messageShortcuts.isEmpty { + CometChat.callExtension( + slug: "message-shortcuts", + type: .get, + endPoint: "v1/fetch", + body: nil + ) { [weak self] extensionResponseData in + guard let self = self else { return } + + if let shortcutData = extensionResponseData?["shortcuts"] as? [String: String] { + self.messageShortcuts = shortcutData + + let suggestedItemsList = self.messageShortcuts + .filter { $0.key.hasPrefix(string) } + .map { CometChatUIKitSwift.SuggestionItem(id: $0.key, name: $0.value, visibleText: $0.value) } + suggestedItems?(suggestedItemsList) } - } onError: { error in - print("Error occured while fetcing shot cuts: \(error?.errorDescription)") + print("Error occurred while fetching shortcuts: \(error?.errorDescription ?? "Unknown error")") } - } else { - - var suggestedItemsList = [CometChatUIKitSwift.SuggestionItem]() - messageShortcuts.forEach({ (key, value) in - if key.hasPrefix(string) { - suggestedItemsList.append(CometChatUIKitSwift.SuggestionItem(id: key, name: value, visibleText: value)) - } - }) + let suggestedItemsList = messageShortcuts + .filter { $0.key.hasPrefix(string) } + .map { CometChatUIKitSwift.SuggestionItem(id: $0.key, name: $0.value, visibleText: $0.value) } + suggestedItems?(suggestedItemsList) - } - } - - override func prepareMessageString(baseMessage: BaseMessage, regexString: String, alignment: MessageBubbleAlignment = .left, formattingType: FormattingType) -> NSAttributedString { + + override func prepareMessageString( + baseMessage: BaseMessage, + regexString: String, + alignment: MessageBubbleAlignment = .left, + formattingType: FormattingType + ) -> NSAttributedString { let message = (baseMessage as? TextMessage)?.text ?? "" return NSAttributedString(string: message) } - + override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) { - // Your code here + // Handle tap event on shortcut text } } ``` + + + +--- ## Usage -1. **Initialization**: Initialize an instance of `ShortCutFormatter` in your application. +### 1. Initialize the Formatter + +Create an instance of `ShortCutFormatter`: ```swift let shortcutFormatter = ShortcutFormatter(trackingCharacter: "!") ``` - - -2. **Integration**: Integrating the `ShortCutFormatter` into your CometChat application involves incorporating it within your project to handle message shortcuts. If you're utilizing the [CometChatMessageComposer](/ui-kit/ios/message-composer) component, you can seamlessly integrate the ShortCutFormatter to manage shortcut functionalities within your application. +### 2. Integrate with Message Composer -* Your final integration code should look like this: +If you're using the [CometChatMessageComposer](/ui-kit/ios/message-composer) component, integrate the `ShortCutFormatter` to manage shortcut functionalities: ```swift let shortcutFormatter = ShortcutFormatter(trackingCharacter: "!") - + let cometChatMessageComposer = CometChatMessageComposer() cometChatMessageComposer.set(textFormatter: [shortcutFormatter]) ``` - - - + +Ensure to pass and present `cometChatConversationsWithMessages`. If a navigation controller is already in use, utilize the `pushViewController` function instead of directly presenting the view controller. + -Ensure to pass and present `cometChatConversationsWithMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - - +--- ## Example + +--- diff --git a/ui-kit/ios/sound-manager.mdx b/ui-kit/ios/sound-manager.mdx index a9fdcd3cc..46c02347b 100644 --- a/ui-kit/ios/sound-manager.mdx +++ b/ui-kit/ios/sound-manager.mdx @@ -1,42 +1,84 @@ --- title: "Sound Manager" +sidebarTitle: "Sound Manager" +description: "Manage and play audio for messages and calls in CometChat UI Kit for iOS" --- ## Overview -The SoundManager is a helper class responsible for managing and playing various types of audio in the CometChat UI Kit. This includes sound events for incoming and outgoing messages and calls. +The `CometChatSoundManager` is a helper class responsible for managing and playing audio in the CometChat UI Kit. It handles sound events for incoming and outgoing messages and calls, providing both default sounds and support for custom audio files. + +--- ## Methods ### Play Sound -The SoundManager plays pre-defined or custom sounds based on user interactions with the chat interface. If no custom sound file is provided, the default sound is played. +The `play(sound:customSound:)` method triggers audio playback based on user interactions with the chat interface. If no custom sound file is provided, the default sound for that event type is played. -Here are the available methods for triggering sound playback: +```swift +play(sound: Sound, customSound: URL?) +``` -* `play(sound: Sound, customSound: URL?)`: This method plays different types of sounds for incoming and outgoing calls and messages.Moreover, it can play a customized sound for a specific URL when triggered. +| Parameter | Type | Description | +| ----------- | ------- | ------------------------------------------------------------ | +| sound | Sound | The type of sound event (e.g., `.incomingMessage`, `.outgoingMessage`, `.incomingCall`, `.outgoingCall`) | +| customSound | URL? | Optional URL to a custom sound file. If `nil`, the default sound is used. | ### Pause Sound -The SoundManager can pause different types of sounds for incoming and outgoing calls and messages using the following method: +The `pause()` method stops any sound currently being played by the SoundManager. + +```swift +pause() +``` -* `pause()`: This method pauses any sound currently being played. +--- ## Usage -Here is how to use CometChatSoundManager: +### Playing Default Sounds + +Play the default sound for an incoming message: -```php -// Play sound: +```swift +// Play the default incoming message sound CometChatSoundManager().play(sound: .incomingMessage) +``` + +### Playing Custom Sounds + +Provide a custom audio file URL to override the default sound: -// Play sound with custom sound: +```swift +// Play a custom sound for incoming messages if let customSoundURL = Bundle.main.url(forResource: "customSound", withExtension: "wav") { - CometChatSoundManager().play(sound: .incomingMessage, customSound: customSoundURL) + CometChatSoundManager().play(sound: .incomingMessage, customSound: customSoundURL) } +``` + +### Pausing Sounds + +Stop any currently playing sound: -// Pause Sound: +```swift +// Pause the currently playing sound CometChatSoundManager().pause() ``` -By using the CometChatSoundManager, you can enhance the user experience in your chat application by integrating audible cues for chat interactions. +--- + +## Sound Types + +The `Sound` enum provides the following options: + +| Sound Type | Description | +| ---------------- | ---------------------------------------- | +| `.incomingMessage` | Played when a new message is received | +| `.outgoingMessage` | Played when a message is sent | +| `.incomingCall` | Played when an incoming call is received | +| `.outgoingCall` | Played when initiating an outgoing call | + +--- + +By using `CometChatSoundManager`, you can enhance the user experience in your chat application by integrating audible cues for chat interactions. From 28e87e9d9d8ee921e4265c181262d00a99cf331e Mon Sep 17 00:00:00 2001 From: Aditya Date: Fri, 13 Feb 2026 17:27:58 +0530 Subject: [PATCH 016/106] modified sound-manager, theme-introduction,threaded-messages-header --- ui-kit/ios/search.mdx | 14 +-- ui-kit/ios/sound-manager.mdx | 34 ++++-- ui-kit/ios/theme-introduction.mdx | 34 +++--- ui-kit/ios/threaded-messages-header.mdx | 144 ++++++++++++------------ 4 files changed, 124 insertions(+), 102 deletions(-) diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index f5aab7cbf..a23b4a856 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -228,13 +228,13 @@ For advanced-level customization, you can set custom views to the component. Thi #### Conversation View Customization -| Function | Description | -|-------------------------------|------------------------------------------------------------------------------------------------------------------| -| conversationListItemView | Assign a custom list item view to a conversation. See [itemView](/ui-kit/ios/conversations). | -| conversationLeadingView | Assign a custom leading view to a conversation. See [leadingView](/ui-kit/ios/conversations). | -| conversationTitleView | Assign a custom title view to a conversation. See [titleView](/ui-kit/ios/conversations). | -| conversationSubtitleView | Assign a custom subtitle view to a conversation. See [subtitleView](/ui-kit/ios/conversations#subtitleview). | -| conversationTrailingView | Assign a custom trailing view to a conversation. See [trailingView](/ui-kit/ios/conversations#trailingview). | +| Function | Description | +|-------------------------------|-------------------------------------------------------------| +| conversationListItemView | Assign a custom list item view to a conversation. | +| conversationLeadingView | Assign a custom leading view to a conversation. | +| conversationTitleView | Assign a custom title view to a conversation. | +| conversationSubtitleView | Assign a custom subtitle view to a conversation. | +| conversationTrailingView | Assign a custom trailing view to a conversation. | #### Message View Customization diff --git a/ui-kit/ios/sound-manager.mdx b/ui-kit/ios/sound-manager.mdx index 46c02347b..ea6bc926a 100644 --- a/ui-kit/ios/sound-manager.mdx +++ b/ui-kit/ios/sound-manager.mdx @@ -6,7 +6,7 @@ description: "Manage and play audio for messages and calls in CometChat UI Kit f ## Overview -The `CometChatSoundManager` is a helper class responsible for managing and playing audio in the CometChat UI Kit. It handles sound events for incoming and outgoing messages and calls, providing both default sounds and support for custom audio files. +`CometChatSoundManager` is a helper class that manages audio playback in the CometChat UI Kit. It handles sound events for incoming and outgoing messages and calls, supporting both default sounds and custom audio files. --- @@ -20,10 +20,10 @@ The `play(sound:customSound:)` method triggers audio playback based on user inte play(sound: Sound, customSound: URL?) ``` -| Parameter | Type | Description | -| ----------- | ------- | ------------------------------------------------------------ | -| sound | Sound | The type of sound event (e.g., `.incomingMessage`, `.outgoingMessage`, `.incomingCall`, `.outgoingCall`) | -| customSound | URL? | Optional URL to a custom sound file. If `nil`, the default sound is used. | +| Parameter | Type | Description | +| ----------- | ------ | ------------------------------------------------------------------------------------------------ | +| sound | Sound | The type of sound event (e.g., `.incomingMessage`, `.outgoingMessage`, `.incomingCall`, `.outgoingCall`) | +| customSound | URL? | Optional URL to a custom sound file. If `nil`, the default sound is used. | ### Pause Sound @@ -41,30 +41,42 @@ pause() Play the default sound for an incoming message: + + ```swift // Play the default incoming message sound CometChatSoundManager().play(sound: .incomingMessage) ``` + + ### Playing Custom Sounds Provide a custom audio file URL to override the default sound: + + ```swift // Play a custom sound for incoming messages if let customSoundURL = Bundle.main.url(forResource: "customSound", withExtension: "wav") { CometChatSoundManager().play(sound: .incomingMessage, customSound: customSoundURL) } ``` + + ### Pausing Sounds Stop any currently playing sound: + + ```swift // Pause the currently playing sound CometChatSoundManager().pause() ``` + + --- @@ -72,12 +84,12 @@ CometChatSoundManager().pause() The `Sound` enum provides the following options: -| Sound Type | Description | -| ---------------- | ---------------------------------------- | -| `.incomingMessage` | Played when a new message is received | -| `.outgoingMessage` | Played when a message is sent | -| `.incomingCall` | Played when an incoming call is received | -| `.outgoingCall` | Played when initiating an outgoing call | +| Sound Type | Description | +| ------------------ | ----------------------------------------- | +| `.incomingMessage` | Played when a new message is received | +| `.outgoingMessage` | Played when a message is sent | +| `.incomingCall` | Played when an incoming call is received | +| `.outgoingCall` | Played when initiating an outgoing call | --- diff --git a/ui-kit/ios/theme-introduction.mdx b/ui-kit/ios/theme-introduction.mdx index 7a8559d15..acdfe7aea 100644 --- a/ui-kit/ios/theme-introduction.mdx +++ b/ui-kit/ios/theme-introduction.mdx @@ -1,20 +1,22 @@ --- title: "Introduction" +sidebarTitle: "Introduction" +description: "Create visually consistent and customizable user interfaces with CometChat theming for iOS" --- ## Overview -Theming in CometChat for iOS allows you to create visually consistent and customizable user interfaces that align with your application's branding. The CometChatTheme system enables global theming, customization of colors, typography, spacing, and component-specific styles to enhance the user experience across all CometChat components. +Theming in CometChat for iOS allows you to create visually consistent and customizable user interfaces that align with your application's branding. The `CometChatTheme` system enables global theming, customization of colors, typography, spacing, and component-specific styles to enhance the user experience across all CometChat components. With global styles and an easy-to-override architecture, you can seamlessly apply themes at both a global and component level. -## Using Theming in Your Project +--- -Global Theming +## Using Theming in Your Project -Set up the global theme for your application during the app launch. This ensures all CometChat components use the specified theme. +### Global Theming -Example in AppDelegate.swift +Set up the global theme for your application during app launch. This ensures all CometChat components use the specified theme. @@ -26,7 +28,10 @@ import CometChatSDK class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { // Apply the global theme CometChatTheme.primaryColor = UIColor.systemBackground @@ -38,33 +43,32 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } } ``` - - -## Customization +--- -Customizing Colors +## Customization -Override specific color attributes globally in CometChatTheme. This is equivalent to overriding attributes in Android's themes.xml. +### Customizing Colors -Example: Setting Primary Color +Override specific color attributes globally in `CometChatTheme`. This is equivalent to overriding attributes in Android's `themes.xml`. ```swift -CometChatTheme.primaryColor = UIColor(hex: "#F76808") // Custom primary color +// Set a custom primary color +CometChatTheme.primaryColor = UIColor(hex: "#F76808") ``` - - + +--- diff --git a/ui-kit/ios/threaded-messages-header.mdx b/ui-kit/ios/threaded-messages-header.mdx index ac5a95af2..c04904382 100644 --- a/ui-kit/ios/threaded-messages-header.mdx +++ b/ui-kit/ios/threaded-messages-header.mdx @@ -1,10 +1,12 @@ --- title: "Threaded Messages Header" +sidebarTitle: "Threaded Messages Header" +description: "Display and customize the header for threaded message conversations in CometChat UI Kit for iOS" --- ## Overview -ThreadedMessages is a [Composite Component](/ui-kit/ios/components-overview#composite-components) that displays all replies made to a particular message in a conversation. By default, the parent message will be displayed at the top, the message composer will be at the bottom and between them a message list will contain all replies. +ThreadedMessages is a [Composite Component](/ui-kit/ios/components-overview#composite-components) that displays all replies made to a particular message in a conversation. By default, the parent message appears at the top, the message composer is at the bottom, and a message list containing all replies is displayed between them. @@ -12,16 +14,18 @@ ThreadedMessages is a [Composite Component](/ui-kit/ios/components-overview#comp ThreadedMessages is composed of the following components: -| Component | Description | -| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | +| Component | Description | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | [MessageList](/ui-kit/ios/message-list) | CometChatMessageList is a component that displays a list of Messages | | [MessageComposer](/ui-kit/ios/message-composer) | CometChatMessageComposer is a component that helps in writing and editing of messages and also sending attachments | +--- + ## Usage ### Integration -As `CometChatThreadedMessageHeader` is a **view**, you can add it to your view controller by adding the following code snippet. +Since `CometChatThreadedMessageHeader` is a view, you can add it to your view controller using the following code snippet: @@ -29,84 +33,79 @@ As `CometChatThreadedMessageHeader` is a **view**, you can add it to your view c let threadedMessage = CometChatThreadedMessageHeader() view.addSubview(threadedMessage) ``` - - - Ensure to pass and present `threadedMessage`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - -*** +--- ### Filters -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria for a more customized experience. Filters can be applied using RequestBuilders of Chat SDK. ThreadedMessages does not have its own Filters. However, you can filter the messages list in ThreadedMessages Component using [MessageListConfiguration](#configuration). **Example** -In this example, we are filtering messages and searching for messages that contain the keyword "payment". +In this example, we are filtering messages and searching for messages that contain the keyword "payment": ```swift -let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() -.set(uid: "your UID") -.set(searchKeyword: "sure") +// MARK: - Filter messages by search keyword +let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() + .set(uid: "your UID") + .set(searchKeyword: "sure") let messageList = CometChatMessageList() messageList.set(user: user) messageList.set(messagesRequestBuilder: messageRequestBuilder) ``` - - -*** +--- ### Events -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events, you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. The MessageList Component does not emit any events of its own. -*** +--- ## Customization To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. -*** +--- ### Style `ThreadedMessagesStyle` contains various properties which can be used to customize the UI of `CometChatThreadedMessages`. -**Global level styling** +**Global Level Styling** ```swift +// MARK: - Apply global styling CometChatThreadedMessageHeader.style.backgroundColor = UIColor(hex: "#F76808") CometChatThreadedMessageHeader.style.dividerTintColor = UIColor(hex: "#F76808") CometChatThreadedMessageHeader.style.bubbleContainerBackgroundColor = UIColor(hex: "#F76808") ``` - - -**Instance level styling** +**Instance Level Styling** ```swift +// MARK: - Apply instance-level styling let customThreadedHeaderStyle = ThreadedMessageHeaderStyle() customThreadedHeaderStyle.backgroundColor = UIColor(hex: "#F76808") customThreadedHeaderStyle.dividerTintColor = UIColor(hex: "#F76808") @@ -115,9 +114,7 @@ customThreadedHeaderStyle.bubbleContainerBackgroundColor = UIColor(hex: "#F76808 let threadedMessage = CometChatThreadedMessageHeader() threadedMessage.style = customThreadedHeaderStyle ``` - - @@ -126,25 +123,27 @@ threadedMessage.style = customThreadedHeaderStyle List of properties available for configuring in ThreadedMessagesStyle: -| **Property** | **Description** | **Code** | +| Property | Description | Code | | ------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------ | -| **Background Color** | Background color for the header. | `CometChatThreadedMessageHeader.style.backgroundColor = CometChatTheme.backgroundColor03` | -| **Border Color** | Border color for the header. | `CometChatThreadedMessageHeader.style.borderColor = UIColor.clear` | -| **Border Width** | Border width for the header. | `CometChatThreadedMessageHeader.style.borderWith = 0` | -| **Corner Radius** | Corner radius for the header. | `CometChatThreadedMessageHeader.style.cornerRadius = CometChatCornerStyle?` | -| **Bubble Container Background Color** | Background color for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerBackgroundColor = UIColor.clear` | -| **Bubble Container Border Color** | Border color for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerBorderColor = UIColor.clear` | -| **Bubble Container Border Width** | Border width for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerBorderWidth = 0` | -| **Bubble Container Corner Radius** | Corner radius for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerCornerRadius = CometChatCornerStyle?` | -| **Divider Tint Color** | Tint color for the divider. | `CometChatThreadedMessageHeader.style.dividerTintColor = CometChatTheme.extendedPrimaryColor100` | -| **Count Text Color** | Text color for the message count text. | `CometChatThreadedMessageHeader.style.countTextColor = CometChatTheme.textColorSecondary` | -| **Count Text Font** | Font for the message count text. | `CometChatThreadedMessageHeader.style.countTextFont = CometChatTypography.Body.regular` | +| Background Color | Background color for the header. | `CometChatThreadedMessageHeader.style.backgroundColor = CometChatTheme.backgroundColor03` | +| Border Color | Border color for the header. | `CometChatThreadedMessageHeader.style.borderColor = UIColor.clear` | +| Border Width | Border width for the header. | `CometChatThreadedMessageHeader.style.borderWith = 0` | +| Corner Radius | Corner radius for the header. | `CometChatThreadedMessageHeader.style.cornerRadius = CometChatCornerStyle?` | +| Bubble Container Background Color | Background color for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerBackgroundColor = UIColor.clear` | +| Bubble Container Border Color | Border color for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerBorderColor = UIColor.clear` | +| Bubble Container Border Width | Border width for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerBorderWidth = 0` | +| Bubble Container Corner Radius | Corner radius for the bubble container. | `CometChatThreadedMessageHeader.style.bubbleContainerCornerRadius = CometChatCornerStyle?` | +| Divider Tint Color | Tint color for the divider. | `CometChatThreadedMessageHeader.style.dividerTintColor = CometChatTheme.extendedPrimaryColor100` | +| Count Text Color | Text color for the message count text. | `CometChatThreadedMessageHeader.style.countTextColor = CometChatTheme.textColorSecondary` | +| Count Text Font | Font for the message count text. | `CometChatThreadedMessageHeader.style.countTextFont = CometChatTypography.Body.regular` | + +--- ### Functionality -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can set maximum lines text area will show before scrolling in the composer, edit a message, add header view and footer view to the composer, etc. +These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can set maximum lines the text area will show before scrolling in the composer, edit a message, add header view and footer view to the composer, and more. -Below is a list of customizations along with corresponding code snippets message composer offers +Below is a list of customizations along with corresponding code snippets: | Property | Description | Code | | ------------------- | ------------------------------------------------------ | --------------------------------- | @@ -156,36 +155,37 @@ Below is a list of customizations along with corresponding code snippets message | setMessageAlignment | Sets the alignment of messages (e.g., left or right). | `setMessageAlignment(.right)` | | setParentMessage | Sets the parent message for the threaded conversation. | `setParentMessage(parentMessage)` | +--- + ### Advanced For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. #### SetDatePattern -You can modify the date pattern to your requirement using .set(datePattern:). This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. +You can modify the date pattern to your requirement using `.set(datePattern:)`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. **Example** ```swift +// MARK: - Custom date pattern let threadedMessageHeader = CometChatThreadedMessageHeader() threadedMessageHeader.set(datePattern: { timestamp in guard let timestamp = timestamp else { - return "" + return "" } - let date = Date(timeIntervalSince1970: TimeInterval(timestamp/1000)) + let date = Date(timeIntervalSince1970: TimeInterval(timestamp / 1000)) let formatter = DateFormatter() formatter.dateFormat = "dd-MM-yyyy" return formatter.string(from: date) }) ``` - - -*** +--- #### SetTextFormatters @@ -195,15 +195,20 @@ This functionality dynamically assigns a list of text formatters. If a custom li This code customizes a CometChat text formatter to identify and style the word "sure", with handling options for interactions like string search, scrolling, and item clicks. The custom formatter is then applied to CometChat messages. -```ruby Swift + + +```swift +// MARK: - Apply custom text formatter let myCustomTextFormatter = MyCustomTextFormatter(trackingCharacter: "#") -let threadedMessageHeader = CometChatThreadedMessageHeader() +let threadedMessageHeader = CometChatThreadedMessageHeader() .set(user: user) .set(textFormatter: [myCustomTextFormatter]) ``` + + -Demonstration: +**Demonstration:** @@ -213,80 +218,81 @@ import CometChatSDK import CometChatUIKitSwift class MyCustomTextFormatter: CometChatTextFormatter { -override func getRegex() -> String { -return "(\\bsure\\b)" - + + // MARK: - Regex Pattern + override func getRegex() -> String { + return "(\\bsure\\b)" } + // MARK: - Tracking Character override func getTrackingCharacter() -> Character { return "#" } + // MARK: - Search override func search(string: String, suggestedItems: ((_: [SuggestionItem]) -> ())? = nil) { // This function would call an API or perform a local search // For now, it does nothing } + // MARK: - Pagination override func onScrollToBottom(suggestionItemList: [SuggestionItem], listItem: ((_: [SuggestionItem]) -> ())?) { // This function would call the next page of an API // For now, it does nothing } + // MARK: - Item Selection override func onItemClick(suggestedItem: SuggestionItem, user: User?, group: Group?) { // Do something with the clicked item } + // MARK: - Pre-Send Processing override func handlePreMessageSend(baseMessage: BaseMessage, suggestionItemList: [SuggestionItem]) { // This function would modify the message before it's sent // For now, it does nothing } + // MARK: - Message String Formatting override func prepareMessageString( - baseMessage: BaseMessage, - regexString: String, - alignment: MessageBubbleAlignment = .left, - formattingType: FormattingType + baseMessage: BaseMessage, + regexString: String, + alignment: MessageBubbleAlignment = .left, + formattingType: FormattingType ) -> NSAttributedString { let attrString = NSMutableAttributedString(string: "SURE") - if alignment == .left { // Received message + if alignment == .left { + // Received message styling attrString.addAttribute(.foregroundColor, value: UIColor.blue, range: NSRange(location: 0, length: attrString.length)) - } else { // Sent message + } else { + // Sent message styling attrString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: 0, length: attrString.length)) } attrString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 18), range: NSRange(location: 0, length: attrString.length)) return attrString } + // MARK: - Text Tap Handler override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) { // Your Action } - } ``` - - -*** +--- #### SetTemplate and AddTemplate [CometChatMessageTemplate](/ui-kit/ios/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/ios/message-template). -*** +--- - To ensure that the `ThreadedMessages` is properly configured, passing the controller is mandatory. -* Swift - ```swift let threadedMessageView = CometChatThreadedMessages() threadedMessageView.set(controller: UIViewController) // Passing the controller is required ``` - - -*** From 27e5aee76bb255d907f4a7ecf317c8ecf7ad6aea Mon Sep 17 00:00:00 2001 From: Aditya Date: Mon, 16 Feb 2026 11:55:20 +0530 Subject: [PATCH 017/106] modified users --- ui-kit/ios/users.mdx | 421 ++++++++++++++++++------------------------- 1 file changed, 180 insertions(+), 241 deletions(-) diff --git a/ui-kit/ios/users.mdx b/ui-kit/ios/users.mdx index 17f682101..fa6b661cf 100644 --- a/ui-kit/ios/users.mdx +++ b/ui-kit/ios/users.mdx @@ -1,29 +1,31 @@ --- title: "Users" +sidebarTitle: "Users" +description: "Display and manage a list of users with search functionality in CometChat UI Kit for iOS" --- ## Overview -The Users is a [Component](/ui-kit/ios/components-overview#components), showcasing an accessible list of all available users. It provides an integral search functionality, allowing you to locate any specific user swiftly and easily. For each user listed, the widget displays the user's name by default, in conjunction with their avatar when available. Furthermore, it includes a status indicator, visually informing you whether a user is currently online or offline. +The Users component is a [Component](/ui-kit/ios/components-overview#components) that displays an accessible list of all available users. It provides built-in search functionality, allowing you to locate any specific user quickly. For each user listed, the component displays the user's name by default, along with their avatar when available. It also includes a status indicator that visually shows whether a user is currently online or offline. -The Users component is composed of the following BaseComponents: +The Users component is composed of the following base components: -| Components | Description | -| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -| [ListBase](/ui-kit/ios/list-base) | a reusable container component having title, search box, customisable background and a List View | -| [ListItem](/ui-kit/ios/list-item) | a component that renders data obtained from a User object on a Tile having a title, subtitle, leading and trailing view | +| Components | Description | +| ---------- | ----------------------------------------------------------------------------------------------------------------------- | +| ListBase | A reusable container component with a title, search box, customizable background, and a list view. | +| ListItem | A component that renders data from a User object on a tile with a title, subtitle, leading view, and trailing view. | -*** +--- ## Usage ### Integration -As `CometChatUsers` is a custom **view controller**, it can be launched directly by user actions such as button clicks or other interactions. It's also possible to integrate it into a **tab view controller**. `CometChatUsers` offers several parameters and methods for UI customization. +Since `CometChatUsers` is a custom view controller, you can launch it directly through user actions such as button clicks or other interactions. You can also integrate it into a tab view controller. `CometChatUsers` offers several parameters and methods for UI customization. @@ -32,18 +34,18 @@ let cometChatUsers = CometChatUsers() let naviVC = UINavigationController(rootViewController: cometChatUsers) self.present(naviVC, animated: true) ``` - - +--- + ### Actions -[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type to tailor the behavior of the component to fit your specific needs. -1. ##### set(onItemClick:) +#### 1. set(onItemClick:) -`set(OnItemClick:)` is triggered when you click on a ListItem of the users component. This `set(OnItemClick:)` method proves beneficial when a user intends to customize the on-click behavior in CometChatUsers. +The `set(onItemClick:)` method is triggered when you click on a ListItem in the Users component. This method is useful when you want to customize the click behavior. @@ -52,34 +54,30 @@ cometChatUsers.set(onItemClick: { user, indexPath in // Override on item click }) ``` - - -*** +--- -2. ##### set(OnItemLongClick:) +#### 2. set(onItemLongClick:) -`set(OnItemLongClick:)` is triggered when you long press on a ListItem of the users component. This `set(OnItemLongClick:)` method proves beneficial when a user intends to additional functionality on long press on list item in CometChatUsers. +The `set(onItemLongClick:)` method is triggered when you long press on a ListItem in the Users component. This method is useful when you want to add additional functionality on long press. ```swift cometChatUsers.set(onItemLongClick: { user, indexPath in - // Override on item click + // Override on item long click }) ``` - - -*** +--- -##### 3. set(onBack:) +#### 3. set(onBack:) -This `set(onBack:)` method becomes valuable when a user needs to override the action triggered upon pressing the back button in CometChatUsers. +The `set(onBack:)` method is useful when you need to override the action triggered upon pressing the back button. @@ -88,35 +86,30 @@ cometChatUsers.set(onBack: { // Override on back }) ``` - - -*** +--- -##### 4. set(onSelection:) +#### 4. set(onSelection:) -The `set(onSelection:)` only gets trigger when selection mode is set to multiple of single. And this gets trigger on every selection, and returns the list of selected users. +The `set(onSelection:)` method is triggered only when the selection mode is set to multiple or single. It fires on every selection and returns the list of selected users. ```swift - cometChatUsers.set(onSelection: { users in - //Handle action + // Handle action }) ``` - - -*** +--- -##### 5. set(onError:) +#### 5. set(onError:) -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatUsers. +The `set(onError:)` method is useful when you need to customize the action taken upon encountering an error. @@ -125,16 +118,14 @@ cometChatUsers.set(onError: { error in // Override on error }) ``` - - -*** +--- -##### 6. set(onEmpty:) +#### 6. set(onEmpty:) -This `set(onEmpty:)` method is triggered when the users list is empty in CometChatUsers. +The `set(onEmpty:)` method is triggered when the users list is empty. @@ -143,16 +134,14 @@ cometChatUsers.set(onEmpty: { // Handle empty state }) ``` - - -*** +--- -##### 7. setOnLoad +#### 7. set(onLoad:) -This set(onLoad:) gets triggered when a user list is fully fetched and going to displayed on the screen, this return the list of users to get displayed on the screen. +The `set(onLoad:)` method is triggered when the user list is fully fetched and about to be displayed on the screen. It returns the list of users to be displayed. @@ -161,36 +150,34 @@ cometChatUsers.set(onLoad: { users in // Handle loaded users }) ``` - - -*** +--- ### Filters -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +Filters allow you to customize the data displayed in a list within a component. You can filter the list based on your specific criteria for a more customized view. Filters can be applied using RequestBuilders from the Chat SDK. -##### 1. UserRequestBuilder +#### 1. UserRequestBuilder -The [UserRequestBuilder](/sdk/ios/retrieve-users) enables you to filter and customize the user list based on available parameters in UserRequestBuilder. This feature allows you to create more specific and targeted queries when fetching users. The following are the parameters available in [UserRequestBuilder](/sdk/ios/retrieve-users) +The [UserRequestBuilder](/sdk/ios/retrieve-users) enables you to filter and customize the user list based on available parameters. This feature allows you to create more specific and targeted queries when fetching users. | Methods | Type | Description | | -------------------- | -------------------- | -------------------------------------------------------------------------------------- | -| **setLimit** | int | sets the number users that can be fetched in a single request, suitable for pagination | -| **setSearchKeyword** | String | used for fetching users matching the passed string | -| **hideBlockedUsers** | bool | used for fetching all those users who are not blocked by the logged in user | -| **friendsOnly** | bool | used for fetching only those users in which logged in user is a member | -| **setRoles** | \[String] | used for fetching users containing the passed tags | -| **setTags** | \[String] | used for fetching users containing the passed tags | -| **withTags** | bool | used to fetch tags data along with the list of users. | -| **setStatus** | CometChat.UserStatus | used for fetching users by their status online or offline | -| **setUIDs** | \[String] | used for fetching users containing the passed users | +| **setLimit** | int | Sets the number of users that can be fetched in a single request, suitable for pagination. | +| **setSearchKeyword** | String | Fetches users matching the passed string. | +| **hideBlockedUsers** | bool | Fetches all users who are not blocked by the logged-in user. | +| **friendsOnly** | bool | Fetches only users who are friends with the logged-in user. | +| **setRoles** | \[String] | Fetches users with the specified roles. | +| **setTags** | \[String] | Fetches users containing the specified tags. | +| **withTags** | bool | Fetches tag data along with the list of users. | +| **setStatus** | CometChat.UserStatus | Fetches users by their status (online or offline). | +| **setUIDs** | \[String] | Fetches users with the specified UIDs. | **Example** -In the example below, we are applying a filter to the UserList based on Friends. +In the example below, we apply a filter to the UserList to show only friends: @@ -201,152 +188,147 @@ let usersWithMessages = CometChatUsersWithMessages(usersRequestBuilder: usersReq let naviVC = UINavigationController(rootViewController: usersWithMessages) self.present(naviVC, animated: true) ``` - - - - -##### 2. SearchRequestBuilder +#### 2. SearchRequestBuilder -The SearchRequestBuilder uses [UserRequestBuilder](/sdk/ios/retrieve-users) enables you to filter and customize the search list based on available parameters in UserRequestBuilder. This feature allows you to keep uniformity between the displayed UserList and searched UserList. +The SearchRequestBuilder uses [UserRequestBuilder](/sdk/ios/retrieve-users) to filter and customize the search list based on available parameters. This feature allows you to maintain uniformity between the displayed UserList and the searched UserList. -**Example** In the example below, we are applying a filter to the UserList based on Search. +**Example** + +In the example below, we apply a filter to the UserList based on a search keyword: ```swift let usersRequestBuilder = UsersRequest.UsersRequestBuilder(limit: 20) -.set(searchKeyword: "**") + .set(searchKeyword: "**") let usersWithMessages = CometChatUsers(usersRequestBuilder: usersRequestBuilder) let naviVC = UINavigationController(rootViewController: usersWithMessages) self.present(naviVC, animated: true) ``` - - - - +--- + ### Events -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +[Events](/ui-kit/ios/components-overview#events) are emitted by a component. By using events, you can extend existing functionality. Being global events, they can be applied in multiple locations and can be added or removed as needed. -To handle events supported by Users you have to add corresponding listeners by using `CometChatUserEvents` +To handle events supported by Users, add the corresponding listeners using `CometChatUserEvents`: | Events | Description | | ----------------- | --------------------------------------------------------------------- | -| emitOnUserBlock | This will get triggered when the logged in user blocks another user | -| emitOnUserUnblock | This will get triggered when the logged in user unblocks another user | +| emitOnUserBlock | Triggered when the logged-in user blocks another user. | +| emitOnUserUnblock | Triggered when the logged-in user unblocks another user. | ```swift -///pass the [User] object of the user which has been blocked by the logged in user - CometChatUserEvents.emitOnUserBlock(user: User) +// Pass the User object of the user who has been blocked by the logged-in user +CometChatUserEvents.emitOnUserBlock(user: User) -///pass the [User] object of the user which has been unblocked by the logged in user - CometChatUserEvents.emitOnUserUnblock(user: User) +// Pass the User object of the user who has been unblocked by the logged-in user +CometChatUserEvents.emitOnUserUnblock(user: User) ``` - - - - **Usage** -```swift Swift -// View controller from your project where you want to listen events. +```swift +// View controller from your project where you want to listen to events public class ViewController: UIViewController { - public override func viewDidLoad() { + public override func viewDidLoad() { super.viewDidLoad() - - // Subscribing for the listener to listen events from user module - CometChatUserEvents.addListener("UNIQUE_ID", self as CometChatUserEventListener) + // Subscribe to the listener for user module events + CometChatUserEvents.addListener("UNIQUE_ID", self as CometChatUserEventListener) } public override func viewWillDisappear(_ animated: Bool) { - // Uncubscribing for the listener to listen events from user module + // Unsubscribe from the listener CometChatUserEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") } } - // Listener events from user module -extension ViewController: CometChatUserEventListener { +// Listener events from user module +extension ViewController: CometChatUserEventListener { func onUserBlock(user: User) { - // Do Stuff + // Handle user block event } func onUserUnblock(user: User) { - // Do Stuff + // Handle user unblock event } } ``` +--- + ## Customization -To fit your app's design requirements, you can customize the appearance of the users component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +To fit your app's design requirements, you can customize the appearance of the Users component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. ### Style -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Using Style, you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. -##### 1. Users Style +#### 1. Users Style -You can set the `UsersStyle` to the Users Component to customize the styling. +You can set the `UsersStyle` to the Users component to customize the styling. -**Global level styling** +**Global Level Styling** ```swift +// Create custom avatar style let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) - + +// Apply global styling CometChatUsers.style.titleColor = UIColor(hex: "#F76808") CometChatUsers.style.titleFont = UIFont(name: "Times-New-Roman", size: 34) CometChatUsers.avatarStyle = customAvatarStyle ``` - - -**Instance level styling** +**Instance Level Styling** ```swift +// Create custom avatar style let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) - + +// Create custom user style let userStyle = UsersStyle() userStyle.titleColor = UIColor(hex: "#F76808") userStyle.titleFont = UIFont(name: "Times-New-Roman", size: 34) - + +// Apply instance-level styling let customUser = CometChatUsers() customUser.style = userStyle customUser.avatarStyle = customAvatarStyle ``` - - -List of properties exposed by MessageListStyle + +List of properties exposed by UsersStyle: | **Property** | **Description** | **Code** | | ----------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | @@ -360,7 +342,7 @@ List of properties exposed by MessageListStyle | **Placeholder Text Font** | Font of the placeholder text in the search bar. | `CometChatUsers.style.searchBarPlaceholderTextFont = UIFont?` | | **Search Bar Text Color** | Color of the entered text in the search bar. | `CometChatUsers.style.searchBarTextColor = UIColor?` | | **Search Bar Text Font** | Font of the entered text in the search bar. | `CometChatUsers.style.searchBarTextFont = UIFont?` | -| **Search Bar Background Color** | Background color of the search bar’s text input area. | `CometChatUsers.style.searchBarBackgroundColor = UIColor?` | +| **Search Bar Background Color** | Background color of the search bar's text input area. | `CometChatUsers.style.searchBarBackgroundColor = UIColor?` | | **Cancel Icon Tint Color** | Tint color for the cancel button in the search bar. | `CometChatUsers.style.searchBarCancelIconTintColor = UIColor?` | | **Cross Icon Tint Color** | Tint color for the clear (cross) button in the search bar. | `CometChatUsers.style.searchBarCrossIconTintColor = UIColor?` | | **Background Color** | Background color for the entire screen or view. | `.backgroundColor = CometChatTheme.backgroundColor01` | @@ -383,7 +365,7 @@ List of properties exposed by MessageListStyle | **Retry Button Border Color** | Border color for the retry button. | `CometChatUsers.style.retryButtonBorderColor = .clear` | | **Retry Button Border Width** | Border width for the retry button. | `CometChatUsers.style.retryButtonBorderWidth = 0` | | **Retry Button Corner Radius** | Corner radius for the retry button. | `CometChatUsers.style.retryButtonCornerRadius = CometChatCornerStyle?` | -| **Empty State Title Font** | Font for the empty state title (when no users/items are present). | `CometChatUsers.style.emptyTitleTextFont = CometChatTypography.Heading3.bold` | +| **Empty State Title Font** | Font for the empty state title (when no users are present). | `CometChatUsers.style.emptyTitleTextFont = CometChatTypography.Heading3.bold` | | **Empty State Title Color** | Text color for the empty state title. | `CometChatUsers.style.emptyTitleTextColor = CometChatTheme.textColorPrimary` | | **Empty Subtitle Font** | Font for the subtitle in the empty state. | `CometChatUsers.style.emptySubTitleFont = CometChatTypography.Body.regular` | | **Empty Subtitle Text Color** | Text color for the subtitle in the empty state. | `CometChatUsers.style.emptySubTitleTextColor = CometChatTheme.textColorSecondary` | @@ -402,14 +384,12 @@ List of properties exposed by MessageListStyle | **Header Title Color** | Text color for section header titles in the list. | `CometChatUsers.style.headerTitleColor = CometChatTheme.textColorHighlight` | | **Header Title Font** | Font for section header titles. | `CometChatUsers.style.headerTitleFont = CometChatTypography.Heading4.medium` | -*** +--- ### Functionality These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. -Below is a list of customizations along with corresponding code snippets - | Method | Description | Code | | -------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------- | | set(userRequestBuilder:) | Sets a custom request builder for fetching users. | `.set(userRequestBuilder: UsersRequest.UsersRequestBuilder())` | @@ -423,96 +403,87 @@ Below is a list of customizations along with corresponding code snippets | hideUserStatus | Hides the online/offline status of users. | `hideUserStatus = true` | | hideSectionHeader | Hides the section header for table view indicating initials of users. | `hideSectionHeader = true` | -*** +--- -### Advance +### Advanced -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. -*** +--- -#### SetOptions +#### set(options:) -You can define custom options for each user using .set(options:). This method allows you to return an array of CometChatUserOption based on the user object. +You can define custom options for each user using `set(options:)`. This method allows you to return an array of `CometChatUserOption` based on the user object. ```swift -cometChatUsers.set(options: { user in - return [CometChatUserOptions] -}) +cometChatUsers.set(options: { user in + return [CometChatUserOption]() +}) ``` - - -*** +--- -#### AddOptions +#### add(options:) -You can dynamically add options to users using .add(options:). This method lets you return additional CometChatUserOption elements. +You can dynamically add options to users using `add(options:)`. This method lets you return additional `CometChatUserOption` elements. ```swift -cometChatUsers.add(options: { user in - return [ArchiveOption()] -}) +cometChatUsers.add(options: { user in + return [ArchiveOption()] +}) ``` - - -*** +--- -#### SetListItemView +#### set(listItemView:) -With this function, you can assign a custom ListItem to the users Component. +With this method, you can assign a custom ListItem view to the Users component. ```swift let cometChatUser = CometChatUsers() cometChatUser.set(listItemView: { user in - //Perform Your Actions + // Return your custom view }) ``` - - -You can indeed create a custom listitem UIView file named `Custom_User_ListItem_View` for more complex or unique list items. - -Afterwards, seamlessly integrate this `Custom_User_ListItem_View` UIView file into the `.setListItemView` method within **CometChatUsers()**. - -You can create a `CustomListItemView` as a custom `UIView`. Which we will inflate in `setListItemView()` - -```swift swift +You can create a custom `UIView` file named `CustomListItemView` for more complex or unique list items. Then integrate this custom view into the `set(listItemView:)` method within `CometChatUsers()`. +```swift import UIKit import CometChatUIKitSwift class CustomListItem: UIView { - // Initialize UI components + + // MARK: - UI Components private var profileImageView: CometChatAvatar = { let imageView = CometChatAvatar(image: UIImage()) - imageView.translatesAutoresizingMaskIntoConstraints = false // Important for manual layout + imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private var nameLabel: UILabel = { let label = UILabel() - label.translatesAutoresizingMaskIntoConstraints = false // Important for manual layout + label.translatesAutoresizingMaskIntoConstraints = false return label }() + // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) setupUI() @@ -522,6 +493,7 @@ class CustomListItem: UIView { fatalError("init(coder:) has not been implemented") } + // MARK: - Setup private func setupUI() { addSubview(profileImageView) addSubview(nameLabel) @@ -533,12 +505,14 @@ class CustomListItem: UIView { profileImageView.widthAnchor.constraint(equalToConstant: 40), profileImageView.heightAnchor.constraint(equalToConstant: 40), + // Name label constraints nameLabel.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 8), nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), nameLabel.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } + // MARK: - Configuration func set(user: User) { var avatarURL: String? if let group = conversation.conversationWith as? Group { @@ -551,40 +525,33 @@ class CustomListItem: UIView { avatarURL = user.avatar } - - - - self.profileImageView.setAvatar(avatarUrl: avatarURL, with: nameLabel.text) + self.profileImageView.setAvatar(avatarUrl: avatarURL, with: nameLabel.text) } } ``` -*** +--- -#### SetLeadingView +#### set(leadingView:) -You can modify the leading view of a user cell using .set(leadingView:). +You can modify the leading view of a user cell using `set(leadingView:)`. ```swift -cometChatUsers.set(leadingView: { user in +cometChatUsers.set(leadingView: { user in let view = CustomLeadingView() - return view -}) + return view +}) ``` - - -Demonstration - -You can create a `CustomLeadingView` as a custom `UIView`. Which we will inflate in `setLeadingView()` +You can create a `CustomLeadingView` as a custom `UIView` to use in `set(leadingView:)`: @@ -593,6 +560,7 @@ import UIKit class CustomLeadingView: UIView { + // MARK: - UI Components private let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill @@ -623,6 +591,7 @@ class CustomLeadingView: UIView { return view }() + // MARK: - Initialization init(image: UIImage?) { super.init(frame: .zero) imageView.image = image @@ -651,37 +620,31 @@ class CustomLeadingView: UIView { } } ``` - - -*** +--- -#### SetTitleView +#### set(titleView:) -You can customize the title view of a user cell using .set(titleView:). +You can customize the title view of a user cell using `set(titleView:)`. ```swift -cometChatUsers.set(titleView: { user in +cometChatUsers.set(titleView: { user in let view = CustomTitleView() return view -}) +}) ``` - - -Demonstration - -You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()` +You can create a `CustomTitleView` as a custom `UIView` to use in `set(titleView:)`: @@ -690,6 +653,7 @@ import UIKit class CustomTitleView: UIView { + // MARK: - UI Components private let nameLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 18) @@ -709,6 +673,7 @@ class CustomTitleView: UIView { return label }() + // MARK: - Initialization init(name: String, role: String) { super.init(frame: .zero) nameLabel.text = name @@ -734,40 +699,32 @@ class CustomTitleView: UIView { fatalError("init(coder:) has not been implemented") } } - - ``` - - -*** +--- -#### SetTrailView +#### set(trailView:) -You can modify the trailing view of a user cell using .set(trailView:). +You can modify the trailing view of a user cell using `set(trailView:)`. ```swift -cometChatUsers.set(trailView: { user in - let view = CustomTrailView() - return view -}) +cometChatUsers.set(trailView: { user in + let view = CustomTrailView() + return view +}) ``` - - -Demonstration - -You can create a `CustomTrailView` as a custom `UIView`. Which we will inflate in `setTrailView()` +You can create a `CustomTrailView` as a custom `UIView` to use in `set(trailView:)`: @@ -776,6 +733,7 @@ import UIKit class CustomTrailView: UIView { + // MARK: - UI Components private let badgeView: UIView = { let view = UIView() view.backgroundColor = .purple @@ -800,6 +758,7 @@ class CustomTrailView: UIView { return label }() + // MARK: - Initialization init() { super.init(frame: .zero) @@ -828,43 +787,33 @@ class CustomTrailView: UIView { fatalError("init(coder:) has not been implemented") } } - - ``` - - -*** +--- -#### SetSubTitleView +#### set(subtitleView:) -You can customize the subtitle view for each users item to meet your requirements +You can customize the subtitle view for each user item to meet your requirements. ```swift let cometChatUser = CometChatUsers() cometChatUser.set(subtitleView: { user in - let view = CustomSubtitleView() - return view + let view = CustomSubtitleView() + return view }) ``` - - -**Example** - -Demonstration - -You can seamlessly integrate this `CustomSubtitleView` UIView file into the `.set(subtitleView:)` method within CometChatUsers. +You can create a `CustomSubtitleView` as a custom `UIView` to use in `set(subtitleView:)`: @@ -886,66 +835,56 @@ class CustomSubtitleView: UILabel { } } ``` - - -*** +--- -#### SetLoadingView +#### set(loadingView:) -You can set a custom loading view using .set(loadingView:). This method accepts a UIView to display while data is being fetched. +You can set a custom loading view using `set(loadingView:)`. This method accepts a `UIView` to display while data is being fetched. ```swift -let loadingIndicator = UIActivityIndicatorView(style: .medium) -loadingIndicator.startAnimating() -cometChatUsers.set(loadingView: loadingIndicator) +let loadingIndicator = UIActivityIndicatorView(style: .medium) +loadingIndicator.startAnimating() +cometChatUsers.set(loadingView: loadingIndicator) ``` - - -*** +--- -#### SetErrorView +#### set(errorView:) -You can customize the error view using .set(errorView:). This method accepts a UIView that appears when an error occurs. +You can customize the error view using `set(errorView:)`. This method accepts a `UIView` that appears when an error occurs. ```swift -let errorLabel = UILabel() -errorLabel.text = "Something went wrong!" -errorLabel.textColor = .red -cometChatUsers.set(errorView: errorLabel) +let errorLabel = UILabel() +errorLabel.text = "Something went wrong!" +errorLabel.textColor = .red +cometChatUsers.set(errorView: errorLabel) ``` - - -*** +--- -#### SetEmptyView +#### set(emptyView:) -You can customize the empty state view using .set(emptyView:). This method accepts a UIView that appears when no user are available. +You can customize the empty state view using `set(emptyView:)`. This method accepts a `UIView` that appears when no users are available. ```swift -let emptyLabel = UILabel() -emptyLabel.text = "No users found" -emptyLabel.textColor = .gray -emptyLabel.textAlignment = .center -cometChatUsers.set(emptyView: emptyLabel) +let emptyLabel = UILabel() +emptyLabel.text = "No users found" +emptyLabel.textColor = .gray +emptyLabel.textAlignment = .center +cometChatUsers.set(emptyView: emptyLabel) ``` - - - -*** From a0887a52600f8942adb1b60f1b418c35bc188db3 Mon Sep 17 00:00:00 2001 From: Aditya Date: Mon, 16 Feb 2026 12:07:24 +0530 Subject: [PATCH 018/106] reverted the getting started and its sub headers --- ui-kit/ios/getting-started.mdx | 604 ++++++++++++++++------------- ui-kit/ios/ios-conversation.mdx | 60 +-- ui-kit/ios/ios-one-to-one-chat.mdx | 63 ++- ui-kit/ios/ios-tab-based-chat.mdx | 175 ++++----- 4 files changed, 443 insertions(+), 459 deletions(-) diff --git a/ui-kit/ios/getting-started.mdx b/ui-kit/ios/getting-started.mdx index 5ea059a3e..0fabda03d 100644 --- a/ui-kit/ios/getting-started.mdx +++ b/ui-kit/ios/getting-started.mdx @@ -1,396 +1,448 @@ --- -title: "Getting Started" +title: "Getting Started With CometChat iOS UI Kit" sidebarTitle: "Integration" -description: "Add chat to your iOS app in minutes with CometChat UI Kit" --- -The CometChat iOS UI Kit provides pre-built chat components with theming support, one-on-one and group messaging, and full customization capabilities. +The **CometChat UI Kit for iOS** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI elements**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. + +With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat iOS UI Kit. -## Prerequisites +*** + +## **Prerequisites** + +Before installing the **CometChat UI Kit for iOS**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: + +* **User Management** +* **Group Chat & Messaging** +* **Voice & Video Calling** +* **Real-time Notifications** + + + +To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: + +1. **App ID** +2. **Auth Key** +3. **Region** + +Ensure you have these details ready before proceeding with the installation and configuration. + + + +*** + +## **Register & Set Up CometChat** + +Follow these steps to **register on CometChat** and **set up your development environment**. + +### **Step 1: Register on CometChat** + +To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. -Before starting, ensure you have: +🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** -- **Xcode 16+** installed on your Mac -- **iOS 13.0+** deployment target -- **Swift 5.0+** -- A [CometChat account](https://app.cometchat.com) with your App ID, Auth Key, and Region +### **Step 2: Get Your Application Keys** + +After registering, create a **new app** and retrieve your **authentication details**: + +1. Navigate to the **QuickStart** or **API & Auth Keys section**. + +2. Note down the following keys: + + * **App ID** + * **Auth Key** + * **Region** -Get your credentials from the [CometChat Dashboard](https://app.cometchat.com) under **QuickStart** or **API & Auth Keys** section. + +Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **web and mobile**. + -## Step 1: Create iOS Project +### **Step 3: Set Up Your Development Environment** + +Ensure your system meets the following **prerequisites** before proceeding with integration. + +**System Requirements:** -Open Xcode and create a new project: +* **Xcode 16 or later** installed on your machine. +* An **iOS device or simulator** with iOS version 13.0 or above. +* **Swift 5.0**. +* **macOS**. -1. File → New → Project → **iOS App** -2. Enter your **Product Name** and **Bundle Identifier** -3. Interface: **Storyboard** -4. Language: **Swift** -5. Click **Create** +*** -## Step 2: Install SDK +## **Integration Steps** + +### **Create an iOS Project** + +To get started, open Xcode and create a new project for UI Kit in the Project window as follows: + +1. Select **iOS App** in the **Choose a template for your new project** window and click Next. +2. Enter your project name in the **Name** field in the **Choose options for your new project** window. +3. Enter your identifier in the **Bundle Identifier** field in the **Choose options for your new project** window. +4. Select **Storyboard** in the **Interface** field in the **Choose options for your new project** window. +5. Select **Swift** in the **Language** field in the **Choose options for your new project** window. + +*** + +### **Install Dependencies** + +This developer kit is an add-on feature to CometChat iOS SDK so installing it will also install the core Chat SDK. You can install CometChat UI Kit into your iOS project using CocoaPods or Swift Package Manager (SPM). -1. Open Terminal and navigate to your project folder: -```bash -cd /path/to/your/project -``` +We recommend using CocoaPods, as they are the most advanced way of managing iOS project dependencies. + +1. Create pod file by running the following command in your project's base level: -2. Create a Podfile: -```bash +```ruby Swift pod init ``` -3. Open the Podfile and add CometChat dependencies: -```ruby +2. Add CometChat SDKs to Your Podfile: + +```ruby Swift platform :ios, '13.0' use_frameworks! target 'YourApp' do + # CometChat UI Kit for Swift pod 'CometChatUIKitSwift', '5.1.7' - pod 'CometChatCallsSDK', '4.2.2' # Optional: for voice/video calls + + # Optional: Include if you're using Audio/Video Calling + pod 'CometChatCallsSDK', '4.2.2' end ``` -4. Install the pods: -```bash +3. Install the CometChat UI Kit framework through CocoaPods: + +```ruby Swift pod install ``` -5. Open the `.xcworkspace` file (not `.xcodeproj`): -```bash -open YourApp.xcworkspace +If you're facing any issues while installing pods, use the following command: + +```ruby Swift +pod install --repo-update +``` + +To get the latest version of CometChat UI Kit, use: + +```ruby Swift +pod update CometChatUIKitSwift +pod update CometChatCallsSDK ``` -If pod install fails, try: `pod install --repo-update` + +Always ensure to open the XCFramework file after adding the dependencies. + + - -1. In Xcode, go to **File → Add Package Dependencies** + +**Swift Package Manager** (SPM) is Apple's built-in tool for managing dependencies in Swift projects. It allows developers to integrate and manage third-party libraries seamlessly. + +1. Go to **File** tab and select **Add Package Dependencies.** + +2. Enter the repository URL of the Swift package: -2. Enter the UI Kit repository URL: ``` https://github.com/cometchat/cometchat-uikit-ios ``` -3. Select version **5.1.7** and click **Add Package** +3. To add the package, select Version Rules, enter Up to Exact Version and click Add package. + + Exact Version: + + ``` + 5.1.7 + ``` + +4. Add `CometChatSDK` repeating the above steps for following link and exact version: + + Link: + + ``` + https://github.com/cometchat/chat-sdk-ios + ``` + + Exact Version: + + ``` + 4.1.0 + ``` -4. Repeat for the Chat SDK: -``` -https://github.com/cometchat/chat-sdk-ios -``` -Version: **4.1.0** + -## Step 3: Configure Permissions +*** -Add the following keys to your `Info.plist` file to enable camera, microphone, and photo library access: +### **Configure Privacy Permissions** -```xml -NSCameraUsageDescription -Camera access for capturing photos and videos +1. To enable media messaging in your app, you must allow **Camera**, **Microphone**, and **Photo Library** access in `Info.plist`. These permissions are required for sending and receiving media files. -NSMicrophoneUsageDescription -Microphone access for voice and video calls + ```ruby Info.plist + NSCameraUsageDescription + Allow access to the camera to capture photos and videos. -NSPhotoLibraryUsageDescription -Photo library access to share images + NSMicrophoneUsageDescription + Enable microphone access for voice and video communication. -NSPhotoLibraryAddUsageDescription -Save photos and videos to your library -``` + NSPhotoLibraryAddUsageDescription + Allow saving photos and videos to your device's photo library. - - - + NSPhotoLibraryUsageDescription + Grant access to select and upload photos from your library. + ``` -Also, in **Build Settings**, disable **User Script Sandboxing** to enable collaborative features like whiteboard and document sharing. + + + - - - +2. Navigate to your Build Settings and disable the User Script Sandboxing option. + + Disabling User Script Sandboxing ensures that WebView can load and execute scripts necessary for collaborative tools. + + + + + +*** + +### **Step 4: Initialize & Login to CometChat UI Kit** + +To authenticate a user, you need a **`UID`**. You can either: -## Step 4: Initialize and Login +1. **Create new users** on the **[CometChat Dashboard](https://app.cometchat.com)**, **[CometChat SDK Method](/ui-kit/react/methods#create-user)** or **[via the API](https://api-explorer.cometchat.com/reference/creates-user)**. -Replace the contents of your `SceneDelegate.swift` with the following code: +2. **Use pre-generated test users**: -```swift + * `cometchat-uid-1` + * `cometchat-uid-2` + * `cometchat-uid-3` + * `cometchat-uid-4` + * `cometchat-uid-5` + +The **Login** method returns a **User object** containing all relevant details of the logged-in user. + +*** + + + +**Security Best Practices** + +* The **Auth Key** method is recommended for **proof-of-concept (POC) development** and early-stage testing. +* For **production environments**, it is strongly advised to use an **[Auth Token](/ui-kit/ios/methods#login-using-auth-token)** instead of an **Auth Key** to enhance security and prevent unauthorized access. + + + +You can initialize CometChat and log in a user in your `SceneDelegate.swift` file: + +> ⚠️ **Important:** Initialization and login are independent steps. However, the CometChat SDK **must be initialized before** you call the login method. + +```swift SceneDelegate.swift highlight={13-15} lines import UIKit import CometChatUIKitSwift class SceneDelegate: UIResponder, UIWindowSceneDelegate { - + var window: UIWindow? - + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + guard let windowScene = (scene as? UIWindowScene) else { return } - - // 1. Configure CometChat UI Kit - let settings = UIKitSettings() - .set(appID: "YOUR_APP_ID") // Replace with your App ID - .set(authKey: "YOUR_AUTH_KEY") // Replace with your Auth Key - .set(region: "YOUR_REGION") // "us" or "eu" + + let uikitSettings = UIKitSettings() + .set(appID: "<#Enter Your App ID Here#>") + .set(region: "<#Enter Your Region Code Here#>") + .set(authKey: "<#Enter Your AuthKey Here#>") .subscribePresenceForAllUsers() .build() - - // 2. Initialize CometChat - CometChatUIKit.init(uiKitSettings: settings) { result in + + CometChatUIKit.init(uiKitSettings: uikitSettings) { result in switch result { case .success: - print("✅ CometChat initialized successfully") - self.loginUser(windowScene: windowScene) - - case .failure(let error): - print("❌ Initialization failed: \(error.localizedDescription)") - } - } - } - - private func loginUser(windowScene: UIWindowScene) { - // Use a test user ID or your own user ID - let uid = "cometchat-uid-1" - - CometChatUIKit.login(uid: uid) { result in - switch result { - case .success(let user): - print("✅ Logged in as: \(user.name ?? uid)") - DispatchQueue.main.async { - self.showConversations(windowScene: windowScene) + debugPrint("CometChat UI Kit initialization succeeded") + + let uid = "cometchat-uid-1" + + CometChatUIKit.login(uid: uid) { loginResult in + switch loginResult { + case .success: + debugPrint("CometChat UI Kit login succeeded") + + // ✅ Option 1: Launch One-to-One or Group Chat Screen + // DispatchQueue.main.async { + // self.setUpOneOneOrGroupConversation(windowScene: windowScene, uid: "cometchat-uid-2") + // } + + // ✅ Option 2: Launch Conversation List + Message View (Split-Screen Style) + // DispatchQueue.main.async { + // self.setupConversationsView(windowScene: windowScene) + // } + + // ✅ Option 3: Launch Tab-Based Chat Experience (Chats, Calls, Users, Groups) + // DispatchQueue.main.async { + // self.setupTabbedView(windowScene: windowScene) + // } + + case .onError(let error): + debugPrint("CometChat UI Kit login failed with error: \(error.description)") + @unknown default: + break + } } - - case .onError(let error): - print("❌ Login failed: \(error.description)") - - @unknown default: - break + + case .failure(let error): + debugPrint("CometChat UI Kit initialization failed with error: \(error.localizedDescription)") } } } - - private func showConversations(windowScene: UIWindowScene) { - let conversations = CometChatConversations() - - // Handle conversation tap - open messages - conversations.set(onItemClick: { [weak self] conversation, _ in - self?.openMessages(for: conversation) - }) - - let navigationController = UINavigationController(rootViewController: conversations) - - window = UIWindow(windowScene: windowScene) - window?.rootViewController = navigationController - window?.makeKeyAndVisible() - } - - private func openMessages(for conversation: Conversation) { - let messages = CometChatMessages() - - if let user = conversation.conversationWith as? User { - messages.set(user: user) - } else if let group = conversation.conversationWith as? Group { - messages.set(group: group) - } - - if let nav = window?.rootViewController as? UINavigationController { - nav.pushViewController(messages, animated: true) - } - } } ``` - -**Security Note**: Use Auth Key only for development and testing. In production, use [Auth Tokens](/ui-kit/ios/methods#login-using-auth-token) generated from your backend server. - + + +Ensure you replace the following placeholders with your actual CometChat credentials: -## Step 5: Run Your App +* App ID → Your CometChat App ID +* Auth Key → Your CometChat Auth Key +* Region → Your App Region -Build and run your app (⌘ + R). You should see these messages in the console: +These values are required for proper authentication and seamless integration. -``` -✅ CometChat initialized successfully -✅ Logged in as: cometchat-uid-1 + + +After running the app, you should see the following log message: + +```sh Console +"CometChat UI Kit initialization succeeded" +"CometChat UI Kit login succeeded" ``` -Your app will display the conversations list. Tap any conversation to open the chat screen. +*** -## Test Users +### **Step 5: Choose a Chat Experience** -CometChat provides pre-created test users for development: +Integrate a conversation view that suits your application's **UX requirements**. Below are the available options: -| User ID | Description | -|---------|-------------| -| `cometchat-uid-1` | Test User 1 | -| `cometchat-uid-2` | Test User 2 | -| `cometchat-uid-3` | Test User 3 | -| `cometchat-uid-4` | Test User 4 | -| `cometchat-uid-5` | Test User 5 | +*** -## Chat Experience Options +### **1️⃣ Conversation List + Message View** -Choose the layout that best fits your app: +**Best for:** Native iOS apps using **stack-based navigation** to switch between conversations and messages. -### Option 1: Conversation List + Messages +**Highlights:** -Standard chat app layout with a conversation list that opens message views. +* **Push-Based Navigation** – Taps on conversations open full message views. +* **Supports One-to-One & Group Chats** – Handles all CometChat conversation types. +* **Real-Time Sync** – Messages auto-refresh using live CometChat event listeners. +* **Session-Aware** – Message states persist across app sessions and devices. +* **Customizable UI** – Modify styling, actions, or behavior using CometChat UI Kit. -This is the default implementation shown in Step 4 above. +**Use When:** + +* You need a **native iOS chat experience** with clean transitions. +* Your app supports **private and group messaging**. +* You want **seamless sync and navigation** between list and messages. -[Full Integration Guide →](/ui-kit/ios/ios-conversation) +[Integrate Conversation List + Message View](./ios-conversation) -### Option 2: Direct Chat +*** -Open a chat directly with a specific user or group without showing a list. +### **2️⃣ One-to-One / Group Chat** + +**Best for:** iOS apps that launch **directly into a conversation screen** without showing a list. + +**Highlights:** + +* **Single View Chat** – Use `CometChatMessages` with a passed user or group object. +* **No Sidebar or List** – Ideal for contextual entry points (support, match, invite, etc.). +* **Works with UINavigationController & SwiftUI NavigationStack** +* **Lightweight** – Launches faster and uses minimal memory. +* **Full-Screen Messaging** – Clear, immersive chat UI. -```swift -import UIKit -import CometChatUIKitSwift -import CometChatSDK +**Use When:** -class DirectChatViewController: UIViewController { - - override func viewDidLoad() { - super.viewDidLoad() - openChatWithUser(uid: "cometchat-uid-2") - } - - func openChatWithUser(uid: String) { - CometChat.getUser(UID: uid) { [weak self] user in - DispatchQueue.main.async { - let messages = CometChatMessages() - messages.set(user: user) - self?.navigationController?.pushViewController(messages, animated: true) - } - } onError: { error in - print("Error: \(error?.errorDescription ?? "")") - } - } - - func openChatWithGroup(guid: String) { - CometChat.getGroup(GUID: guid) { [weak self] group in - DispatchQueue.main.async { - let messages = CometChatMessages() - messages.set(group: group) - self?.navigationController?.pushViewController(messages, animated: true) - } - } onError: { error in - print("Error: \(error?.errorDescription ?? "")") - } - } -} -``` +* Your app starts directly with a **specific user or group chat**. +* You want a **clean, distraction-free** chat experience. +* Ideal for **support workflows, community replies, or invitations.** + +[Integrate One-to-One / Group Chat](./ios-one-to-one-chat) + +*** -[Full Integration Guide →](/ui-kit/ios/ios-one-to-one-chat) +### **3️⃣ Tab-Based Messaging UI (All-in-One)** -### Option 3: Tab-Based Layout +**Best for:** iOS apps needing a **multi-tab interface** with seamless transitions between Chats, Users, Calls, and Settings. -Full-featured chat app with tabs for Chats, Users, Groups, and more. +**Highlights:** + +* **UITabBarController or SwiftUI TabView** – Native navigation pattern for iOS. +* **Modular UI** – Isolated controllers or views for each tab. +* **Full-Screen Messaging** – Dedicated message views within the Chat tab. +* **Extensible** – Add future tabs like Notifications, Search, or Profile. +* **Responsive Layouts** – Works across iPhones and iPads. +* **Great for SuperApps & Enterprise Tools** -```swift -import UIKit -import CometChatUIKitSwift -import CometChatSDK +**Use When:** -class ChatTabBarController: UITabBarController { - - override func viewDidLoad() { - super.viewDidLoad() - setupTabs() - } - - private func setupTabs() { - // Chats Tab - let chatsNav = UINavigationController() - let conversations = CometChatConversations() - conversations.set(onItemClick: { [weak chatsNav] conversation, _ in - let messages = CometChatMessages() - if let user = conversation.conversationWith as? User { - messages.set(user: user) - } else if let group = conversation.conversationWith as? Group { - messages.set(group: group) - } - chatsNav?.pushViewController(messages, animated: true) - }) - chatsNav.setViewControllers([conversations], animated: false) - chatsNav.tabBarItem = UITabBarItem( - title: "Chats", - image: UIImage(systemName: "message"), - selectedImage: UIImage(systemName: "message.fill") - ) - - // Users Tab - let usersNav = UINavigationController() - let users = CometChatUsers() - users.set(onItemClick: { [weak usersNav] user, _ in - let messages = CometChatMessages() - messages.set(user: user) - usersNav?.pushViewController(messages, animated: true) - }) - usersNav.setViewControllers([users], animated: false) - usersNav.tabBarItem = UITabBarItem( - title: "Users", - image: UIImage(systemName: "person.2"), - selectedImage: UIImage(systemName: "person.2.fill") - ) - - // Groups Tab - let groupsNav = UINavigationController() - let groups = CometChatGroups() - groups.set(onItemClick: { [weak groupsNav] group, _ in - let messages = CometChatMessages() - messages.set(group: group) - groupsNav?.pushViewController(messages, animated: true) - }) - groupsNav.setViewControllers([groups], animated: false) - groupsNav.tabBarItem = UITabBarItem( - title: "Groups", - image: UIImage(systemName: "person.3"), - selectedImage: UIImage(systemName: "person.3.fill") - ) - - viewControllers = [chatsNav, usersNav, groupsNav] - } -} -``` +* You need a **structured layout** for navigating chat, calls, and contacts. +* Your app supports **multiple modules** (e.g., user directory, history, chat). +* Designed for **enterprise, support, or social use cases**. + +[Integrate Tab-Based Chat](./ios-tab-based-chat) + +*** + +## **Build Your Own Chat Experience** + +**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app’s design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. + +**Recommended for:** + +* Apps that require **a fully customized chat experience**. +* Developers who want to **extend functionalities and modify UI components**. +* Businesses integrating chat seamlessly into **existing platforms**. + +**Key Areas to Explore:** + +* **[iOS Sample App](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp)** – Fully functional sample applications to accelerate your development. +* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities. +* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design. +* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding. +* **[Build Your Own UI](/sdk/javascript/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience. -[Full Integration Guide →](/ui-kit/ios/ios-tab-based-chat) +*** -## Troubleshooting +## **Next Steps** -| Issue | Solution | -|-------|----------| -| Pod install fails | Run `pod install --repo-update` | -| Initialization fails | Verify App ID, Auth Key, and Region are correct | -| Login fails | Check that the user exists in your CometChat dashboard | -| UI not displaying | Ensure UI updates are on the main thread | -| Permissions denied | Add all required keys to Info.plist | -| Collaborative features not working | Disable User Script Sandboxing in Build Settings | +Now that you’ve selected your **chat experience**, proceed to the **integration guide**: -## Next Steps +* **[Integrate Conversation List + Message](/ui-kit/ios/ios-conversation)** +* **[Integrate One-to-One Chat](/ui-kit/ios/ios-one-to-one-chat)** +* **[Integrate Tab-Based Chat](/ui-kit/ios/ios-tab-based-chat)** +* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** -- [Core Features](/ui-kit/ios/core-features) - Messaging, reactions, threads, and more -- [Components](/ui-kit/ios/components-overview) - All available UI components -- [Theming](/ui-kit/ios/theme-introduction) - Customize colors, fonts, and styles -- [Events](/ui-kit/ios/events) - Listen for chat events -- [Extensions](/ui-kit/ios/extensions) - Enable additional features -- [Sample App](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) - Full working example +*** diff --git a/ui-kit/ios/ios-conversation.mdx b/ui-kit/ios/ios-conversation.mdx index 1acf8462b..6124c475c 100644 --- a/ui-kit/ios/ios-conversation.mdx +++ b/ui-kit/ios/ios-conversation.mdx @@ -1,36 +1,33 @@ --- title: "Building A Conversation List + Message View" sidebarTitle: "Conversation List + Message View" -description: "Create a two-panel chat experience with conversation list and messages" --- -The Conversation List + Message View layout offers a modern two-panel chat experience. It's ideal for applications needing seamless switching between multiple conversations and chat windows—similar to WhatsApp Web, Slack, or Microsoft Teams. +The **Conversation List + Message View** layout offers a modern two-panel chat experience. It's ideal for applications needing seamless switching between multiple conversations and chat windows—similar to **WhatsApp Web**, **Slack**, or **Microsoft Teams**. ---- +*** -## User Interface Preview +## **User Interface Preview** -### Key Components +### **Key Components** -| Component | Description | -|-----------|-------------| -| Chat Header | Displays user or group name, avatar, and back button | -| Message List | Displays chat messages and real-time updates | -| Message Composer | Allows sending of text, media, and reactions | +1. **Chat Header** – Displays user or group name, avatar, and back button. +2. **Message List** – Displays chat messages and real-time updates. +3. **Message Composer** – Allows sending of text, media, and reactions. ---- +*** -## Step-by-Step Guide +## **Step-by-Step Guide** -### Step 1: Setup SceneDelegate.swift +### **Step 1: Setup SceneDelegate.swift** Ensure UIKit is initialized and the user is logged in before presenting the conversation view. -```swift +```swift SceneDelegate.swift highlight={15-17} lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -44,7 +41,6 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard let windowScene = (scene as? UIWindowScene) else { return } - // Configure UIKit settings with your credentials let uikitSettings = UIKitSettings() .set(appID: "<#Enter Your App ID Here#>") .set(region: "<#Enter Your Region Code Here#>") @@ -52,13 +48,11 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { .subscribePresenceForAllUsers() .build() - // Initialize CometChat UIKit CometChatUIKit.init(uiKitSettings: uikitSettings) { result in switch result { case .success: debugPrint("CometChatUIKit initialization succeeded") - // Login with a test user let uid = "cometchat-uid-1" CometChatUIKit.login(uid: uid) { loginResult in @@ -66,7 +60,6 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { case .success: debugPrint("CometChatUIKit login succeeded") - // Setup conversations view on main thread DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.setupConversationsView(windowScene: windowScene) @@ -85,23 +78,16 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } func setupConversationsView(windowScene: UIWindowScene) { - // Create conversations list view controller let conversationsVC = CometChatConversations() let navController = UINavigationController(rootViewController: conversationsVC) - // Handle conversation item click conversationsVC.set(onItemClick: { [weak navController] conversation, _ in let messagesVC = MessagesVC() - - // Set user or group based on conversation type messagesVC.group = conversation.conversationWith as? Group messagesVC.user = conversation.conversationWith as? CometChatSDK.User - - // Navigate to messages screen navController?.pushViewController(messagesVC, animated: true) }) - // Configure and display window window = UIWindow(windowScene: windowScene) window?.rootViewController = navController window?.makeKeyAndVisible() @@ -109,13 +95,13 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } ``` ---- +*** -### Step 2: Create MessagesVC.swift +### **Step 2: Create MessagesVC.swift** This view controller handles chat between users or within groups. -```swift +```swift MessagesVC.swift lines import UIKit import CometChatSDK import CometChatUIKitSwift @@ -137,14 +123,12 @@ class MessagesVC: UIViewController { private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { view.set(group: group) } - view.set(controller: self) return view }() @@ -153,14 +137,12 @@ class MessagesVC: UIViewController { private lazy var composerView: CometChatMessageComposer = { let composer = CometChatMessageComposer() composer.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { composer.set(user: user) } else if let group = group { composer.set(group: group) } - composer.set(controller: self) return composer }() @@ -169,14 +151,12 @@ class MessagesVC: UIViewController { private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { listView.set(group: group) } - listView.set(controller: self) return listView }() @@ -230,14 +210,12 @@ class MessagesVC: UIViewController { } ``` ---- +*** -## Next Steps +## **Next Steps** -### Enhance the User Experience +### **Enhance the User Experience** -- [Advanced Customizations](/ui-kit/ios/theme-introduction) — Personalize the chat UI to align with your brand -- [Core Features](/ui-kit/ios/core-features) — Explore messaging, reactions, threads, and more -- [Components Overview](/ui-kit/ios/components-overview) — Browse all available UI components +* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. ---- +*** diff --git a/ui-kit/ios/ios-one-to-one-chat.mdx b/ui-kit/ios/ios-one-to-one-chat.mdx index 300f4a062..ae1c160d6 100644 --- a/ui-kit/ios/ios-one-to-one-chat.mdx +++ b/ui-kit/ios/ios-one-to-one-chat.mdx @@ -1,36 +1,33 @@ --- title: "Building A One To One/Group Chat Experience" sidebarTitle: "One To One/Group Chat" -description: "Create a direct messaging interface for private conversations" --- -The One-to-One Chat feature provides a streamlined direct messaging interface, making it ideal for support chats, dating apps, and private messaging platforms. This setup eliminates distractions by focusing solely on a dedicated chat window. +The **One-to-One Chat** feature provides a streamlined **direct messaging interface**, making it ideal for **support chats, dating apps, and private messaging platforms**. This setup eliminates distractions by focusing solely on a **dedicated chat window**. ---- +*** -## User Interface Preview +## **User Interface Preview** -### Key Components +### **Key Components** -| Component | Description | -|-----------|-------------| -| Chat Header | Displays recipient details and optional call/video call buttons | -| Message View | Shows real-time chat history | -| Message Input Box | Enables users to send messages, media, and reactions | +1. **Chat Header** – Displays recipient details and optional call/video call buttons. +2. **Message View** – Shows real-time chat history. +3. **Message Input Box** – Enables users to send messages, media, and reactions. ---- +*** -## Step-by-Step Guide +## **Step-by-Step Guide** -### Step 1: Setup SceneDelegate.swift +### **Step 1: Setup SceneDelegate.swift** Ensure UI Kit is initialized and the user is logged in before presenting the message view. -```swift +```swift SceneDelegate.swift highlight={15-17} lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -44,7 +41,6 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { guard let windowScene = (scene as? UIWindowScene) else { return } - // Configure UIKit settings with your credentials let uikitSettings = UIKitSettings() .set(appID: "<#Enter Your App ID Here#>") .set(region: "<#Enter Your Region Code Here#>") @@ -52,13 +48,11 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { .subscribePresenceForAllUsers() .build() - // Initialize CometChat UIKit CometChatUIKit.init(uiKitSettings: uikitSettings) { result in switch result { case .success: debugPrint("CometChat UI Kit initialization succeeded") - // Login with a test user let uid = "cometchat-uid-1" CometChatUIKit.login(uid: uid) { loginResult in @@ -66,7 +60,6 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { case .success: debugPrint("CometChat UI Kit login succeeded") - // Setup one-on-one conversation on main thread DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.setUpOneOneOrGroupConversation(windowScene: windowScene, uid: "cometchat-uid-2") @@ -84,35 +77,33 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } } - func setUpOneOneOrGroupConversation(windowScene: UIWindowScene, uid: String) { - // Fetch the user to chat with + func setUpOneOneOrGroupConversation(windowScene: UIWindowScene, uid : String) { CometChat.getUser(UID: uid) { user in DispatchQueue.main.async { - // Create messages view controller let messagesVC = MessagesVC() let navController = UINavigationController(rootViewController: messagesVC) messagesVC.user = user - - // Configure and display window self.window = UIWindow(windowScene: windowScene) self.window?.rootViewController = navController self.window?.makeKeyAndVisible() } } onError: { error in - // Handle error + } + } + } ``` ---- +*** -### Step 2: Create MessagesVC.swift +### **Step 2: Create MessagesVC.swift** This view controller handles chat between users or within groups. -```swift +```swift MessagesVC.swift lines import UIKit import CometChatSDK import CometChatUIKitSwift @@ -134,14 +125,12 @@ class MessagesVC: UIViewController { private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { view.set(group: group) } - view.set(controller: self) return view }() @@ -150,14 +139,12 @@ class MessagesVC: UIViewController { private lazy var composerView: CometChatMessageComposer = { let composer = CometChatMessageComposer() composer.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { composer.set(user: user) } else if let group = group { composer.set(group: group) } - composer.set(controller: self) return composer }() @@ -166,14 +153,12 @@ class MessagesVC: UIViewController { private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { listView.set(group: group) } - listView.set(controller: self) return listView }() @@ -227,14 +212,12 @@ class MessagesVC: UIViewController { } ``` ---- +*** -## Next Steps +## **Next Steps** -### Enhance the User Experience +### **Enhance the User Experience** -- [Advanced Customizations](/ui-kit/ios/theme-introduction) — Personalize the chat UI to align with your brand -- [Core Features](/ui-kit/ios/core-features) — Explore messaging, reactions, threads, and more -- [Components Overview](/ui-kit/ios/components-overview) — Browse all available UI components +* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. ---- +*** diff --git a/ui-kit/ios/ios-tab-based-chat.mdx b/ui-kit/ios/ios-tab-based-chat.mdx index 7b953306b..8c6d7b047 100644 --- a/ui-kit/ios/ios-tab-based-chat.mdx +++ b/ui-kit/ios/ios-tab-based-chat.mdx @@ -1,100 +1,77 @@ --- title: "Building A Tab Based Messaging UI In iOS" sidebarTitle: "Tab Based Chat Experience" -description: "Create a complete tab-based messaging interface with Chats, Calls, Users, and Groups tabs using CometChat UI Kit for iOS" --- This guide walks you through creating a **tab-based messaging interface** in your **iOS application** using **CometChat UI Kit for iOS**. The UI includes tabs for **Chats**, **Calls**, **Users**, and **Groups**, offering an organized and fluid experience. ---- +*** -## User Interface Preview +## **User Interface Preview** -### Tab Layout Overview +This layout contains: -| Tab | Component | Description | -|-----|-----------|-------------| -| Chats | `CometChatConversations` | Lists all recent conversations | -| Calls | `CometChatCallLogs` | Displays call history and logs | -| Users | `CometChatUsers` | Lists available users to chat with | -| Groups | `CometChatGroups` | Lists available groups to join | +1. **Conversations** – Lists all recent chats. +2. **Calls** – Displays call logs. +3. **Users** – Lists available users. +4. **Groups** – Lists available groups. ---- +*** -## Step-by-Step Guide +## **Step-by-Step Guide** -### Step 1: Initialize UIKit in SceneDelegate.swift +### **Step 1: Initialize UIKit in `SceneDelegate.swift`** Ensure UIKit is initialized and the user is logged in before presenting the tabbed view. -```swift SceneDelegate.swift -import UIKit -import CometChatUIKitSwift -import CometChatSDK - -class SceneDelegate: UIResponder, UIWindowSceneDelegate { - - var window: UIWindow? - - func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - guard let windowScene = (scene as? UIWindowScene) else { return } - - // Configure UIKit settings with your credentials - let uikitSettings = UIKitSettings() - .set(appID: "<#Enter Your App ID Here#>") - .set(region: "<#Enter Your Region Code Here#>") - .set(authKey: "<#Enter Your AuthKey Here#>") - .subscribePresenceForAllUsers() - .build() - - // Initialize CometChat UIKit - CometChatUIKit.init(uiKitSettings: uikitSettings) { result in - switch result { - case .success: - debugPrint("CometChat UI Kit initialization succeeded") - - // Login with a test user - CometChatUIKit.login(uid: "cometchat-uid-1") { loginResult in - switch loginResult { - case .success: - debugPrint("CometChat UI Kit login succeeded") - - // Setup tabbed view on main thread - DispatchQueue.main.async { - self.setupTabbedView(windowScene: windowScene) - } - - case .onError(let error): - debugPrint("Login failed: \(error.description)") - @unknown default: break +```swift SceneDelegate.swift highlight={5-7} lines +func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { + guard let windowScene = (scene as? UIWindowScene) else { return } + + let uikitSettings = UIKitSettings() + .set(appID: "<#Enter Your App ID Here#>") + .set(region: "<#Enter Your Region Code Here#>") + .set(authKey: "<#Enter Your AuthKey Here#>") + .subscribePresenceForAllUsers() + .build() + + CometChatUIKit.init(uiKitSettings: uikitSettings) { result in + switch result { + case .success: + CometChatUIKit.login(uid: "cometchat-uid-1") { loginResult in + switch loginResult { + case .success: + DispatchQueue.main.async { + self.setupTabbedView(windowScene: windowScene) } + default: + break } - - case .failure(let error): - debugPrint("Initialization failed: \(error.localizedDescription)") } + default: + break } } } ``` ---- +*** -### Step 2: Setup Tab Bar Controller +### **Step 2: Setup Tab Bar** -Create a method to configure and display the tab layout with all four tabs. +Create a method to display the tab layout. -```swift SceneDelegate.swift +```swift SceneDelegate.swift lines func setupTabbedView(windowScene: UIWindowScene) { // Create the main Tab Bar Controller let tabBarController = UITabBarController() tabBarController.tabBar.backgroundColor = .white - + // MARK: - Conversations Tab let conversationsVC = CometChatConversations() let conversationsNav = UINavigationController(rootViewController: conversationsVC) @@ -103,8 +80,8 @@ func setupTabbedView(windowScene: UIWindowScene) { image: UIImage(systemName: "message.fill"), tag: 0 ) - - // Handle conversation item tap to open messages + + // Handle item click inside conversation list conversationsVC.set(onItemClick: { [weak conversationsNav] conversation, indexPath in let messagesVC = MessagesVC() messagesVC.group = conversation.conversationWith as? Group @@ -112,7 +89,7 @@ func setupTabbedView(windowScene: UIWindowScene) { messagesVC.hidesBottomBarWhenPushed = true conversationsNav?.pushViewController(messagesVC, animated: true) }) - + // MARK: - Call Logs Tab let callLogsVC = CometChatCallLogs() let callLogsNav = UINavigationController(rootViewController: callLogsVC) @@ -121,7 +98,7 @@ func setupTabbedView(windowScene: UIWindowScene) { image: UIImage(systemName: "phone.fill"), tag: 1 ) - + // MARK: - Users Tab let usersVC = CometChatUsers() let usersNav = UINavigationController(rootViewController: usersVC) @@ -130,7 +107,7 @@ func setupTabbedView(windowScene: UIWindowScene) { image: UIImage(systemName: "person.2.fill"), tag: 2 ) - + // MARK: - Groups Tab let groupsVC = CometChatGroups() let groupsNav = UINavigationController(rootViewController: groupsVC) @@ -139,7 +116,7 @@ func setupTabbedView(windowScene: UIWindowScene) { image: UIImage(systemName: "person.3.fill"), tag: 3 ) - + // Assign all navigation controllers to the Tab Bar tabBarController.viewControllers = [ conversationsNav, @@ -147,115 +124,110 @@ func setupTabbedView(windowScene: UIWindowScene) { usersNav, groupsNav ] - + // Ensures layout includes space for opaque bars like the navigation bar tabBarController.extendedLayoutIncludesOpaqueBars = true - + // Setup and display main window with tabBarController as root window = UIWindow(windowScene: windowScene) window?.rootViewController = tabBarController window?.makeKeyAndVisible() + } ``` ---- +*** -### Step 3: Create MessagesVC.swift +### **Step 3: Create `MessagesVC.swift`** -This view controller handles chat between users or within groups when a conversation is selected. +This view controller handles chat between users or within groups. -```swift MessagesVC.swift +```swift MessagesVC.swift lines import UIKit import CometChatSDK import CometChatUIKitSwift /// A view controller that displays a chat interface using CometChat components class MessagesVC: UIViewController { - + // MARK: - Properties - + /// The user entity for one-on-one chats var user: User? - + /// The group entity for group chats var group: Group? - + // MARK: - UI Components - + /// Header view displaying user/group information private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { view.set(group: group) } - view.set(controller: self) return view }() - + /// Message input composer view private lazy var composerView: CometChatMessageComposer = { let composer = CometChatMessageComposer() composer.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { composer.set(user: user) } else if let group = group { composer.set(group: group) } - composer.set(controller: self) return composer }() - + /// List view displaying chat messages private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { listView.set(group: group) } - listView.set(controller: self) return listView }() - + // MARK: - Lifecycle Methods - + override func viewDidLoad() { super.viewDidLoad() configureView() setupLayout() } - + override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } - + // MARK: - Private Methods - + /// Configure basic view properties private func configureView() { view.backgroundColor = .systemBackground navigationController?.setNavigationBarHidden(true, animated: false) } - + /// Set up view hierarchy and constraints private func setupLayout() { // Add subviews to the view hierarchy [headerView, messageListView, composerView].forEach { view.addSubview($0) } - + // Set up constraints NSLayoutConstraint.activate([ // Header view constraints @@ -263,13 +235,13 @@ class MessagesVC: UIViewController { headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), headerView.heightAnchor.constraint(equalToConstant: 50), - + // Message list view constraints messageListView.topAnchor.constraint(equalTo: headerView.bottomAnchor), messageListView.leadingAnchor.constraint(equalTo: view.leadingAnchor), messageListView.trailingAnchor.constraint(equalTo: view.trailingAnchor), messageListView.bottomAnchor.constraint(equalTo: composerView.topAnchor), - + // Composer view constraints composerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), composerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), @@ -279,13 +251,12 @@ class MessagesVC: UIViewController { } ``` ---- +*** -## Next Steps +## **Next Steps** -- [One To One/Group Chat](/ui-kit/ios/ios-one-to-one-chat) — Build a focused direct messaging interface -- [Conversation List + Messages](/ui-kit/ios/ios-conversation) — Create a split-view chat experience -- [Theme Introduction](/ui-kit/ios/theme-introduction) — Customize the chat UI to match your brand -- [Components Overview](/ui-kit/ios/components-overview) — Explore all available UI components +### **Enhance the User Experience** ---- +* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. + +*** From cacae38d8cd664d45064cd5c142a39af78f9b7a9 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 14:25:38 +0530 Subject: [PATCH 019/106] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 96adadbc8..19273fa01 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .DS_Store .kiro/ +/codebase From ce931013c36f8b729626b6db6c98be5df5ed36df Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 14:49:44 +0530 Subject: [PATCH 020/106] adds missing methods --- ui-kit/flutter/conversations.mdx | 7 +++++++ ui-kit/flutter/message-list.mdx | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index 32dc1707c..adaac93ab 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -403,6 +403,13 @@ List of Poperties exposed by `CometChatConversations` | **Disable Sound For Messages** | Disable sound for messages | `disableSoundForMessages: bool` | | **Mention All Label Id** | Allows setting a custom label id for group mentions (@channel, @everyone, etc.). | `mentionAllLabelId: String` | | **Mention All Label** | Allows setting a custom label for group mentions (@channel, @everyone, etc.). | `mentionAllLabel: String` | +| **Hide Search** | Hides the search bar in the app bar | `hideSearch: bool` | +| **Search Read Only** | Makes the search box read-only | `searchReadOnly: bool` | +| **On Search Tap** | Callback triggered when the search box is tapped | `onSearchTap: GestureTapCallback` | +| **Search Box Icon** | Custom prefix icon for the search box | `searchBoxIcon: Widget` | +| **Search Padding** | Provides padding for the search box | `searchPadding: EdgeInsetsGeometry` | +| **Search Content Padding** | Provides padding for the search box content | `searchContentPadding: EdgeInsetsGeometry` | +| **Date Time Formatter Callback** | Callback that can be used to format the date and time | `dateTimeFormatterCallback: DateTimeFormatterCallback` | ### Advanced diff --git a/ui-kit/flutter/message-list.mdx b/ui-kit/flutter/message-list.mdx index 097a01648..aaf056e49 100644 --- a/ui-kit/flutter/message-list.mdx +++ b/ui-kit/flutter/message-list.mdx @@ -451,6 +451,10 @@ Below is a list of customizations along with corresponding code snippets: | `startFromUnreadMessages` | `bool?` | Starts the message list from the first unread message. | | `showMarkAsUnreadOption` | `bool?` | show the visibility of the "Mark unread" option in the message actions menu. | | `newMessageIndicatorView` | `Widget?` | Custom view for the unread message indicator. | +| `enableConversationSummary` | `bool?` | Enables conversation summary generation. | +| `generateConversationSummary` | `bool?` | Triggers conversation summary generation. | +| `hideReplyOption` | `bool?` | Hides the reply message option. | +| `flagReasonLocalizer` | `String Function(String reasonId)?` | Function to localize flag reason IDs to the desired language. | *** From f2bd637ec39b10c416e42c93a573cf5c32d49bf0 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 15:19:28 +0530 Subject: [PATCH 021/106] Update group-members.mdx --- ui-kit/flutter/group-members.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/flutter/group-members.mdx b/ui-kit/flutter/group-members.mdx index 8ad574c0b..693396536 100644 --- a/ui-kit/flutter/group-members.mdx +++ b/ui-kit/flutter/group-members.mdx @@ -486,7 +486,7 @@ CometChatGroupMembers( | `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | | `leadingStateView` | `Widget? Function(BuildContext, GroupMember)?` | Widget for the leading section of each group member. | | `titleView` | `Widget? Function(BuildContext, GroupMember)?` | Custom title view for each group member. | -| `hideUserStatus` | `bool?` | Flag to hide the user status indicator on the avatar. | +| `usersStatusVisibility` | `bool?` | Controls visibility of the user status indicator on the avatar (default: true). | | `hideBanMemberOption` | `bool?` | Flag to hide the ban member option. | | `hideKickMemberOption` | `bool?` | Flag to hide the kick member option. | | `hideScopeChangeOption` | `bool?` | Flag to hide the scope change option. | From 4bd9167fb9ee5f16f605b4643ed11cdc52cb9e5d Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 16:11:16 +0530 Subject: [PATCH 022/106] updates events and methods --- ui-kit/flutter/events.mdx | 52 +++++++++++++++++++++- ui-kit/flutter/methods.mdx | 88 +++++++++++++++++++++++++++++++++++++- 2 files changed, 137 insertions(+), 3 deletions(-) diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 7d7f857d1..4b0a0a06e 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -24,8 +24,8 @@ void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { **Available Event Types:** - **User Events** → Block/Unblock users - **Group Events** → Create, delete, join, leave groups -- **Conversation Events** → Delete conversations -- **Message Events** → Send, edit, delete, receive messages +- **Conversation Events** → Delete conversations, update conversations +- **Message Events** → Send, edit, delete, receive messages, reactions, AI messages - **Call Events** → Outgoing, accepted, rejected, ended calls - **UI Events** → Show/hide panels, active chat changes @@ -212,6 +212,7 @@ The `CometChatConversationEvents` component emits events when the logged-in user **Available Events:** 1. `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. +2. `ccUpdateConversation`: Triggered when a conversation is updated (e.g., unread count changes). @@ -248,6 +249,11 @@ class _ConversationEventsExampleState extends State w // TODO("Not yet implemented") } + @override + void ccUpdateConversation(Conversation conversation) { + // TODO("Not yet implemented") + } + @override Widget build(BuildContext context) { return const Placeholder(); @@ -288,6 +294,13 @@ class _ConversationEventsExampleState extends State w 21. `onSchedulerMessageReceived`: Triggered when a scheduler message is received. 22. `onMessageReactionAdded`: Triggered when a reaction is added to a message. 23. `onMessageReactionRemoved`: Triggered when a reaction is removed from a message. +24. `ccReplyToMessage`: Triggered when the logged-in user replies to a message. +25. `onMessagesDeliveredToAll`: Triggered when messages are delivered to all recipients. +26. `onMessagesReadByAll`: Triggered when messages are read by all recipients. +27. `onMessageModerated`: Triggered when a message is moderated. +28. `onAIAssistantMessageReceived`: Triggered when an AI Assistant message is received. +29. `onAIToolResultReceived`: Triggered when an AI tool result is received. +30. `onAIToolArgumentsReceived`: Triggered when AI tool arguments are received. @@ -430,6 +443,41 @@ class _MessageEventsExampleState extends State with CometC // TODO("Not yet implemented") } + @override + void ccReplyToMessage(BaseMessage message, MessageStatus status) { + // TODO("Not yet implemented") + } + + @override + void onMessagesDeliveredToAll(MessageReceipt messageReceipt) { + // TODO("Not yet implemented") + } + + @override + void onMessagesReadByAll(MessageReceipt messageReceipt) { + // TODO("Not yet implemented") + } + + @override + void onMessageModerated(BaseMessage message) { + // TODO("Not yet implemented") + } + + @override + void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { + // TODO("Not yet implemented") + } + + @override + void onAIToolResultReceived(AIToolResultMessage aiToolResultMessage) { + // TODO("Not yet implemented") + } + + @override + void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { + // TODO("Not yet implemented") + } + @override Widget build(BuildContext context) { return const Placeholder(); diff --git a/ui-kit/flutter/methods.mdx b/ui-kit/flutter/methods.mdx index 9423a6005..d0ab76a2a 100644 --- a/ui-kit/flutter/methods.mdx +++ b/ui-kit/flutter/methods.mdx @@ -40,6 +40,10 @@ Here's the table format for the properties available in `UIKitSettings`: | **autoEstablishSocketConnection** | `Boolean` | Configures if web socket connections will established automatically on app initialization or be done manually, set to true by default | | **aiFeature** | `List` | Sets the AI Features that need to be added in UI Kit | | **extensions** | `List` | Sets the list of extension that need to be added in UI Kit | +| **callingExtension** | `ExtensionsDataSource` | Sets the calling extension configuration | +| **adminHost** | `String` | Sets a custom admin host URL | +| **clientHost** | `String` | Sets a custom client host URL | +| **dateTimeFormatterCallback** | `DateTimeFormatterCallback` | Sets a custom date/time formatter for consistent formatting across all UI components | *** @@ -142,7 +146,47 @@ As a developer, you can dynamically create users on CometChat using the `.create ```dart -CometChat.createUser(userObject, 'authKey', onSuccess: (user) { +CometChatUIKit.createUser(userObject, onSuccess: (user) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); +``` + + + + + +*** + +### Update User + +As a developer, you can update user details using the `.updateUser()` function. This should ideally be achieved at your backend using the Restful APIs, but can also be done client-side when needed. + + + +```dart +CometChatUIKit.updateUser(userObject, onSuccess: (user) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); +``` + + + + + +*** + +### Get Logged In User + +You can check if there is any existing session in the SDK and retrieve the details of the logged-in user using the `.getLoggedInUser()` function. + + + +```dart +CometChatUIKit.getLoggedInUser(onSuccess: (user) { // TODO("Not yet implemented") }, onError: (e) { // TODO("Not yet implemented") @@ -446,3 +490,45 @@ CometChatUIKit.sendCustomInteractiveMessage(interactiveMessageObject, onSuccess: *** + +### Reactions + +#### Add Reaction + +As a developer, you can add a reaction to a message using the `addReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. + + + +```dart +CometChatUIKit.addReaction(messageId, "👍", onSuccess: (message) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); +``` + + + + + +*** + +#### Remove Reaction + +As a developer, you can remove a reaction from a message using the `removeReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. + + + +```dart +CometChatUIKit.removeReaction(messageId, "👍", onSuccess: (message) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); +``` + + + + + +*** From e46793eaab88869f50a285255fcd580d600b575e Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 16:36:28 +0530 Subject: [PATCH 023/106] updates the findings --- ui-kit/flutter/mentions-formatter-guide.mdx | 47 +++++++++++++++++++- ui-kit/flutter/message-template.mdx | 48 ++++++++++++++++++++ ui-kit/flutter/shortcut-formatter-guide.mdx | 49 +++++++++++++++++++++ 3 files changed, 143 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/mentions-formatter-guide.mdx b/ui-kit/flutter/mentions-formatter-guide.mdx index aa5989ca2..97a49cfed 100644 --- a/ui-kit/flutter/mentions-formatter-guide.mdx +++ b/ui-kit/flutter/mentions-formatter-guide.mdx @@ -129,7 +129,6 @@ CometChatMessages( | **showLoadingIndicator** | Whether to show a loading indicator during mention search. | `bool? showLoadingIndicator` | | **onSearch** | Callback function to perform search when mention is triggered. | `void Function(String)? onSearch` | | **onError** | Callback function to handle errors during mention search. | `void Function(String)? onError` | -| **theme** | The theme for styling the mentions formatter. | `ThemeData? theme` | | **message** | The message in which mentions are to be formatted. | `String? message` | | **messageBubbleTextStyle** | The text style for the message bubble. | `TextStyle? messageBubbleTextStyle` | | **messageInputTextStyle** | The text style for the message input. | `TextStyle? messageInputTextStyle` | @@ -143,6 +142,11 @@ CometChatMessages( | **mentionsType** | The type of mentions (e.g., user, group). | `MentionsType? mentionsType` | | **onMentionTap** | Callback function to handle mention tap actions. | `void Function(User)? onMentionTap` | | **visibleIn** | Defines where the mentions are visible. | `Set? visibleIn` | +| **style** | Style configuration for customizing mention appearance. | `CometChatMentionsStyle? style` | +| **disableMentions** | Disables mentions in the composer (default: false). | `bool disableMentions` | +| **disableMentionAll** | Controls whether @all mention is enabled (default: false). | `bool disableMentionAll` | +| **mentionAllLabel** | Custom label to display for @all mention. | `String? mentionAllLabel` | +| **mentionAllLabelId** | Custom ID for @all mention (default: "all"). | `String? mentionAllLabelId` | *** @@ -150,6 +154,47 @@ CometChatMessages( For advanced-level customization, you can set the style of the Mentions formatters. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your formatters style. +### @all Mention Feature + +The `CometChatMentionsFormatter` supports mentioning all members in a group using the @all feature. When enabled, users can type `@` followed by "all" (or a custom label) to notify everyone in the group. + + + +```dart +CometChatMessages( + group: group, + messageComposerConfiguration: MessageComposerConfiguration( + textFormatters: [ + CometChatMentionsFormatter( + disableMentionAll: false, // Enable @all mention (default) + mentionAllLabel: "everyone", // Custom label (optional) + mentionAllLabelId: "all", // Custom ID (optional) + ) + ] + ), +) +``` + + + + + +To disable the @all mention feature: + + + +```dart +CometChatMentionsFormatter( + disableMentionAll: true, // Disable @all mention +) +``` + + + + + +*** + ### Composer Mention Text Style Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel for [CometChatMessageComposer](/ui-kit/flutter/message-composer) refer to the below code snippet diff --git a/ui-kit/flutter/message-template.mdx b/ui-kit/flutter/message-template.mdx index ddd2891da..6be26a674 100644 --- a/ui-kit/flutter/message-template.mdx +++ b/ui-kit/flutter/message-template.mdx @@ -154,6 +154,54 @@ MessageTemplate provides you with methods that allow you to alter various proper +9. **Status Info Widget** + + The `statusInfoView` property allows you to assign a custom status info widget to the MessageBubble. By default, it displays the timestamp and read receipt under the content view. + + + + ```dart + cometChatMessageTemplate.statusInfoView = (BaseMessage baseMessage, BuildContext buildContext, BubbleAlignment alignment) { + return const Placeholder(); + }; + ``` + + + + + +10. **Thread Widget** + + The `threadView` property allows you to assign a custom thread widget to the MessageBubble. This is displayed at the bottom of the bubble for threaded messages. + + + + ```dart + cometChatMessageTemplate.threadView = (BaseMessage baseMessage, BuildContext buildContext, BubbleAlignment alignment) { + return const Placeholder(); + }; + ``` + + + + + +11. **Reply Widget** + + The `replyView` property allows you to assign a custom reply widget to the MessageBubble. This is displayed at the top of the bubble when replying to a message. + + + + ```dart + cometChatMessageTemplate.replyView = (BaseMessage baseMessage, BuildContext buildContext, BubbleAlignment alignment, {AdditionalConfigurations? additionalConfigurations}) { + return const Placeholder(); + }; + ``` + + + + + ## Customization Let's dive into how you can use the [properties](#properties) of MessageTemplate to customize an existing template or add a new one to the [MessageList](/ui-kit/flutter/message-list) Widget. diff --git a/ui-kit/flutter/shortcut-formatter-guide.mdx b/ui-kit/flutter/shortcut-formatter-guide.mdx index efa1b70c7..cae25ad9e 100644 --- a/ui-kit/flutter/shortcut-formatter-guide.mdx +++ b/ui-kit/flutter/shortcut-formatter-guide.mdx @@ -189,6 +189,55 @@ void onScrollToBottom(TextEditingController textEditingController) { +6. **Additional Base Class Methods**: The `CometChatTextFormatter` base class provides additional methods you can override for advanced customization: + + + +```dart +/// Override to customize the text style in message bubbles +@override +TextStyle getMessageBubbleTextStyle(BuildContext context, BubbleAlignment? alignment, {bool forConversation = false}) { + return TextStyle( + color: alignment == BubbleAlignment.right ? Colors.white : Colors.black, + fontSize: 14, + fontWeight: FontWeight.bold, + ); +} + +/// Override to build custom attributed text for the input field +@override +List buildInputFieldText({ + required BuildContext context, + TextStyle? style, + required bool withComposing, + required String text, + List? existingAttributes, +}) { + return existingAttributes ?? []; +} + +/// Override to get attributed text for styling in message bubbles +@override +List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, { + List? existingAttributes, + Function(String)? onTap, + bool forConversation = false, +}) { + // Custom implementation + return super.getAttributedText(text, context, alignment, + existingAttributes: existingAttributes, + onTap: onTap, + forConversation: forConversation); +} +``` + + + + + *** ## Usage From 0059870001fc82c4a893feac715c31bd4a14a409 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 17:16:23 +0530 Subject: [PATCH 024/106] fixes discrepancies --- docs.json | 25 +- .../flutter/custom-text-formatter-guide.mdx | 398 ++++++++++++++++++ ui-kit/flutter/getting-started.mdx | 10 +- ui-kit/flutter/guide-overview.mdx | 19 +- ui-kit/flutter/guide-search-messages.mdx | 222 ++++++++++ ui-kit/flutter/overview.mdx | 2 +- ui-kit/flutter/troubleshooting.mdx | 211 ++++++++++ ui-kit/flutter/url-formatter-guide.mdx | 300 +++++++++++++ 8 files changed, 1167 insertions(+), 20 deletions(-) create mode 100644 ui-kit/flutter/custom-text-formatter-guide.mdx create mode 100644 ui-kit/flutter/guide-search-messages.mdx create mode 100644 ui-kit/flutter/troubleshooting.mdx create mode 100644 ui-kit/flutter/url-formatter-guide.mdx diff --git a/docs.json b/docs.json index 6fe2a0c07..f12ad9f4f 100644 --- a/docs.json +++ b/docs.json @@ -1861,11 +1861,11 @@ "group": "Chat", "pages": [ "ui-kit/flutter/core-features", - "ui-kit/flutter/extensions" + "ui-kit/flutter/extensions", + "ui-kit/flutter/ai-features" ] }, - "ui-kit/flutter/call-features", - "ui-kit/flutter/ai-features" + "ui-kit/flutter/call-features" ] }, { @@ -1890,6 +1890,7 @@ "ui-kit/flutter/message-header", "ui-kit/flutter/message-list", "ui-kit/flutter/message-composer", + "ui-kit/flutter/message-template", "ui-kit/flutter/threaded-messages-header", "ui-kit/flutter/incoming-call", "ui-kit/flutter/outgoing-call", @@ -1906,14 +1907,6 @@ "ui-kit/flutter/events" ] }, - { - "group": "Advanced", - "pages": [ - "ui-kit/flutter/message-template", - "ui-kit/flutter/mentions-formatter-guide", - "ui-kit/flutter/shortcut-formatter-guide" - ] - }, { "group": "Guides", "pages": [ @@ -1922,9 +1915,14 @@ "ui-kit/flutter/guide-block-unblock-user", "ui-kit/flutter/guide-new-chat", "ui-kit/flutter/guide-message-privately", + "ui-kit/flutter/guide-search-messages", "ui-kit/flutter/guide-call-log-details", "ui-kit/flutter/guide-group-chat", - "ui-kit/flutter/guide-message-agentic-flow" + "ui-kit/flutter/guide-message-agentic-flow", + "ui-kit/flutter/custom-text-formatter-guide", + "ui-kit/flutter/mentions-formatter-guide", + "ui-kit/flutter/url-formatter-guide", + "ui-kit/flutter/shortcut-formatter-guide" ] }, { @@ -1935,7 +1933,8 @@ ] }, "ui-kit/flutter/link/sample", - "ui-kit/flutter/link/changelog" + "ui-kit/flutter/link/changelog", + "ui-kit/flutter/troubleshooting" ] } ] diff --git a/ui-kit/flutter/custom-text-formatter-guide.mdx b/ui-kit/flutter/custom-text-formatter-guide.mdx new file mode 100644 index 000000000..ce0274947 --- /dev/null +++ b/ui-kit/flutter/custom-text-formatter-guide.mdx @@ -0,0 +1,398 @@ +--- +title: "Custom Text Formatter" +description: "Extend the CometChatTextFormatter base class to implement custom inline text patterns with regex and callbacks in Flutter." +--- + + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key class | `CometChatTextFormatter` (abstract base class for custom formatters) | +| Required setup | `CometChatUIKit.init(uiKitSettings: uiKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Extend to create custom inline text patterns with regex, styling, and callbacks | +| Features | Text formatting, customizable styles, dynamic text replacement, input field integration | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [ShortCut Formatter](/ui-kit/flutter/shortcut-formatter-guide) \| [Mentions Formatter](/ui-kit/flutter/mentions-formatter-guide) \| [All Guides](/ui-kit/flutter/guide-overview) | + + + +`CometChatTextFormatter` is an abstract class for formatting text in the message composer and message bubbles. Extend it to build custom formatters — hashtags, keywords, or any regex-based pattern. + +| Capability | Description | +| --- | --- | +| Text formatting | Auto-format text based on regex patterns and styles | +| Custom styles | Set colors, fonts, and backgrounds for matched text | +| Dynamic replacement | Regex-based find-and-replace in user input | +| Input integration | Real-time monitoring of the composer input field | +| Attributed text | Build styled text spans for message bubbles | + +--- + +## Steps + +### 1. Import the base class + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +``` + +### 2. Extend CometChatTextFormatter + +```dart +class HashTagTextFormatter extends CometChatTextFormatter { + HashTagTextFormatter() : super( + trackingCharacter: '#', + pattern: RegExp(r'\B#(\w+)\b'), + ); + + // Override required methods... +} +``` + +### 3. Configure tracking character and regex + +Set the character that triggers formatting and the regex to match. + +```dart +HashTagTextFormatter() : super( + trackingCharacter: '#', + pattern: RegExp(r'\B#(\w+)\b'), + showLoadingIndicator: false, +); +``` + +### 4. Implement required methods + +```dart +@override +void init() { + // Initialize formatter +} + +@override +void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) { + // Process message before sending +} + +@override +TextStyle getMessageInputTextStyle(BuildContext context) { + return TextStyle(color: Colors.blue); +} + +@override +void onScrollToBottom(TextEditingController textEditingController) { + // Handle scroll events +} + +@override +void onChange(TextEditingController textEditingController, String previousText) { + // Handle text changes +} +``` + +### 5. Customize message bubble styling + +```dart +@override +TextStyle getMessageBubbleTextStyle( + BuildContext context, + BubbleAlignment? alignment, + {bool forConversation = false} +) { + return TextStyle( + color: alignment == BubbleAlignment.right + ? Colors.white + : Colors.blue, + fontWeight: FontWeight.bold, + decoration: TextDecoration.underline, + ); +} +``` + +--- + +## Example + +A hashtag formatter used with [CometChatMessageList](/ui-kit/flutter/message-list) and [CometChatMessageComposer](/ui-kit/flutter/message-composer). + + + + + + + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class HashTagTextFormatter extends CometChatTextFormatter { + HashTagTextFormatter() : super( + trackingCharacter: '#', + pattern: RegExp(r'\B#(\w+)\b'), + showLoadingIndicator: false, + ); + + @override + void init() { + // Initialization logic + } + + @override + void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) { + // Process hashtags before sending + } + + @override + TextStyle getMessageInputTextStyle(BuildContext context) { + CometChatColorPalette colorPalette = CometChatThemeHelper.getColorPalette(context); + return TextStyle( + color: colorPalette.primary, + fontWeight: FontWeight.w500, + ); + } + + @override + TextStyle getMessageBubbleTextStyle( + BuildContext context, + BubbleAlignment? alignment, + {bool forConversation = false} + ) { + CometChatColorPalette colorPalette = CometChatThemeHelper.getColorPalette(context); + return TextStyle( + color: alignment == BubbleAlignment.right + ? colorPalette.white + : colorPalette.primary, + fontWeight: FontWeight.bold, + decoration: TextDecoration.underline, + ); + } + + @override + void onScrollToBottom(TextEditingController textEditingController) { + // Handle scroll to bottom + } + + @override + void onChange(TextEditingController textEditingController, String previousText) { + // Handle text changes - detect new hashtags + String currentText = textEditingController.text; + if (currentText.contains('#')) { + // Process hashtag + } + } + + @override + List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, + {List? existingAttributes, + Function(String)? onTap, + bool forConversation = false} + ) { + return super.getAttributedText( + text, + context, + alignment, + existingAttributes: existingAttributes, + onTap: onTap ?? (hashtag) { + // Handle hashtag tap - e.g., search for hashtag + print('Tapped hashtag: $hashtag'); + }, + forConversation: forConversation, + ); + } +} +``` + + + + + +Pass the formatter via the `textFormatters` property. + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class MessageListDemo extends StatefulWidget { + const MessageListDemo({super.key}); + + @override + State createState() => _MessageListDemoState(); +} + +class _MessageListDemoState extends State { + User? chatUser; + + @override + void initState() { + super.initState(); + CometChat.getUser("uid").then((user) { + setState(() { + chatUser = user; + }); + }); + } + + @override + Widget build(BuildContext context) { + if (chatUser == null) { + return const Center(child: CircularProgressIndicator()); + } + + return CometChatMessageList( + user: chatUser, + textFormatters: [HashTagTextFormatter()], + ); + } +} +``` + + + + +--- + +## Methods Reference + +| Field | Description | +| --- | --- | +| `trackingCharacter` | Character that starts tracking (e.g. `#` for hashtags) | +| `pattern` | Regex pattern to match text for formatting | +| `showLoadingIndicator` | Whether to show loading indicator during search | +| `messageBubbleTextStyle` | Function to style message bubble text | +| `messageInputTextStyle` | Function to style composer input text | +| `message` | Current message being processed | +| `user` | User context for the formatter | +| `group` | Group context for the formatter | + +--- + +## Override Methods + + + + +Initialize the formatter. Called when the formatter is first used. + +```dart +@override +void init() { + // Setup any initial state +} +``` + + + + + +Process the message before it's sent. Use this to modify message metadata. + +```dart +@override +void handlePreMessageSend(BuildContext context, BaseMessage baseMessage) { + // Add hashtag metadata to message + if (baseMessage is TextMessage) { + final hashtags = pattern?.allMatches(baseMessage.text) + .map((m) => m.group(1)) + .toList(); + // Store hashtags in message metadata + } +} +``` + + + + + +Returns the TextStyle for formatted text in message bubbles. + +```dart +@override +TextStyle getMessageBubbleTextStyle( + BuildContext context, + BubbleAlignment? alignment, + {bool forConversation = false} +) { + return TextStyle( + color: Colors.blue, + fontWeight: FontWeight.bold, + ); +} +``` + + + + + +Returns styled text spans for the message bubble. + +```dart +@override +List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, + {List? existingAttributes, + Function(String)? onTap, + bool forConversation = false} +) { + // Return attributed text with styling + return super.getAttributedText( + text, context, alignment, + existingAttributes: existingAttributes, + onTap: onTap, + forConversation: forConversation, + ); +} +``` + + + + + +Called when text changes in the composer. + +```dart +@override +void onChange(TextEditingController textEditingController, String previousText) { + // Detect and process new patterns +} +``` + + + + +--- + +## Built-in Formatters + +Flutter UI Kit includes these pre-built formatters: + +| Formatter | Description | +| --- | --- | +| `CometChatMentionsFormatter` | @mentions with user suggestions | +| `CometChatUrlFormatter` | Auto-detect and style URLs | +| `CometChatEmailFormatter` | Auto-detect and style email addresses | +| `CometChatPhoneNumberFormatter` | Auto-detect and style phone numbers | + +--- + +## Next Steps + + + + Add @mentions with styled tokens. + + + Customize the message input component. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/flutter/getting-started.mdx b/ui-kit/flutter/getting-started.mdx index 1b53fde4e..ac00ff131 100644 --- a/ui-kit/flutter/getting-started.mdx +++ b/ui-kit/flutter/getting-started.mdx @@ -107,7 +107,7 @@ Ensure your system meets the following **prerequisites** before proceeding with * **Flutter** installed on your system (Flutter 3.0 or higher recommended) * **Android Studio** or **VS Code** with configured Flutter/Dart plugins * **Xcode & CocoaPods** for iOS development -* An **iOS device or simulator** with iOS 12.0 or above +* An **iOS device or simulator** with iOS 13.0 or above * An **Android device or emulator** with Android version 5.0 (API level 21) or above *** @@ -136,7 +136,7 @@ dependencies: flutter: sdk: flutter - cometchat_chat_uikit: ^5.2.8 + cometchat_chat_uikit: ^5.2.10 cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling ``` @@ -151,13 +151,13 @@ publish_to: 'none' version: 1.0.0+1 environment: - sdk: ^3.5.3 + sdk: '>=3.8.0 <4.0.0' dependencies: flutter: sdk: flutter - cometchat_chat_uikit: ^5.2.8 + cometchat_chat_uikit: ^5.2.10 cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling cupertino_icons: ^1.0.8 @@ -201,7 +201,7 @@ android { In your Podfile (located at `ios/Podfile`), update the minimum iOS version your project supports to 12.0: ```ruby Podfile -platform :ios, '12.0' +platform :ios, '13.0' ``` After updating, run: diff --git a/ui-kit/flutter/guide-overview.mdx b/ui-kit/flutter/guide-overview.mdx index 896324117..0cecb9a9c 100644 --- a/ui-kit/flutter/guide-overview.mdx +++ b/ui-kit/flutter/guide-overview.mdx @@ -15,10 +15,17 @@ Available implementation guides for Flutter UI Kit: - [Block/Unblock User](/ui-kit/flutter/guide-block-unblock-user) → `CometChatUIKit.blockUsers()` - [New Chat](/ui-kit/flutter/guide-new-chat) → `CometChatContacts` - [Message Privately](/ui-kit/flutter/guide-message-privately) → `CometChatUserInfo` +- [Search Messages](/ui-kit/flutter/guide-search-messages) → `CometChatSearch` - [Group Management](/ui-kit/flutter/guide-group-chat) → `CometChatGroups` - [Call Log Details](/ui-kit/flutter/guide-call-log-details) → `CometChatCallLogs` - [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) → `CometChatAIAssistantChatHistory` +**Formatter Guides:** +- [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) → `CometChatTextFormatter` +- [Mentions Formatter](/ui-kit/flutter/mentions-formatter-guide) → `CometChatMentionsFormatter` +- [URL Formatter](/ui-kit/flutter/url-formatter-guide) → `CometChatUrlFormatter` +- [Shortcut Formatter](/ui-kit/flutter/shortcut-formatter-guide) → `ShortcutFormatter` + **Sample App:** [GitHub Repository](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) Each guide provides end-to-end implementation with code examples and component references. @@ -30,7 +37,7 @@ This page indexes focused, task‑oriented feature guides for the Flutter UI Kit Use these after finishing [Getting Started](/ui-kit/flutter/getting-started) and wiring a basic conversations/messages experience. Add them incrementally to deepen functionality without rebuilding fundamentals. -## Guide Directory +## Feature Guides | Guide | Description | |:------|:------------| @@ -39,9 +46,19 @@ Use these after finishing [Getting Started](/ui-kit/flutter/getting-started) and | [Group Management](/ui-kit/flutter/guide-group-chat) | Create/join groups, view members, add / remove users, manage roles, and moderate participation. | | [Message Privately](/ui-kit/flutter/guide-message-privately) | Start a direct 1:1 chat from a profile or list; optionally send an initial message to surface the conversation. | | [New Chat](/ui-kit/flutter/guide-new-chat) | Offer a unified discovery screen for users & groups and launch new chats quickly. | +| [Search Messages](/ui-kit/flutter/guide-search-messages) | Full-text message search across conversations with result routing and navigation. | | [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) | Enable threaded replies: open parent message context, browse replies, and compose within a focused thread. | | [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) | Integrate AI agents with chat history, contextual responses, and seamless handoffs. | +## Formatter Guides + +| Guide | Description | +|:------|:------------| +| [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) | Build custom inline text patterns with regex, styling, and callbacks. | +| [Mentions Formatter](/ui-kit/flutter/mentions-formatter-guide) | Add @mentions with user suggestions and styled tokens. | +| [URL Formatter](/ui-kit/flutter/url-formatter-guide) | Auto-detect and style URLs as clickable links. | +| [Shortcut Formatter](/ui-kit/flutter/shortcut-formatter-guide) | Create keyboard shortcuts for quick text insertion. | + Need another guide? Request one via the [Developer Community](http://community.cometchat.com/) or Support. --- diff --git a/ui-kit/flutter/guide-search-messages.mdx b/ui-kit/flutter/guide-search-messages.mdx new file mode 100644 index 000000000..bdf9382aa --- /dev/null +++ b/ui-kit/flutter/guide-search-messages.mdx @@ -0,0 +1,222 @@ +--- +title: "Search Messages" +sidebarTitle: "Search Messages" +description: "Add full-text message search across conversations with result routing in CometChat Flutter UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatSearch`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader` | +| Init | `CometChatUIKit.init(uiKitSettings: uiKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Full-text message search across conversations with result routing and navigation | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | + + + +Search Messages lets users locate specific messages across conversations and groups using keyword search, then navigate directly to the result. + +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. + +--- + +## Components + +| Component / Class | Role | +|:---|:---| +| `CometChatSearch` | Main container for searching messages and conversations | +| `CometChatMessageList` | Displays messages and supports scrolling to specific messages | +| `CometChatMessageComposer` | Supports navigation after selecting a search result | +| `CometChatMessageHeader` | Displays search context and navigation controls | + +--- + +## Integration Steps + +### 1. Launch Search Component + +Launch the `CometChatSearch` widget directly using Navigator or embed it in your widget tree. + +```dart +Navigator.push( + context, + MaterialPageRoute(builder: (context) => CometChatSearch()) +); +``` + +--- + +### 2. Handle Search Result Clicks + +Wire up the `onMessageClicked` callback to navigate to the message in context. + +```dart +CometChatSearch( + onMessageClicked: (message) { + // Navigate to the conversation containing this message + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + user: message.sender, // or group for group messages + ), + ), + ); + }, + onConversationClicked: (conversation) { + // Navigate to the selected conversation + if (conversation.conversationWith is User) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + user: conversation.conversationWith as User, + ), + ), + ); + } else if (conversation.conversationWith is Group) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + group: conversation.conversationWith as Group, + ), + ), + ); + } + }, +); +``` + +--- + +### 3. Filter Search Results + +Use request builders to customize what gets searched. + +```dart +CometChatSearch( + // Filter conversations + conversationsRequestBuilder: ConversationsRequestBuilder() + ..limit = 30, + // Filter messages + messagesRequestBuilder: MessagesRequestBuilder() + ..limit = 50 + ..searchKeyword = "hello", +); +``` + +--- + +### 4. Customize Search Appearance + +Apply custom styling to match your app's design. + +```dart +CometChatSearch( + searchStyle: CometChatSearchStyle( + backgroundColor: Colors.white, + searchTextStyle: TextStyle(fontSize: 16), + searchFilterChipTextStyle: TextStyle(color: Colors.blue), + searchMessageItemBackgroundColor: Color(0xFFF5F5F5), + ), +); +``` + +--- + +## Feature Matrix + +| Feature | Component / Method | Description | +|:---|:---|:---| +| Search input | `CometChatSearch` | Main search interface | +| Display results | `CometChatSearch` | Shows matching conversations and messages | +| Conversation click | `onConversationClicked` | Handle conversation selection | +| Message click | `onMessageClicked` | Handle message selection | +| Filter conversations | `conversationsRequestBuilder` | Customize conversation search | +| Filter messages | `messagesRequestBuilder` | Customize message search | + +--- + +## Complete Example + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class SearchScreen extends StatelessWidget { + const SearchScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('Search')), + body: CometChatSearch( + onConversationClicked: (conversation) { + _navigateToConversation(context, conversation); + }, + onMessageClicked: (message) { + _navigateToMessage(context, message); + }, + onBack: () { + Navigator.pop(context); + }, + onError: (error) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: ${error.message}')), + ); + }, + ), + ); + } + + void _navigateToConversation(BuildContext context, Conversation conversation) { + if (conversation.conversationWith is User) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + user: conversation.conversationWith as User, + ), + ), + ); + } else if (conversation.conversationWith is Group) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatMessageList( + group: conversation.conversationWith as Group, + ), + ), + ); + } + } + + void _navigateToMessage(BuildContext context, BaseMessage message) { + // Navigate to the message's conversation + // Implementation depends on your app's navigation structure + } +} +``` + +--- + +## Next Steps + + + + Full search component reference. + + + Render real-time message threads. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index ea11a9337..84839787b 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -155,7 +155,7 @@ This layered approach means: The Flutter UI Kit works seamlessly across: -* **iOS** – iPhone and iPad (iOS 12.0+) +* **iOS** – iPhone and iPad (iOS 13.0+) * **Android** – Phones and tablets (API level 21+) *** diff --git a/ui-kit/flutter/troubleshooting.mdx b/ui-kit/flutter/troubleshooting.mdx new file mode 100644 index 000000000..afde830f4 --- /dev/null +++ b/ui-kit/flutter/troubleshooting.mdx @@ -0,0 +1,211 @@ +--- +title: "Troubleshooting" +description: "Common failure modes and fixes for the CometChat Flutter UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Page type | Troubleshooting reference | +| Scope | All CometChat Flutter UI Kit v5 issues — initialization, rendering, theming, calling, extensions, AI features, localization, sound, events | +| When to reference | When a component fails to render, data is missing, styling doesn't apply, or a feature doesn't appear | + + + +## Initialization and Login + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `CometChatUIKit.init()` fails silently | Invalid App ID, Region, or Auth Key | Double-check credentials from the [CometChat Dashboard](https://app.cometchat.com/) | +| Widget doesn't render | `init()` not called or not awaited before rendering | Ensure `init()` completes before mounting widgets. See [Methods](/ui-kit/flutter/methods) | +| Widget renders but shows no data | User not logged in | Call `CometChatUIKit.login("UID")` after init | +| Login fails with "UID not found" | UID doesn't exist in your CometChat app | Create the user via Dashboard, SDK, or API first | +| Blank screen after login | Widget mounted before init/login completes | Use `FutureBuilder` or state to conditionally render after login resolves | +| `getLoggedInUser()` returns null | User not logged in or session expired | Call `login()` or `loginWithAuthToken()` first | +| `sendTextMessage()` fails | User not logged in or invalid receiver | Ensure login completes before sending messages | +| Auth Key exposed in production | Using Auth Key instead of Auth Token | Switch to [Auth Token](/ui-kit/flutter/methods#login-using-auth-token) for production | + +--- + +## Platform-Specific Issues + +### Android + +| Symptom | Cause | Fix | +| --- | --- | --- | +| App crashes on launch | Missing internet permission | Add `` to `AndroidManifest.xml` | +| Network requests fail | Missing network security config | For debug builds, add `android:usesCleartextTraffic="true"` to `AndroidManifest.xml` | +| Camera/microphone not working | Missing permissions | Add camera and microphone permissions to `AndroidManifest.xml` | +| Build fails with minSdk error | minSdkVersion too low | Set `minSdkVersion 21` or higher in `build.gradle` | +| ProGuard issues in release build | Missing ProGuard rules | Add CometChat ProGuard rules to `proguard-rules.pro` | + +### iOS + +| Symptom | Cause | Fix | +| --- | --- | --- | +| App crashes on camera/mic access | Missing Info.plist entries | Add `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` to `Info.plist` | +| Build fails with deployment target error | iOS version too low | Set `platform :ios, '13.0'` or higher in `Podfile` | +| Pod install fails | CocoaPods cache issue | Run `pod cache clean --all` then `pod install` | +| Bitcode error | Bitcode enabled | Disable bitcode in Xcode build settings | +| Simulator crashes | Architecture mismatch | Ensure you're using the correct simulator architecture | + +--- + +## Theming and Styling + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Theme not applied | Theme not passed to widget | Wrap your app with `CometChatTheme` or pass theme to individual widgets | +| Colors not changing | Using wrong color palette | Use `CometChatThemeHelper.getColorPalette(context)` to access theme colors | +| Typography not applied | Font family not set | Set font family in `CometChatTypography` | +| Dark mode not working | Theme mode not set | Use `ThemeMode.dark` and ensure `CometChatColorPalette` has dark mode colors | +| Custom style not applying | Style property not set correctly | Check the component's style class (e.g., `CometChatConversationsStyle`) | +| Spacing issues | Using wrong spacing values | Use `CometChatSpacing` for consistent spacing | + +--- + +## Components + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Callback not firing | Wrong callback name or signature | Check the Actions section on the component page for exact callback name and parameters | +| Custom view not appearing | Returning `null` from view builder | Ensure view builder returns a valid Widget | +| Messages not loading | Invalid user/group object passed | Ensure you fetch the user/group via SDK before passing to components | +| List not refreshing | State not updated | Call `setState()` or use a state management solution | +| Scroll position lost | Key not set on list items | Ensure unique keys are set on list items | +| Empty state not showing | `emptyStateView` not set | Provide an `emptyStateView` builder | + +--- + +## Calling + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Call buttons not appearing | Calling extension not installed | Add `cometchat_calls_uikit` to your `pubspec.yaml` | +| Incoming call screen not showing | `CometChatIncomingCall` not in widget tree | Add `CometChatIncomingCall` at the app root level | +| Call fails to connect | WebRTC permissions not granted | Ensure camera and microphone permissions are granted | +| Audio not working in call | Audio session not configured | Configure audio session for iOS in `AppDelegate.swift` | +| Video not showing | Camera permission denied | Request camera permission before starting video call | +| Call drops immediately | Network connectivity issue | Check internet connection and firewall settings | + +--- + +## Extensions + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Extension feature not appearing | Extension not activated in Dashboard | Enable the specific extension from your [Dashboard](/fundamentals/extensions-overview) | +| Stickers not showing in composer | Sticker extension not enabled | Activate [Sticker Extension](/fundamentals/stickers) in Dashboard | +| Polls option missing | Polls extension not enabled | Activate [Polls Extension](/fundamentals/polls) in Dashboard | +| Link preview not rendering | Link Preview extension not enabled | Activate [Link Preview Extension](/fundamentals/link-preview) in Dashboard | +| Reactions not working | Reactions extension not enabled | Activate [Reactions Extension](/fundamentals/reactions) in Dashboard | + +--- + +## AI Features + +| Symptom | Cause | Fix | +| --- | --- | --- | +| AI features not appearing | Feature not activated in Dashboard | Enable the specific AI feature from your [Dashboard](/fundamentals/ai-user-copilot/overview) | +| Conversation Starter not showing | Feature not enabled or no conversation context | Ensure [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter) is activated | +| Smart Replies not appearing | Feature not enabled in Dashboard | Ensure [Smart Replies](/fundamentals/ai-user-copilot/smart-replies) is activated | +| AI extension not in UIKitSettings | AI features not configured | Add AI extensions to `UIKitSettings.aiFeature` list | + +```dart +UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..aiFeature = [ + AISmartRepliesExtension(), + AIConversationStarterExtension(), + AIConversationSummaryExtension(), + ] +).build(); +``` + +--- + +## Localization + +| Symptom | Cause | Fix | +| --- | --- | --- | +| UI text not translated | Language code not matching | Check supported languages in [Localize](/ui-kit/flutter/localize) | +| Custom translations not appearing | Translations not added correctly | Use `Translations` class to add custom translations | +| Date/time format unchanged | Locale not set | Set locale in `MaterialApp` or use `dateTimeFormatterCallback` | +| RTL layout not working | Text direction not set | Set `textDirection: TextDirection.rtl` for RTL languages | + +--- + +## Sound + +| Symptom | Cause | Fix | +| --- | --- | --- | +| No sound plays | Sound disabled or volume muted | Check `CometChatSoundManager` settings and device volume | +| Custom sound not playing | Invalid file path or format | Ensure the path is correct and file is WAV/MP3 format | +| Sound plays multiple times | Multiple listeners registered | Ensure you're not registering duplicate sound listeners | +| Sound continues after app backgrounded | Sound not stopped | Call `CometChatSoundManager.stop()` when appropriate | + +--- + +## Events + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Event listener not firing | Subscribed to wrong event | Check the [Events](/ui-kit/flutter/events) page for exact event names | +| Duplicate event triggers | Multiple subscriptions | Remove listener in `dispose()` method | +| Event fires but UI doesn't update | State not updated in handler | Call `setState()` in the event handler | +| Memory leak from events | Listener not removed | Always remove listeners in `dispose()` | + +```dart +@override +void dispose() { + CometChatMessageEvents.removeMessagesListener("listenerId"); + super.dispose(); +} +``` + +--- + +## Build and Dependencies + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Dependency conflict | Version mismatch | Run `flutter pub upgrade` and check version constraints | +| Build fails with Dart version error | Dart SDK too old | Upgrade Flutter: `flutter upgrade` | +| iOS build fails | Pod dependencies outdated | Run `cd ios && pod update` | +| Android build fails with Gradle error | Gradle version mismatch | Update Gradle in `android/gradle/wrapper/gradle-wrapper.properties` | +| Package not found | Package not in pubspec.yaml | Add `cometchat_chat_uikit: ^5.x.x` to dependencies | + +--- + +## Performance + +| Symptom | Cause | Fix | +| --- | --- | --- | +| UI janky/laggy | Too many rebuilds | Use `const` constructors and optimize state management | +| Memory usage high | Images not cached | Enable image caching and limit message history | +| Slow message loading | Large message history | Use pagination with `MessagesRequestBuilder().limit` | +| App freezes on large groups | Too many members loaded | Use pagination for group members | + +--- + +## Common Error Messages + +| Error | Cause | Fix | +| --- | --- | --- | +| `ERR_APP_NOT_FOUND` | Invalid App ID | Check App ID in Dashboard | +| `ERR_AUTH_TOKEN_NOT_FOUND` | Invalid or expired auth token | Generate new auth token | +| `ERR_UID_NOT_FOUND` | User doesn't exist | Create user first via Dashboard or API | +| `ERR_GROUP_NOT_FOUND` | Group doesn't exist | Create group first | +| `ERR_NOT_LOGGED_IN` | User not authenticated | Call `login()` before using SDK | +| `ERR_WEBSOCKET_CONNECTION_FAILED` | Network issue | Check internet connection | + +--- + +## Getting Help + +If you're still experiencing issues: + +1. Check the [CometChat Documentation](https://www.cometchat.com/docs) +2. Search the [GitHub Issues](https://github.com/cometchat/cometchat-uikit-flutter/issues) +3. Contact [CometChat Support](https://www.cometchat.com/support) +4. Join the [CometChat Community](https://community.cometchat.com) diff --git a/ui-kit/flutter/url-formatter-guide.mdx b/ui-kit/flutter/url-formatter-guide.mdx new file mode 100644 index 000000000..6627d0be0 --- /dev/null +++ b/ui-kit/flutter/url-formatter-guide.mdx @@ -0,0 +1,300 @@ +--- +title: "URL Formatter" +description: "Detect and style plain URLs as clickable links with optional tracking logic in CometChat Flutter UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key class | `CometChatUrlFormatter` (extends `CometChatTextFormatter`) | +| Required setup | `CometChatUIKit.init(uiKitSettings: uiKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Auto-detects URLs in text messages and converts them to clickable links | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) \| [All Guides](/ui-kit/flutter/guide-overview) | + + + +`CometChatUrlFormatter` extends [CometChatTextFormatter](/ui-kit/flutter/custom-text-formatter-guide) to detect URLs in text messages and render them as clickable links. + + + + + +--- + +## Overview + +The URL formatter is included by default in the Flutter UI Kit. It automatically: +- Detects URLs in message text using regex patterns +- Styles URLs with underline and link color +- Opens URLs in the browser when tapped + +--- + +## Default Behavior + +The `CometChatUrlFormatter` is automatically applied to messages. URLs are: +- Styled with underline decoration +- Colored based on bubble alignment (white for outgoing, info color for incoming) +- Clickable - tapping opens the URL in the default browser + +--- + +## Usage + +### Basic Usage (Default) + +The URL formatter is included by default. No additional setup required. + +```dart +CometChatMessageList( + user: chatUser, + // URL formatter is automatically included +) +``` + +### Custom URL Formatter + +Create a custom URL formatter with your own styling and behavior. + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class CustomUrlFormatter extends CometChatUrlFormatter { + CustomUrlFormatter() : super( + pattern: RegExp(r'(https?:\/\/[^\s]+)'), + messageBubbleTextStyle: (context, alignment, {forConversation}) { + return TextStyle( + color: Colors.blue, + decoration: TextDecoration.underline, + decorationColor: Colors.blue, + ); + }, + ); + + @override + List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, + {List? existingAttributes, + Function(String)? onTap, + bool forConversation = false} + ) { + return super.getAttributedText( + text, context, alignment, + existingAttributes: existingAttributes, + onTap: onTap ?? (url) async { + // Custom URL handling + _trackUrlClick(url); + await _openUrl(url); + }, + forConversation: forConversation, + ); + } + + void _trackUrlClick(String url) { + // Add analytics tracking + print('URL clicked: $url'); + } + + Future _openUrl(String url) async { + if (!url.startsWith('http://') && !url.startsWith('https://')) { + url = 'https://$url'; + } + final uri = Uri.parse(url); + if (await canLaunchUrl(uri)) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + } + } +} +``` + +### Apply Custom Formatter + +```dart +CometChatMessageList( + user: chatUser, + textFormatters: [ + CustomUrlFormatter(), + CometChatMentionsFormatter(), // Keep other formatters + ], +) +``` + +--- + +## Customization + +### Styling Links + +Override `getMessageBubbleTextStyle` to customize link appearance: + +```dart +@override +TextStyle getMessageBubbleTextStyle( + BuildContext context, + BubbleAlignment? alignment, + {bool forConversation = false} +) { + CometChatColorPalette colorPalette = CometChatThemeHelper.getColorPalette(context); + + return TextStyle( + color: alignment == BubbleAlignment.right + ? colorPalette.white + : colorPalette.info, + fontWeight: FontWeight.w500, + decoration: TextDecoration.underline, + decorationColor: alignment == BubbleAlignment.right + ? colorPalette.white + : colorPalette.info, + ); +} +``` + +### Custom URL Pattern + +Use a custom regex pattern to match specific URL formats: + +```dart +CometChatUrlFormatter( + pattern: RegExp( + r'(https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*))' + ), +) +``` + +### Handle URL Clicks + +Override `getAttributedText` to add custom click handling: + +```dart +@override +List getAttributedText( + String text, + BuildContext context, + BubbleAlignment? alignment, + {List? existingAttributes, + Function(String)? onTap, + bool forConversation = false} +) { + return super.getAttributedText( + text, context, alignment, + existingAttributes: existingAttributes, + onTap: (url) async { + // Show confirmation dialog before opening + final shouldOpen = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text('Open Link'), + content: Text('Open $url?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: Text('Cancel'), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + child: Text('Open'), + ), + ], + ), + ); + + if (shouldOpen == true) { + await launchUrl(Uri.parse(url)); + } + }, + forConversation: forConversation, + ); +} +``` + +--- + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| `pattern` | `RegExp?` | Regex pattern to match URLs | +| `messageBubbleTextStyle` | `Function?` | Custom style for URL text in bubbles | +| `onSearch` | `Function?` | Callback when URL is detected | +| `showLoadingIndicator` | `bool?` | Show loading indicator during processing | + +--- + +## Complete Example + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class UrlFormatterExample extends StatefulWidget { + const UrlFormatterExample({super.key}); + + @override + State createState() => _UrlFormatterExampleState(); +} + +class _UrlFormatterExampleState extends State { + User? chatUser; + + @override + void initState() { + super.initState(); + CometChat.getUser("uid").then((user) { + setState(() => chatUser = user); + }); + } + + @override + Widget build(BuildContext context) { + if (chatUser == null) { + return const Center(child: CircularProgressIndicator()); + } + + return Scaffold( + body: CometChatMessageList( + user: chatUser, + textFormatters: [ + CometChatUrlFormatter( + messageBubbleTextStyle: (context, alignment, {forConversation}) { + return TextStyle( + color: alignment == BubbleAlignment.right + ? Colors.white + : Colors.blue, + decoration: TextDecoration.underline, + ); + }, + ), + CometChatMentionsFormatter(), + ], + ), + ); + } +} +``` + +--- + +## Next Steps + + + + Build custom inline text patterns. + + + Render real-time message threads. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + From a013171ca62c7521332f163caeaef42dc342464d Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 17:27:52 +0530 Subject: [PATCH 025/106] Create .mintignore --- .mintignore | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .mintignore diff --git a/.mintignore b/.mintignore new file mode 100644 index 000000000..a2bfd86bc --- /dev/null +++ b/.mintignore @@ -0,0 +1,2 @@ +.kiro/ +/codebase \ No newline at end of file From ec9577a17ae0e9786948e5e08ec2445b2d055195 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 17:31:53 +0530 Subject: [PATCH 026/106] Update conversations.mdx --- ui-kit/flutter/conversations.mdx | 2377 +++++++++++++++++------------- 1 file changed, 1351 insertions(+), 1026 deletions(-) diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index adaac93ab..239fda8b6 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -1,54 +1,219 @@ --- title: "Conversations" +description: "Scrollable list of recent one-on-one and group conversations for the logged-in user." --- -## Overview + +```json +{ + "component": "CometChatConversations", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Scrollable list of recent one-on-one and group conversations for the logged-in user.", + "primaryOutput": { + "prop": "onItemTap", + "type": "Function(Conversation conversation)" + }, + "props": { + "data": { + "conversationsRequestBuilder": { + "type": "ConversationsRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + } + }, + "callbacks": { + "onItemTap": "Function(Conversation conversation)", + "onItemLongPress": "Function(Conversation conversation)", + "onSelection": "Function(List? list)", + "onBack": "VoidCallback", + "onError": "OnError", + "onLoad": "OnLoad", + "onEmpty": "OnEmpty", + "onSearchTap": "GestureTapCallback" + }, + "visibility": { + "receiptsVisibility": { "type": "bool", "default": true }, + "usersStatusVisibility": { "type": "bool", "default": true }, + "groupTypeVisibility": { "type": "bool", "default": true }, + "deleteConversationOptionVisibility": { "type": "bool", "default": true }, + "hideAppbar": { "type": "bool", "default": false }, + "hideError": { "type": "bool", "default": false }, + "hideSearch": { "type": "bool", "default": false }, + "showBackButton": { "type": "bool", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "bool", "default": false }, + "customSoundForMessages": { "type": "String", "default": "built-in" } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], + "default": "null" + }, + "activateSelection": { + "type": "ActivateSelection", + "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], + "default": "null" + } + }, + "viewSlots": { + "listItemView": "Widget Function(Conversation conversation)", + "leadingView": "Widget? Function(BuildContext context, Conversation conversation)", + "titleView": "Widget? Function(BuildContext context, Conversation conversation)", + "subtitleView": "Widget? Function(BuildContext context, Conversation conversation)", + "trailingView": "Widget? Function(Conversation conversation)", + "loadingStateView": "WidgetBuilder", + "emptyStateView": "WidgetBuilder", + "errorStateView": "WidgetBuilder", + "setOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)", + "addOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)" + }, + "formatting": { + "textFormatters": { + "type": "List", + "default": "default formatters from data source" + } + } + }, + "events": [ + { + "name": "CometChatConversationEvents.ccConversationDeleted", + "payload": "Conversation", + "description": "Conversation deleted from list" + } + ], + "sdkListeners": [ + "onTextMessageReceived", + "onMediaMessageReceived", + "onCustomMessageReceived", + "onTypingStarted", + "onTypingEnded", + "onMessagesDelivered", + "onMessagesRead", + "onUserOnline", + "onUserOffline", + "onGroupMemberJoined", + "onGroupMemberLeft", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup" + ], + "compositionExample": { + "description": "Sidebar conversations wired to message view", + "components": [ + "CometChatConversations", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemTap emits Conversation -> extract User/Group via conversationWith -> pass to MessageHeader, MessageList, MessageComposer" + }, + "types": { + "CometChatOption": { + "id": "String?", + "title": "String?", + "icon": "String?", + "iconWidget": "Widget?", + "onClick": "VoidCallback?" + }, + "SelectionMode": { + "single": "SelectionMode.single", + "multiple": "SelectionMode.multiple", + "none": "SelectionMode.none" + } + } +} +``` + -The `CometChatConversations` is a [Widget](/ui-kit/flutter/components-overview#components), That shows all conversations related to the currently logged-in user, - - - +## Where It Fits -## Usage +`CometChatConversations` is a sidebar list widget. It renders recent conversations and emits the selected `Conversation` via `onItemTap`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a standard two-panel chat layout. -### Integration + + +```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -As `CometChatConversations` is a widget, it can be initiated either by tapping a button or through the trigger of any event. It offers multiple parameters and methods for tailoring its user interface. +class ChatApp extends StatefulWidget { + const ChatApp({super.key}); -You can launch `CometChatConversations` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. + @override + State createState() => _ChatAppState(); +} -##### 1. Using Navigator to Launch `CometChatConversations` +class _ChatAppState extends State { + User? selectedUser; + Group? selectedGroup; + + void handleItemTap(Conversation conversation) { + final entity = conversation.conversationWith; + setState(() { + if (entity is User) { + selectedUser = entity; + selectedGroup = null; + } else if (entity is Group) { + selectedGroup = entity; + selectedUser = null; + } + }); + } - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => const CometChatConversations())); + @override + Widget build(BuildContext context) { + return Scaffold( + body: Row( + children: [ + SizedBox( + width: 400, + child: CometChatConversations( + onItemTap: handleItemTap, + ), + ), + Expanded( + child: selectedUser != null || selectedGroup != null + ? CometChatMessages( + user: selectedUser, + group: selectedGroup, + ) + : const Center( + child: Text('Select a conversation'), + ), + ), + ], + ), + ); + } +} ``` - - -##### 2. Embedding `CometChatConversations` as a Widget in the build Method + + + + +--- + + +## Minimal Render ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class Conversations extends StatefulWidget { - const Conversations({super.key}); - - @override - State createState() => _ConversationsState(); -} +class ConversationsDemo extends StatelessWidget { + const ConversationsDemo({super.key}); -class _ConversationsState extends State { @override Widget build(BuildContext context) { - return Scaffold( + return const Scaffold( body: SafeArea( child: CometChatConversations(), ), @@ -56,206 +221,185 @@ class _ConversationsState extends State { } } ``` - - -### Actions + + + + +You can also launch it using `Navigator.push`: -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +```dart +Navigator.push( + context, + MaterialPageRoute(builder: (context) => const CometChatConversations()) +); +``` + +--- -##### onItemTap +## Filtering Conversations -`onItemTap` is triggered when you click on a ListItem of the `CometChatConversations` widget. This `onItemTap` method proves beneficial when a user intends to customize the click behavior in CometChatConversations. +Pass a `ConversationsRequestBuilder` to `conversationsRequestBuilder`. Pass the builder instance — not the result of `.build()`. ```dart CometChatConversations( - onItemTap: (conversation) => { - // TODO("Not yet implemented") - } -), + conversationsRequestBuilder: ConversationsRequestBuilder() + ..conversationType = "user" + ..limit = 10, +) ``` - - -*** +### Filter Recipes + +| Recipe | Code | +| --- | --- | +| Only user conversations | `ConversationsRequestBuilder()..conversationType = "user"` | +| Only group conversations | `ConversationsRequestBuilder()..conversationType = "group"` | +| Limit to 10 per page | `ConversationsRequestBuilder()..limit = 10` | +| With specific tags | `ConversationsRequestBuilder()..tags = ["vip"]` | +| With user and group tags | `ConversationsRequestBuilder()..withUserAndGroupTags = true` | + +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. + +Refer to [ConversationsRequestBuilder](/sdk/flutter/retrieve-conversations) for the full builder API. + +--- + + +## Actions and Events + +### Callback Props -##### onItemLongPress +#### onItemTap -`onItemLongPress` is triggered when you on long press on a ListItem of the `CometChatConversations` widget. This `onItemLongPress` method proves beneficial when a user intends to customize the long press behavior in CometChatConversations. +Fires when a conversation row is tapped. Primary navigation hook — set the active conversation and render the message view. ```dart CometChatConversations( - onItemLongPress: (conversation) => { - // Handle long press on conversation item - } -), + onItemTap: (conversation) { + print("Selected: ${conversation.conversationId}"); + }, +) ``` - - -*** +#### onItemLongPress -##### onBack - -This `onBack` method becomes valuable when a user needs to override the action triggered upon pressing the back button in CometChatConversations. +Fires when a conversation row is long-pressed. Useful for showing context menus or custom actions. ```dart CometChatConversations( - onBack: () => { - // TODO("Not yet implemented") - }, -), + onItemLongPress: (conversation) { + // Show custom context menu + }, +) ``` - - -*** - -##### setOnSelection +#### onSelection -The `onSelection` feature enables selection with modes: `SelectionMode.single` and `SelectionMode.multiple`. - -The `onSelection` event is triggered upon the completion of a selection in `onSelection`. This returns the selected conversations list when the callback is triggered. It can be executed with any button or action. +Fires when conversations are selected in multi-select mode. Requires `selectionMode` to be set. ```dart CometChatConversations( - selectionMode: SelectionMode.multiple, - onSelection: (list) => { - // TODO("Not yet implemented") - }, -), + selectionMode: SelectionMode.multiple, + onSelection: (selectedList) { + print("Selected ${selectedList?.length ?? 0} conversations"); + }, +) ``` - - -*** - -##### onError +#### onError -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatConversations. +Fires on internal errors (network failure, auth issue, SDK exception). ```dart CometChatConversations( - onError: (e) { - // TODO("Not yet implemented") - }, -), + onError: (error) { + print("CometChatConversations error: $error"); + }, +) ``` - - -*** +#### onBack -##### onLoad - -Invoked when the list is successfully fetched and loaded, helping track component readiness. +Fires when the back button is pressed. ```dart CometChatConversations( - onLoad: (list) { - // Handle conversations list load - }, -), + showBackButton: true, + onBack: () { + Navigator.pop(context); + }, +) ``` - - -*** - -##### onEmpty +#### onLoad -Called when the list is empty, enabling custom handling such as showing a placeholder message +Fires when the conversation list is successfully loaded. ```dart CometChatConversations( - onEmpty: () { - // Handle empty conversations list - }, -), + onLoad: (list) { + print("Loaded ${list.length} conversations"); + }, +) ``` - - -*** - -### Filters - -You can set `ConversationsRequestBuilder` in the `CometChatConversations` widget to filter the conversation list. You can modify the builder as per your specific requirements with multiple options available to know more refer to [ConversationsRequestBuilder](/sdk/flutter/retrieve-conversations). +#### onEmpty -You can set filters using the following parameters. - -* Conversation Type: Filters on type of Conversation, User or Groups. -* Limit: Number of conversations fetched in a single request. -* WithTags: Filter on fetching conversations containing tags. -* Tags: Filters on specific Tag. -* UserTags: Filters on specific User Tag. -* GroupTags: Filters on specific Group Tag. +Fires when the conversation list is empty. ```dart CometChatConversations( - conversationsRequestBuilder: ConversationsRequestBuilder() - ..conversationType = "user" - ..limit = 10 - ..withTags = false, + onEmpty: () { + print("No conversations found"); + }, ) ``` - - -You can set filters using the following parameters: - -| Property | Description | Code | -| ---------------------------- | ---------------------------------------------------- | ------------------------------- | -| **Build** | Builds and returns an `ConversationsRequest` object. | `build(): ConversationsRequest` | -| **Conversation Type** | Type of the conversation. | `conversationType: String?` | -| **Limit** | Number of results to limit the query. | `limit: int?` | -| **Tags** | Tags for filtering. | `tags: List?` | -| **With Tags** | Flag to include tags. | `withTags: bool?` | -| **With User And Group Tags** | Flag to include user and group tags. | `withUserAndGroupTags: bool?` | -*** +### Global UI Events -### Events +`CometChatConversationEvents` emits events subscribable from anywhere in the application. Add a listener in `initState` and remove it in `dispose`. -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccConversationDeleted` | A conversation is deleted from the list | `Conversation` | -##### 1. Conversation Deleted - -This `ccConversationDeleted` will be emitted when the user deletes a conversation +When to use: sync external UI with conversation state changes. For example, update an unread count badge in a tab bar when a conversation is deleted. @@ -267,1140 +411,1321 @@ class _YourScreenState extends State with CometChatConversationEvent @override void initState() { super.initState(); - CometChatConversationEvents.addConversationListListener("listenerId", this); // Add the listener + CometChatConversationEvents.addConversationListListener("listenerId", this); } @override - void dispose(){ + void dispose() { + CometChatConversationEvents.removeConversationListListener("listenerId"); super.dispose(); - CometChatConversationEvents.removeConversationListListener("listenerId"); // Remove the listener } @override void ccConversationDeleted(Conversation conversation) { - // TODO("Not yet implemented") + print("Deleted: ${conversation.conversationId}"); } } ``` - - -*** - -## Customization +### SDK Events (Real-Time, Automatic) -To align with your app's design specifications, you have the flexibility to customize the appearance of the conversation widget. We offer accessible methods that empower you to tailor the experience and functionality to meet your unique requirements. +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -### Style +| SDK Listener | Internal behavior | +| --- | --- | +| `onTextMessageReceived` / `onMediaMessageReceived` / `onCustomMessageReceived` | Moves conversation to top, updates last message preview and unread count | +| `onTypingStarted` / `onTypingEnded` | Shows/hides typing indicator in the subtitle | +| `onMessagesDelivered` / `onMessagesRead` | Updates receipt ticks (unless `receiptsVisibility: false`) | +| `onUserOnline` / `onUserOffline` | Updates online/offline status dot (unless `usersStatusVisibility: false`) | +| `onGroupMemberJoined` / `onGroupMemberLeft` / `onGroupMemberKicked` / `onGroupMemberBanned` / `onMemberAddedToGroup` | Updates group conversation metadata | -You can set the `CometChatConversationsStyle` to the `CometChatConversations` Widget to customize the styling. +Automatic: new messages, typing indicators, receipts, user presence, group membership changes. - - -```dart -CometChatConversations( - conversationsStyle: CometChatConversationsStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - badgeStyle:CometChatBadgeStyle( - backgroundColor: Color(0xFFF76808) - ) -) -), -``` +--- - - +## Custom View Slots - - - +Each slot replaces a section of the default UI. Slots that accept a conversation parameter receive the `Conversation` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `listItemView` | `Widget Function(Conversation)` | Entire list item row | +| `leadingView` | `Widget? Function(BuildContext, Conversation)` | Avatar / left section | +| `titleView` | `Widget? Function(BuildContext, Conversation)` | Name / title text | +| `subtitleView` | `Widget? Function(BuildContext, Conversation)` | Last message preview | +| `trailingView` | `Widget? Function(Conversation)` | Timestamp / badge / right section | +| `loadingStateView` | `WidgetBuilder` | Loading spinner | +| `emptyStateView` | `WidgetBuilder` | Empty state | +| `errorStateView` | `WidgetBuilder` | Error state | +| `setOptions` | `List? Function(Conversation, Controller, BuildContext)` | Context menu actions (replaces default) | +| `addOptions` | `List? Function(Conversation, Controller, BuildContext)` | Context menu actions (adds to default) | -### Functionality +### listItemView -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Replace the entire list item row. - + ```dart - CometChatConversations( - showBackButton: false, - title: "Your Title", +CometChatConversations( + listItemView: (conversation) { + final entity = conversation.conversationWith; + final name = entity is User ? entity.name : (entity as Group).name; + + return CometChatListItem( + avatarName: name, + avatarURL: entity is User ? entity.avatar : (entity as Group).icon, + title: name, + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + ), + ); + }, ) ``` - - -List of Poperties exposed by `CometChatConversations` - -| Property | Description | Code | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | -| **Activate Selection** | Used to specify if the listed conversations can be selected, selection can be activated on tap or on long press | `activateSelection: ActivateSelection` | -| **AppBar Options** | Used to set the options available in the app bar | `appBarOptions: List` | -| **Back Button** | Used to set back button located in the app bar | `backButton: Widget` | -| **Scroll Controller** | Used to programmatically update the scroll physics of list containing the conversations | `scrollController: ScrollController` | -| **Date Pattern** | Used to display a custom string instead of the timestamp show at the tail of the conversation item | `datePattern: String Function(Conversation conversation)` | -| **Empty State View** | Used to set a custom widget response when fetching the conversations has returned an empty list | `emptyStateView: WidgetBuilder` | -| **Error State View** | Used to set a custom widget response when some error occurs on fetching the list of conversations | `errorStateView: WidgetBuilder` | -| **Loading State View** | Used to set a custom widget response when conversations are loading | `loadingStateView: WidgetBuilder` | -| **Hide Appbar** | Toggle visibility for app bar | `hideAppbar: bool` | -| **Hide Error** | Used to hide error on fetching conversations | `hideError: bool` | -| **Hide Receipt** | Used to toggle visibility of message receipts shown in the subtitle of the conversation | `receiptsVisibility: bool` | -| **Protected Group Icon** | Used to set icon shown in place of status indicator if the conversation is taking place in a password-protected group | `protectedGroupIcon: Widget` | -| **Private Group Icon** | Used to set icon shown in place of status indicator if the conversation is taking place in a private group | `privateGroupIcon: Widget` | -| **Selection Icon** | Change selection icon | `selectionIcon: Widget` | -| **Sent Icon** | Used to customize the receipt icon shown in the subtitle of the conversation item if receiptsVisibility is false and the status of the last message in the conversation is sent | `sentIcon: Widget` | -| **Delivered Icon** | Used to customize the receipt icon if the message was delivered | `deliveredIcon: Widget` | -| **Read Icon** | Used to customize the receipt icon if the message was read | `readIcon: Widget` | -| **Show Back Button** | Used to toggle visibility for back button | `showBackButton: bool` | -| **Theme** | Used to set a custom theme | `conversationsStyle: CometChatConversationsStyle` | -| **Title** | Used to set the title in the app bar | `title: String` | -| **Typing Indicator Text** | Used to customize the text response shown in the subtitle of the conversation item if a participant of a conversation is typing | `typingIndicatorText: String` | -| **Disable Conversation Delete Option Visibility** | Used to toggle visibility for delete option | `deleteConversationOptionVisibility: bool` | -| **User Status Visibility** | Used to control visibility of status indicator shown if a user is online | `usersStatusVisibility: bool` | -| **Group Type Visibility** | Used to control visibility of the status indicator shown for the group type | `groupTypeVisibility: bool` | -| **On Back** | Callback triggered when closing the screen | `onBack: VoidCallback` | -| **On Item Tap** | Callback triggered when tapping a conversation item | `onItemTap: Function(Conversation conversation)` | -| **On Item Long Press** | Callback triggered when long pressing a conversation item | `onItemLongPress: Function(Conversation conversation)` | -| **Text Formatters** | List of text formatters for message bubbles with text type | `textFormatters: List` | -| **Date Padding** | Provides padding for the conversation date | `datePadding: EdgeInsets` | -| **Date Height** | Provides height for the conversation date | `dateHeight: double` | -| **Date Background Transparency** | Controls the background transparency of the conversation date | `dateBackgroundIsTransparent: bool` | -| **Date Width** | Provides width for the conversation date | `dateWidth: double` | -| **Badge Width** | Provides width for conversation badges | `badgeWidth: double` | -| **Badge Height** | Provides height for conversation badges | `badgeHeight: double` | -| **Badge Padding** | Provides padding for conversation badges | `badgePadding: EdgeInsetsGeometry` | -| **Avatar Width** | Provides width for user/group avatars | `avatarWidth: double` | -| **Avatar Height** | Provides height for user/group avatars | `avatarHeight: double` | -| **Avatar Padding** | Provides padding for user/group avatars | `avatarPadding: EdgeInsetsGeometry` | -| **Avatar Margin** | Provides margin for user/group avatars | `avatarMargin: EdgeInsetsGeometry` | -| **Status Indicator Width** | Provides width for the user/group status indicator | `statusIndicatorWidth: double` | -| **Status Indicator Height** | Provides height for the user/group status indicator | `statusIndicatorHeight: double` | -| **Status Indicator Border Radius** | Provides border radius for the user/group status indicator | `statusIndicatorBorderRadius: BorderRadiusGeometry` | -| **Controller Tag** | Tag for controller, used when parent needs to control the widget | `controllerTag: String` | -| **Submit Icon** | Used to override the default submit icon | `submitIcon: Widget` | -| **Set Options** | Sets the list of actions available on long press of a list item | `setOptions: Function(Conversation, Controller, Context)` | -| **Add Options** | Adds into the current list of actions available on long press of a list item | `addOptions: Function(Conversation, Controller, Context)` | -| **Leading View** | Custom widget for the leading section of each conversation | `leadingView: Widget Function(BuildContext, Conversation)` | -| **Title View** | Custom widget for the title section of each conversation | `titleView: Widget Function(BuildContext, Conversation)` | -| **On Load** | Callback when conversation list is loading | `onLoad: OnLoad` | -| **On Empty** | Callback when conversation list is empty | `onEmpty: OnEmpty` | -| **On Error** | Callback when an error occurs | `onError: OnError` | -| **Custom Sound For Messages** | Set a custom notification sound for messages | `customSoundForMessages: String` | -| **Disable Sound For Messages** | Disable sound for messages | `disableSoundForMessages: bool` | -| **Mention All Label Id** | Allows setting a custom label id for group mentions (@channel, @everyone, etc.). | `mentionAllLabelId: String` | -| **Mention All Label** | Allows setting a custom label for group mentions (@channel, @everyone, etc.). | `mentionAllLabel: String` | -| **Hide Search** | Hides the search bar in the app bar | `hideSearch: bool` | -| **Search Read Only** | Makes the search box read-only | `searchReadOnly: bool` | -| **On Search Tap** | Callback triggered when the search box is tapped | `onSearchTap: GestureTapCallback` | -| **Search Box Icon** | Custom prefix icon for the search box | `searchBoxIcon: Widget` | -| **Search Padding** | Provides padding for the search box | `searchPadding: EdgeInsetsGeometry` | -| **Search Content Padding** | Provides padding for the search box content | `searchContentPadding: EdgeInsetsGeometry` | -| **Date Time Formatter Callback** | Callback that can be used to format the date and time | `dateTimeFormatterCallback: DateTimeFormatterCallback` | - -### Advanced - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -#### setOptions - -This method sets a predefined list of actions that users can perform when they long press a conversation in the list. These options typically include: - -* Deleting a conversation -* Marking a conversation as read or unread -* Pinning or unpinning a conversation -* Muting notifications for a specific conversation - -By customizing these options, developers can provide a streamlined and contextually relevant user experience. +### leadingView + +Replace the avatar / left section. Typing-aware avatar example. + + + + ```dart +Map typingMap = {}; + CometChatConversations( - setOptions: (conversation, controller, context) { return [];}, + leadingView: (context, conversation) { + final entity = conversation.conversationWith; + final id = entity is User ? entity.uid : (entity as Group).guid; + + if (typingMap.containsKey(id)) { + return Container( + decoration: BoxDecoration( + border: Border.all(color: Color(0xFFF76808), width: 2), + borderRadius: BorderRadius.circular(8), + ), + child: Image.asset("assets/typing_icon.png", height: 40, width: 40), + ); + } + return null; // Use default avatar + }, ) ``` - - -Demonstration + +### titleView + +Replace the name / title text. Inline user status example. - + ```dart CometChatConversations( - setOptions: (conversation, controller, context) { - return [ - CometChatOption( - id: "Delete Conversation", - icon: AssetConstants.delete, - title: "Delete", - onClick: () { - // Delete Conversation - }, - ), - ]; - }, -), + titleView: (context, conversation) { + final entity = conversation.conversationWith; + final name = entity is User ? entity.name : (entity as Group).name; + final statusMessage = entity is User ? entity.statusMessage : null; + + return Row( + children: [ + Text(name ?? "", style: TextStyle(fontWeight: FontWeight.w500)), + if (statusMessage != null) + Text(" · $statusMessage", style: TextStyle(color: Color(0xFF6852D6))), + ], + ); + }, +) ``` - - -*** - -#### addOptions +### subtitleView -This method extends the existing set of actions available when users long press a conversation item. Unlike setOptionsDefines, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: +Replace the last message preview text. -* Adding a "Report Spam" action -* Introducing a "Save to Notes" option -* Integrating third-party actions such as "Share to Cloud Storage" - -This method provides flexibility in modifying user interaction capabilities. + + + ```dart CometChatConversations( - addOptions: (conversation, controller, context) { return [];}, -), + subtitleView: (context, conversation) { + final entity = conversation.conversationWith; + String subtitle; + + if (entity is User) { + final dateTime = entity.lastActiveAt ?? DateTime.now(); + subtitle = "Last Active: ${DateFormat('dd/MM/yyyy, HH:mm').format(dateTime)}"; + } else { + final dateTime = (entity as Group).createdAt ?? DateTime.now(); + subtitle = "Created: ${DateFormat('dd/MM/yyyy, HH:mm').format(dateTime)}"; + } + + return Text(subtitle, style: TextStyle(color: Color(0xFF727272), fontSize: 14)); + }, +) ``` - - -Demonstration +### trailingView + +Replace the timestamp / badge / right section. Relative time badge example. - + ```dart CometChatConversations( -addOptions: (conversation, controller, context) { - return [ - CometChatOption( - id: "Archive", - iconWidget: Icon( - Icons.archive_outlined, - color: colorPalette.error, - ), - title: "Archive", - onClick: () { - // Archive Conversation - }, - ), - CometChatOption( - id: "Pin", - iconWidget: Icon( - Icons.push_pin_outlined, - color: colorPalette.error, - ), - title: "Pin", - onClick: () { - // Pin Conversation - }, - ), - CometChatOption( - id: "Mark As Read", - iconWidget: Icon( - Icons.mark_chat_unread_outlined, - color: colorPalette.error, - ), - title: "Mark as unread", - onClick: () { - // Mark as unread - }, - ), - ]; - }, -), -``` + trailingView: (conversation) { + final timestamp = conversation.updatedAt?.millisecondsSinceEpoch ?? 0; + final now = DateTime.now(); + final lastSeen = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); + final diffInMinutes = now.difference(lastSeen).inMinutes; + final diffInHours = now.difference(lastSeen).inHours; + + String timeText; + String label; + Color cardColor; + + if (diffInMinutes < 60) { + timeText = "$diffInMinutes"; + label = "Min ago"; + cardColor = Color(0x666852D6); + } else if (diffInHours < 10) { + timeText = "$diffInHours"; + label = "Hr ago"; + cardColor = Color(0x66FFAB00); + } else { + timeText = "$diffInHours"; + label = "Hr ago"; + cardColor = Color(0x66F44649); + } + return Card( + color: cardColor, + child: Padding( + padding: EdgeInsets.all(4), + child: Column( + children: [ + Text(timeText, style: TextStyle(fontWeight: FontWeight.bold)), + Text(label, style: TextStyle(fontSize: 12)), + ], + ), + ), + ); + }, +) +``` - -*** - -#### disableSoundForMessages -This disables sound notifications for incoming messages. When activated, the application will not play an audio alert when new messages arrive. This feature is beneficial in scenarios where: +### setOptions -* Users prefer a silent messaging experience -* The app is being used in a professional or quiet environment -* Background processes need to minimize distractions +Replace the context menu / long-press actions on each conversation item. -By providing this option, the app allows users to tailor their notification preferences + + + ```dart CometChatConversations( - disableSoundForMessages: true, + setOptions: (conversation, controller, context) { + return [ + CometChatOption( + id: "delete", + title: "Delete", + icon: AssetConstants.delete, + onClick: () { + // Delete conversation + }, + ), + ]; + }, ) ``` - - -*** - -#### setCustomSoundForMessages +### addOptions -This method enables users to personalize their chat experience by setting a custom sound file for incoming message notifications. Users can choose from: +Add to the existing context menu actions without removing defaults. -* Default system sounds -* Custom sound files uploaded by the user -* Theme-based or brand-specific notification sounds - -By allowing sound customization, this feature enhances personalization and improves user engagement. + + + ```dart CometChatConversations( - customSoundForMessages: "message.mp3", -), + addOptions: (conversation, controller, context) { + return [ + CometChatOption( + id: "archive", + title: "Archive", + iconWidget: Icon(Icons.archive_outlined), + onClick: () { + // Archive conversation + }, + ), + CometChatOption( + id: "pin", + title: "Pin", + iconWidget: Icon(Icons.push_pin_outlined), + onClick: () { + // Pin conversation + }, + ), + ]; + }, +) ``` - - -*** - -#### loadingStateView +### appBarOptions -This method allows developers to set a custom loading view that is displayed when data is being fetched or loaded within the component. Instead of using a default loading spinner, a custom animation, progress bar, or branded loading screen can be displayed. +Add custom widgets to the app bar. -Use cases : - -* Showing a skeleton loader for conversations while data loads -* Displaying a custom progress indicator with branding -* Providing an animated loading experience for a more engaging UI + + + ```dart CometChatConversations( - loadingStateView: (context) { - // return Loading state Widget - }, -), + showBackButton: false, + appBarOptions: [ + PopupMenuButton( + icon: CometChatAvatar( + image: CometChatUIKit.loggedInUser?.avatar, + name: CometChatUIKit.loggedInUser?.name, + ), + itemBuilder: (context) => [ + PopupMenuItem(value: 'create', child: Text("Create Conversation")), + PopupMenuItem(value: 'logout', child: Text("Logout")), + ], + onSelected: (value) { + // Handle menu selection + }, + ), + ], +) ``` - - -*** - -#### emptyStateView +--- -Configures a custom view to be displayed when there are no conversations or messages in the list. This improves the user experience by providing meaningful content instead of an empty screen. -Use cases : +## Styling -* Displaying a message like "No conversations yet. Start a new chat!" -* Showing an illustration or animation to make the UI visually appealing -* Providing a button to start a new conversation +Set `CometChatConversationsStyle` to customize the appearance. ```dart CometChatConversations( - emptyStateView: (context) { - // return Empty state Widget - }, -), + conversationsStyle: CometChatConversationsStyle( + backgroundColor: Colors.white, + titleTextColor: Color(0xFF141414), + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + badgeStyle: CometChatBadgeStyle( + backgroundColor: Color(0xFFF76808), + ), + ), +) ``` - - -*** + + + -#### errorStateView +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color` | Background color of the component | +| `border` | `Border` | Border for the widget | +| `borderRadius` | `BorderRadiusGeometry` | Border radius for the widget | +| `titleTextColor` | `Color` | Color of the header title | +| `titleTextStyle` | `TextStyle` | Style for the header title | +| `backIconColor` | `Color` | Back button icon color | +| `searchBackgroundColor` | `Color` | Background color of search box | +| `searchBorder` | `BorderSide` | Border for search box | +| `searchBorderRadius` | `BorderRadius` | Border radius for search box | +| `searchPlaceHolderTextColor` | `Color` | Placeholder text color in search | +| `searchPlaceHolderTextStyle` | `TextStyle` | Placeholder text style in search | +| `searchIconColor` | `Color` | Search icon color | +| `separatorColor` | `Color` | Color of list item separators | +| `separatorHeight` | `double` | Height of list item separators | +| `emptyStateTextColor` | `Color` | Text color for empty state title | +| `emptyStateTextStyle` | `TextStyle` | Text style for empty state title | +| `emptyStateSubTitleTextColor` | `Color` | Text color for empty state subtitle | +| `emptyStateSubTitleTextStyle` | `TextStyle` | Text style for empty state subtitle | +| `errorStateTextColor` | `Color` | Text color for error state title | +| `errorStateTextStyle` | `TextStyle` | Text style for error state title | +| `errorStateSubTitleTextColor` | `Color` | Text color for error state subtitle | +| `errorStateSubTitleTextStyle` | `TextStyle` | Text style for error state subtitle | +| `itemTitleTextColor` | `Color` | Text color for conversation item title | +| `itemTitleTextStyle` | `TextStyle` | Text style for conversation item title | +| `itemSubtitleTextColor` | `Color` | Text color for conversation item subtitle | +| `itemSubtitleTextStyle` | `TextStyle` | Text style for conversation item subtitle | +| `messageTypeIconColor` | `Color` | Icon color for message type indicators | +| `avatarStyle` | `CometChatAvatarStyle` | Style for avatars | +| `badgeStyle` | `CometChatBadgeStyle` | Style for unread badges | +| `receiptStyle` | `CometChatMessageReceiptStyle` | Style for message receipts | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle` | Style for online status indicator | +| `dateStyle` | `CometChatDateStyle` | Style for date/time display | +| `typingIndicatorStyle` | `CometChatTypingIndicatorStyle` | Style for typing indicator | +| `mentionsStyle` | `CometChatMentionsStyle` | Style for @mentions | +| `deleteConversationDialogStyle` | `CometChatConfirmDialogStyle` | Style for delete confirmation dialog | +| `privateGroupIconBackground` | `Color` | Background color for private group icon | +| `protectedGroupIconBackground` | `Color` | Background color for protected group icon | +| `submitIconColor` | `Color` | Color for submit icon in selection mode | +| `checkBoxBackgroundColor` | `Color` | Background color for selection checkbox | +| `checkBoxCheckedBackgroundColor` | `Color` | Background color when checkbox is checked | +| `checkBoxBorder` | `BorderSide` | Border for selection checkbox | +| `checkBoxBorderRadius` | `BorderRadiusGeometry` | Border radius for selection checkbox | +| `checkboxSelectedIconColor` | `Color` | Icon color when checkbox is selected | +| `listItemSelectedBackgroundColor` | `Color` | Background color for selected list items | -Defines a custom error state view that appears when an issue occurs while loading conversations or messages. This enhances the user experience by displaying friendly error messages instead of generic system errors. +--- -Use cases : +## Common Patterns -* Showing "Something went wrong. Please try again." with a retry button -* Displaying a connection issue message if the user is offline -* Providing troubleshooting steps for the error +### Custom empty state with CTA ```dart CometChatConversations( - errorStateView: (context) { - // return Error state Widget - }, -), + emptyStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text("No conversations yet"), + SizedBox(height: 16), + ElevatedButton( + onPressed: () { + // Navigate to contacts + }, + child: Text("Start a conversation"), + ), + ], + ), + ); + }, +) ``` - - -*** +### Hide all chrome — minimal list -#### leadingView - -Allows setting a custom leading view element that appears at the beginning of each conversation item. This is typically used to modify profile pictures, avatars, or icons in the conversation list. + + +```dart +CometChatConversations( + receiptsVisibility: false, + usersStatusVisibility: false, + groupTypeVisibility: false, + deleteConversationOptionVisibility: false, + hideAppbar: true, +) +``` + + -Use cases : -* Displaying user avatars with online/offline status indicators -* Using initials or custom graphics instead of images +### Conversations with search ```dart CometChatConversations( - leadingView: (context, conversation) { - // return leading view - }, -), + hideSearch: false, + onSearchTap: () { + // Handle search tap - navigate to search screen + }, +) ``` - - -Demonstration +### Custom date pattern - + ```dart - - - Map typingMap = {}; - - @override - void onTypingStarted(TypingIndicator typingIndicator) { - if (userIsNotBlocked(typingIndicator.sender)) { - setTypingIndicator(typingIndicator, true); - } - } - - - @override - void onTypingEnded(TypingIndicator typingIndicator) { - if (userIsNotBlocked(typingIndicator.sender)) { - setTypingIndicator(typingIndicator, false); - } - } - - bool userIsNotBlocked(User user) { - return user.blockedByMe != true && user.hasBlockedMe != true; - } - - void setTypingIndicator( - TypingIndicator typingIndicator, bool isTypingStarted) { - if (typingIndicator.receiverType == ReceiverTypeConstants.user) { - if (isTypingStarted) { - typingMap[typingIndicator.sender.uid] = typingIndicator; - } else { - typingMap.remove(typingIndicator.sender.uid); - } - } else { - if (isTypingStarted) { - typingMap[typingIndicator.receiverId] = typingIndicator; - } else { - typingMap.remove(typingIndicator.receiverId); - } - } - setState(() {}); - } - CometChatConversations( -leadingView: (context, conversation) { - if (typingMap.containsKey( - (conversation.conversationType == "user" - ? (conversation.conversationWith as User).uid - : (conversation.conversationWith as Group).guid))) { - return Container( - decoration: BoxDecoration( - border: Border.all(color: Color(0xFFF76808), width: 2), - borderRadius: BorderRadius.circular(8), - ), - child: Image.asset( - "assets/leading_typing_icon.png", - height: 40, - width: 40, - ), - ); - } - return null; - }, + datePattern: (conversation) { + final date = conversation.lastMessage?.sentAt ?? DateTime.now(); + return DateFormat('d MMM, hh:mm a').format(date); + }, ) ``` - - -*** - -#### titleView +### Text formatters -Overrides the default title view in the conversation list with a custom layout. This is useful for branding or modifying how conversation names and details are displayed. +Configure text formatters for the conversation subtitle. See [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide) for mention formatting. -Use cases : - -* Displaying conversation titles with additional metadata (e.g., last seen time) -* Custom fonts or text styles for conversation names -* Adding icons or indicators next to titles + + + ```dart CometChatConversations( - titleView: (context, conversation) { - // return title view - }, + textFormatters: [ + CometChatMentionsFormatter( + style: CometChatMentionsStyle( + mentionSelfTextBackgroundColor: Color(0xFFF76808), + mentionTextBackgroundColor: Colors.white, + mentionTextColor: Colors.black, + mentionSelfTextColor: Colors.white, + ), + ), + ], ) ``` - - -Demonstration +--- - - - - - -```dart +## Props -CometChatConversations( - titleView: (context, conversation) { - return Row( - children: [ - Text( - conversation.conversationWith is User - ? (conversation.conversationWith as User).name ?? "" - : (conversation.conversationWith as Group).name ?? "", - style: TextStyle( - color: colorPalette.textPrimary, - fontSize: typography.body?.medium?.fontSize, - fontFamily: typography.body?.medium?.fontFamily, - fontWeight: typography.body?.medium?.fontWeight, - ), - ), - Text( - (conversation.conversationWith is User && - (conversation.conversationWith as User) - .statusMessage != - null) - ? ". ${(conversation.conversationWith as User).statusMessage}" - : "", - style: TextStyle( - color: colorPalette.textPrimary, - fontSize: typography.body?.medium?.fontSize, - fontFamily: typography.body?.medium?.fontFamily, - fontWeight: typography.body?.medium?.fontWeight, - ), - ), - ], - ); - }, -) -``` +All props are optional. Sorted alphabetically. - +### activateSelection - +Controls when selection mode activates. -*** +| | | +| --- | --- | +| Type | `ActivateSelection` | +| Default | `null` | -#### trailingView +Values: `ActivateSelection.onClick`, `ActivateSelection.onLongClick` -Customizes the trailing (end) view of a conversation item, which is typically used for action buttons or additional information. +--- -Use cases : +### addOptions -* Adding a mute/unmute button for each conversation -* Displaying the last message time in a custom format -* Showing unread message counts or notification badges +Adds to the current list of actions available on long press. - - -```dart -CometChatConversations( - trailingView: (context, conversation) { - // return tailing view - }, -) -``` +| | | +| --- | --- | +| Type | `List? Function(Conversation, CometChatConversationsController, BuildContext)` | +| Default | `null` | - +--- - +### appBarOptions -Demonstration +List of widgets to display in the app bar. - - - +| | | +| --- | --- | +| Type | `List` | +| Default | `null` | - - -```dart +--- -CometChatConversations( -trailingView: (conversation) { - int timestamp = - conversation.updatedAt?.millisecondsSinceEpoch ?? 0; - if (timestamp.toString().length == 10) { - timestamp *= - 1000; // Convert seconds to milliseconds if needed - } - - DateTime now = DateTime.now(); - DateTime lastSeen = - DateTime.fromMillisecondsSinceEpoch(timestamp); - - Duration diff = now.difference(lastSeen); - int diffInMinutes = diff.inMinutes; - int diffInHours = diff.inHours; - - String timeText; - String minText; - Color textColor; - Color cardColor; - - if (diffInMinutes == 0) { - timeText = "1"; - minText = "Min ago"; - textColor = Color(0xFF6852D6); - cardColor = Color(0x666852D6); // 40% alpha - } else if (diffInMinutes < 60) { - timeText = "$diffInMinutes"; - minText = "Min ago"; - textColor = Color(0xFF6852D6); - cardColor = Color(0x666852D6); - } else if (diffInHours < 10) { - timeText = "$diffInHours"; - minText = "Hr ago"; - textColor = Color(0xFFFFAB00); - cardColor = Color(0x66FFAB00); - } else { - timeText = "$diffInHours"; - minText = "Hr ago"; - textColor = Color(0xFFF44649); - cardColor = Color(0x66F44649); - } - return Card( - color: cardColor, - child: Padding( - padding: EdgeInsets.symmetric( - vertical: spacing.padding1 ?? 0, - horizontal: spacing.padding1 ?? 0, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Text( - timeText, - style: TextStyle( - color: textColor, - fontSize: 16, - fontWeight: FontWeight.bold), - ), - Text( - minText, - style: TextStyle( - color: textColor, - fontSize: 16, - fontWeight: FontWeight.bold), - ), - ], - ), - ), - ); - }, -) -``` +### backButton - +Custom back button widget. - +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in back arrow | -*** +--- -#### ListItemView +### conversationsRequestBuilder -With this function, you can assign a custom ListItem view to the `CometChatConversations` Widget. +Controls which conversations load and in what order. - - -```dart -CometChatConversations( - listItemView: (conversation) { - return Placeholder(); - }, -) -``` +| | | +| --- | --- | +| Type | `ConversationsRequestBuilder` | +| Default | SDK default (30 per page) | - +Pass the builder instance, not the result of `.build()`. - +--- - - - +### conversationsStyle -**Example** +Style configuration for the component. -Here is the complete example for reference: +| | | +| --- | --- | +| Type | `CometChatConversationsStyle` | +| Default | `CometChatConversationsStyle()` | - - -```dart custom_list_item.dart -Widget getCustomListItem( - Conversation conversation, - BuildContext context - ) { - Widget? tail; - Color? statusBackgroundColor; - Widget? icon; - final lastMessageTime = conversation.lastMessage?.sentAt ?? DateTime.now(); - tail = Padding( - padding: EdgeInsets.only( - left: 8, - ), - child: CometChatDate( - date: lastMessageTime, - padding:const EdgeInsets.all(0), - style: CometChatDateStyle( - backgroundColor: Colors.transparent, - textStyle: TextStyle( - color: Color(0xFF727272), - fontSize: 12, - fontWeight: FontWeight.w400, - ), - border: - Border.all( - width: 0, - color: Colors.transparent, - ), - ), - pattern: DateTimePattern.dayDateTimeFormat, - ) - ); +--- +### customSoundForMessages - User? conversationWithUser; - Group? conversationWithGroup; - if (conversation.conversationWith is User) { - conversationWithUser = conversation.conversationWith as User; - } else { - conversationWithGroup = conversation.conversationWith as Group; - } +Path to a custom audio file for incoming message notifications. - final statusStyle = - CometChatThemeHelper.getTheme( - context: context, - defaultTheme: CometChatStatusIndicatorStyle.of); - - StatusIndicatorUtils statusIndicatorUtils = - StatusIndicatorUtils.getStatusIndicatorFromParams( - context: context, - user: conversationWithUser, - group: conversationWithGroup, - onlineStatusIndicatorColor: Color(0xFF09C26F) - ); - - statusBackgroundColor = statusIndicatorUtils.statusIndicatorColor; - icon = statusIndicatorUtils.icon; - return GestureDetector( - key: UniqueKey(), - child: CometChatListItem( - avatarHeight:48, - avatarWidth:48, - id: conversation.conversationId, - avatarName: conversationWithUser?.name ?? conversationWithGroup?.name, - avatarURL: conversationWithUser?.avatar ?? conversationWithGroup?.icon, - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFAA9EE8), - ), - title: conversationWithUser?.name ?? conversationWithGroup?.name, - key: UniqueKey(), - tailView: tail, - statusIndicatorColor: statusBackgroundColor, - statusIndicatorIcon: icon, - statusIndicatorStyle: CometChatStatusIndicatorStyle( - border: statusStyle.border ?? - Border.all( - width: 2, - color: Color(0xFFFFFFFF), - ), - backgroundColor: statusStyle.backgroundColor, - ), - hideSeparator: true, - style: ListItemStyle( - background: Colors.transparent, - titleStyle: TextStyle( - overflow: TextOverflow.ellipsis, - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF141414), - ), - padding: EdgeInsets.symmetric( - horizontal: 16, - vertical: 12, - ), - ), - ), - ); -} -``` +| | | +| --- | --- | +| Type | `String` | +| Default | Built-in sound | - +--- - +### datePattern - - -```dart main.dart -CometChatConversations( - listItemView: (conversation) { - return getCustomListItem( - conversation, - context - ); - }, -) -``` +Custom date format function for conversation timestamps. - +| | | +| --- | --- | +| Type | `String Function(Conversation)` | +| Default | Built-in date formatting | - +--- -*** +### deleteConversationOptionVisibility -#### TextFormatters +Controls visibility of delete option in context menu. -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide) +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | -**Example** +--- -Here is the complete example for reference: +### deliveredIcon - - -```dart -CometChatConversations( - textFormatters: [ - CometChatMentionsFormatter( - style: CometChatMentionsStyle( - mentionSelfTextBackgroundColor: Color(0xFFF76808), - mentionTextBackgroundColor: Colors.white, - mentionTextColor: Colors.black, - mentionSelfTextColor: Colors.white, - ) - ) - ], -) -``` +Custom icon for delivered message receipts. - +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in delivered icon | - +--- - - - +### disableSoundForMessages -*** +Disables notification sound for incoming messages. -#### AppBarOptions +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | -You can set the Custom AppBarOptions to the `CometChatConversations` widget. +--- - - - - - -```dart - CometChatConversations( - showBackButton: false, - appBarOptions: [ - PopupMenuButton( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(8), - side: BorderSide( - color: Color(0xFFF5F5F5), - width: 1, - ), - ), - color: Color(0xFFFFFFFF), - elevation: 4, - menuPadding : EdgeInsets.zero, - padding: EdgeInsets.zero, - icon: Padding( - padding: EdgeInsets.only( - left: 12, - right: 16, - ), - child: CometChatAvatar( - width: 40, - height: 40, - image: CometChatUIKit.loggedInUser?.avatar, - name: CometChatUIKit.loggedInUser?.name, - ), - ), - onSelected: (value) { - switch (value) { - case '/Create': - setState(() { - _selectedIndex = 2; - }); - break; - case '/logout': - logout(); - break; - case '/name': - break; - case '/version': - break; - } - }, - position: PopupMenuPosition.under, - enableFeedback: false, - itemBuilder: (BuildContext context) { - return [ - PopupMenuItem( - height: 44, - padding: EdgeInsets.all(16), - value: '/Create', - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Padding( - padding: - EdgeInsets.only(right: 8), - child: Icon( - Icons.add_comment_outlined, - color: Color(0xFFA1A1A1), - size: 24, - ), - ), - Text( - "Create Conversation", - style: TextStyle( - fontSize: 14, - fontWeight:FontWeight.w400, - color: Color(0xFF141414), - ), - ), - ], - ), - ), - PopupMenuItem( - height: 44, - padding: EdgeInsets.all(16), - value: '/name', - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Padding( - padding: - EdgeInsets.only(right: 8), - child: Icon( - Icons.account_circle_outlined, - color: Color(0xFFA1A1A1), - size: 24, - ), - ), - Text( - CometChatUIKit.loggedInUser?.name ?? "", - style: TextStyle( - fontSize: 14, - fontWeight:FontWeight.w400, - color: Color(0xFF141414), - ), - ), - ], - ), - ), - PopupMenuItem( - height: 44, - padding: EdgeInsets.all(16), - value: '/logout', - child: Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - Padding( - padding: - EdgeInsets.only(right: 8), - child: Icon( - Icons.logout, - color: Colors.red, - size: 24, - ), - ), - Text( - "Logout", - style: TextStyle( - fontSize: 14, - fontWeight:FontWeight.w400, - color: Colors.red, - ), - ), - ], - ), - ), - PopupMenuItem( - enabled: false, - height: 44, - padding: EdgeInsets.zero, - value: '/version', - child: Container( - width: double.infinity, - decoration: BoxDecoration( - border: Border( - top: BorderSide( - color: Color(0xFFF5F5F5), - width: 1, - ), - ), - ), - child: Padding( - padding: EdgeInsets.all(16), - child: Text( - "V5.0.0_alpha1", - style: TextStyle( - fontSize: 14, - fontWeight:FontWeight.w400, - color: Color(0xFF727272), - ), - ), - ), - ), - ), - ]; - }, - ), - ], - onItemTap: (conversation) { - User? user; - Group? group; - if (conversation.conversationWith is User) { - user = conversation.conversationWith as User; - } else { - group = conversation.conversationWith as Group; - } - navigateToMessages(user: user, group: group); - }, - ) -``` +### emptyStateView - +Custom widget displayed when there are no conversations. - +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in empty state | -*** +--- -#### DatePattern +### errorStateView -You can modify the date pattern to your requirement using `datePattern`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. +Custom widget displayed when an error occurs. - - - +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in error state | - - -```dart -CometChatConversations( - datePattern: (conversation) => DateFormat('d MMM, hh:mm a').format(conversation.lastMessage?.sentAt ?? DateTime.now()), -) -``` +Hidden when `hideError: true`. - +--- - +### groupTypeVisibility -*** +Controls visibility of group type icon (public/private/password). -#### SubtitleView +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | -You can customize the subtitle view for each conversation item to meet your requirements +--- - - - +### hideAppbar - - -```dart -CometChatConversations( - subtitleView: (context, conversation) { - String subtitle = ""; - - if (conversation.conversationWith is User) { - User user = conversation.conversationWith as User; - final dateTime = user.lastActiveAt ?? DateTime.now(); - subtitle = "Last Active at " + DateFormat('dd/MM/yyyy, HH:mm:ss').format(dateTime); - } else { - Group group = conversation.conversationWith as Group; - final dateTime = group.createdAt ?? DateTime.now(); - subtitle = "Created at " + DateFormat('dd/MM/yyyy, HH:mm:ss').format(dateTime); - } - return Text(subtitle, - style: TextStyle( - color: Color(0xFF727272), - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ); - } -) -``` +Hides the entire app bar. - +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | - +--- + +### hideError + +Hides the default and custom error views. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### hideSearch + +Hides the search bar in the app bar. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### leadingView + +Custom renderer for the avatar / left section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext, Conversation)` | +| Default | Built-in avatar | + +Return `null` to use the default avatar. + +--- + +### listItemView + +Custom renderer for the entire list item row. + +| | | +| --- | --- | +| Type | `Widget Function(Conversation)` | +| Default | Built-in list item | + +--- + +### loadingStateView + +Custom widget displayed during loading state. + +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in shimmer | + +--- + +### mentionAllLabel + +Custom label for group mentions (@channel, @everyone). + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### mentionAllLabelId + +Custom label ID for group mentions. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + + +### onBack + +Callback fired when the back button is pressed. + +| | | +| --- | --- | +| Type | `VoidCallback` | +| Default | `null` | + +--- + +### onEmpty + +Callback fired when the conversation list is empty. + +| | | +| --- | --- | +| Type | `OnEmpty` | +| Default | `null` | + +--- + +### onError + +Callback fired when the component encounters an error. + +| | | +| --- | --- | +| Type | `OnError` | +| Default | `null` | + +--- + +### onItemLongPress + +Callback fired when a conversation row is long-pressed. + +| | | +| --- | --- | +| Type | `Function(Conversation)` | +| Default | `null` | + +--- + +### onItemTap + +Callback fired when a conversation row is tapped. + +| | | +| --- | --- | +| Type | `Function(Conversation)` | +| Default | `null` | + +--- + +### onLoad + +Callback fired when the conversation list is loaded. + +| | | +| --- | --- | +| Type | `OnLoad` | +| Default | `null` | + +--- + +### onSearchTap + +Callback fired when the search box is tapped. + +| | | +| --- | --- | +| Type | `GestureTapCallback` | +| Default | `null` | + +Requires `searchReadOnly: true` to work properly. + +--- + +### onSelection + +Callback fired when conversations are selected/deselected. + +| | | +| --- | --- | +| Type | `Function(List?)` | +| Default | `null` | + +Requires `selectionMode` to be set. + +--- + +### privateGroupIcon + +Custom icon for private group indicator. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in lock icon | + +--- + +### protectedGroupIcon + +Custom icon for password-protected group indicator. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in lock icon | + +--- + +### readIcon + +Custom icon for read message receipts. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in read icon | + +--- + +### receiptsVisibility + +Controls visibility of message read/delivery receipts. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + + +### scrollController + +Custom scroll controller for the list. + +| | | +| --- | --- | +| Type | `ScrollController` | +| Default | `null` | + +--- + +### searchBoxIcon + +Custom prefix icon for the search box. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in search icon | + +--- + +### searchReadOnly + +Makes the search box read-only (tap only). + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### selectionMode + +Enables single or multi-select mode. + +| | | +| --- | --- | +| Type | `SelectionMode` | +| Default | `null` | + +Values: `SelectionMode.single`, `SelectionMode.multiple`, `SelectionMode.none` + +Must pair with `onSelection` to capture selections. + +--- + +### sentIcon + +Custom icon for sent message receipts. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in sent icon | + +--- + +### setOptions + +Replaces the list of actions available on long press. + +| | | +| --- | --- | +| Type | `List? Function(Conversation, CometChatConversationsController, BuildContext)` | +| Default | `null` | + +--- + +### showBackButton + +Shows the back button in the app bar. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### subtitleView + +Custom renderer for the last message preview. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext, Conversation)` | +| Default | Built-in subtitle | + +--- + +### textFormatters + +Custom text formatters for the conversation subtitle. + +| | | +| --- | --- | +| Type | `List` | +| Default | Default formatters from data source | + +See [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide) for mention formatting. + +--- + +### title + +Custom title text for the app bar. + +| | | +| --- | --- | +| Type | `String` | +| Default | "Chats" | + +--- + +### titleView + +Custom renderer for the name / title text. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext, Conversation)` | +| Default | Built-in title | + +--- + +### trailingView + +Custom renderer for the timestamp / badge / right section. + +| | | +| --- | --- | +| Type | `Widget? Function(Conversation)` | +| Default | Built-in trailing view | + +--- + +### typingIndicatorText + +Custom text shown when a user is typing. + +| | | +| --- | --- | +| Type | `String` | +| Default | "typing..." | + +--- + +### usersStatusVisibility + +Controls visibility of online/offline status indicator. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + +### avatarHeight + +Height for user/group avatars. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### avatarWidth + +Width for user/group avatars. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### avatarPadding + +Padding for user/group avatars. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### avatarMargin + +Margin for user/group avatars. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### badgeWidth + +Width for unread message badge. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### badgeHeight + +Height for unread message badge. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### badgePadding + +Padding for unread message badge. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### controllerTag + +Tag for controller management. When passed, parent is responsible for closing. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### dateBackgroundIsTransparent + +Controls whether the date background is transparent. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `null` | + +--- + +### dateHeight + +Height for the conversation date display. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### datePadding + +Padding for the conversation date display. + +| | | +| --- | --- | +| Type | `EdgeInsets` | +| Default | `null` | + +--- + +### dateTimeFormatterCallback + +Callback for custom date and time formatting. + +| | | +| --- | --- | +| Type | `DateTimeFormatterCallback` | +| Default | `null` | + +--- + +### dateWidth + +Width for the conversation date display. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### listItemStyle + +Style configuration for list items. + +| | | +| --- | --- | +| Type | `ListItemStyle` | +| Default | `null` | + +--- + +### searchContentPadding + +Padding for search box content. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### searchPadding + +Padding for the search box. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### statusIndicatorBorderRadius + +Border radius for the status indicator. + +| | | +| --- | --- | +| Type | `BorderRadiusGeometry` | +| Default | `null` | + +--- + +### statusIndicatorHeight + +Height for the status indicator. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### statusIndicatorWidth + +Width for the status indicator. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### submitIcon + +Custom submit icon for selection mode. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in check icon | + +--- + +## Events + +| Event | Payload | Fires when | +| --- | --- | --- | +| `CometChatConversationEvents.ccConversationDeleted` | `Conversation` | Conversation deleted from list | + +Subscribe using `CometChatConversationEvents.addConversationListListener()` and unsubscribe with `removeConversationListListener()`. + +--- + +## Customization Matrix -*** +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Widget props | `on` callbacks | `onItemTap: (c) => setActive(c)` | +| Filter which conversations appear | Widget props | `conversationsRequestBuilder` | `conversationsRequestBuilder: ConversationsRequestBuilder()..limit = 10` | +| Toggle visibility of UI elements | Widget props | `Visibility` boolean props | `receiptsVisibility: false` | +| Replace a section of the list item | Widget props | `View` render props | `listItemView: (conversation) => CustomWidget()` | +| Change colors, fonts, spacing | Widget props | `conversationsStyle` | `conversationsStyle: CometChatConversationsStyle(backgroundColor: Colors.white)` | From f485affa16092081120d6c0e39d91a0c01091ee7 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Tue, 3 Mar 2026 17:57:35 +0530 Subject: [PATCH 027/106] Update conversations.mdx --- ui-kit/flutter/conversations.mdx | 339 +++++++++++++++++++++++++++++-- 1 file changed, 322 insertions(+), 17 deletions(-) diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index 239fda8b6..d71e86706 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -82,22 +82,37 @@ description: "Scrollable list of recent one-on-one and group conversations for t "name": "CometChatConversationEvents.ccConversationDeleted", "payload": "Conversation", "description": "Conversation deleted from list" + }, + { + "name": "CometChatConversationEvents.ccUpdateConversation", + "payload": "Conversation", + "description": "Conversation updated" } ], "sdkListeners": [ "onTextMessageReceived", "onMediaMessageReceived", "onCustomMessageReceived", + "onFormMessageReceived", + "onCardMessageReceived", + "onCustomInteractiveMessageReceived", + "onSchedulerMessageReceived", "onTypingStarted", "onTypingEnded", "onMessagesDelivered", "onMessagesRead", + "onMessagesDeliveredToAll", + "onMessagesReadByAll", + "onMessageEdited", + "onMessageDeleted", "onUserOnline", "onUserOffline", "onGroupMemberJoined", "onGroupMemberLeft", "onGroupMemberKicked", "onGroupMemberBanned", + "onGroupMemberUnbanned", + "onGroupMemberScopeChanged", "onMemberAddedToGroup" ], "compositionExample": { @@ -264,9 +279,27 @@ CometChatConversations( | Limit to 10 per page | `ConversationsRequestBuilder()..limit = 10` | | With specific tags | `ConversationsRequestBuilder()..tags = ["vip"]` | | With user and group tags | `ConversationsRequestBuilder()..withUserAndGroupTags = true` | +| Include blocked users | `ConversationsRequestBuilder()..includeBlockedUsers = true` | +| Search conversations | `ConversationsRequestBuilder()..searchKeyword = "hello"` | +| Unread only | `ConversationsRequestBuilder()..unread = true` | Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. +### ConversationsRequestBuilder Properties + +| Property | Description | Code | +| --- | --- | --- | +| `limit` | Number of conversations to fetch per request. Maximum 50. | `..limit = 30` | +| `conversationType` | Filter by conversation type: `"user"` or `"group"`. If not set, returns both. | `..conversationType = "user"` | +| `withTags` | Include tags associated with conversations. Default `false`. | `..withTags = true` | +| `tags` | Filter conversations by specific tags. | `..tags = ["archived", "vip"]` | +| `withUserAndGroupTags` | Include user/group tags in the Conversation object. Default `false`. | `..withUserAndGroupTags = true` | +| `includeBlockedUsers` | Include conversations with blocked users. Default `false`. | `..includeBlockedUsers = true` | +| `withBlockedInfo` | Include blocked info in the ConversationWith object. Default `false`. | `..withBlockedInfo = true` | +| `searchKeyword` | Search conversations by user or group name. Requires Advanced plan. | `..searchKeyword = "John"` | +| `unread` | Fetch only unread conversations. Requires Advanced plan. | `..unread = true` | +| `build()` | Builds and returns a `ConversationsRequest` object. | `.build()` | + Refer to [ConversationsRequestBuilder](/sdk/flutter/retrieve-conversations) for the full builder API. --- @@ -493,6 +526,81 @@ CometChatConversations( +For a more complete custom list item with status indicator and date: + + + +```dart +Widget getCustomListItem(Conversation conversation, BuildContext context) { + User? conversationWithUser; + Group? conversationWithGroup; + + if (conversation.conversationWith is User) { + conversationWithUser = conversation.conversationWith as User; + } else { + conversationWithGroup = conversation.conversationWith as Group; + } + + // Get status indicator + StatusIndicatorUtils statusIndicatorUtils = StatusIndicatorUtils.getStatusIndicatorFromParams( + context: context, + user: conversationWithUser, + group: conversationWithGroup, + onlineStatusIndicatorColor: Color(0xFF09C26F), + ); + + // Build tail view with date + final lastMessageTime = conversation.lastMessage?.sentAt ?? DateTime.now(); + Widget tail = CometChatDate( + date: lastMessageTime, + padding: EdgeInsets.zero, + style: CometChatDateStyle( + backgroundColor: Colors.transparent, + textStyle: TextStyle(color: Color(0xFF727272), fontSize: 12), + border: Border.all(width: 0, color: Colors.transparent), + ), + pattern: DateTimePattern.dayDateTimeFormat, + ); + + return CometChatListItem( + avatarHeight: 48, + avatarWidth: 48, + id: conversation.conversationId, + avatarName: conversationWithUser?.name ?? conversationWithGroup?.name, + avatarURL: conversationWithUser?.avatar ?? conversationWithGroup?.icon, + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFAA9EE8), + ), + title: conversationWithUser?.name ?? conversationWithGroup?.name, + tailView: tail, + statusIndicatorColor: statusIndicatorUtils.statusIndicatorColor, + statusIndicatorIcon: statusIndicatorUtils.icon, + statusIndicatorStyle: CometChatStatusIndicatorStyle( + border: Border.all(width: 2, color: Colors.white), + ), + hideSeparator: true, + style: ListItemStyle( + background: Colors.transparent, + titleStyle: TextStyle( + overflow: TextOverflow.ellipsis, + fontSize: 16, + fontWeight: FontWeight.w500, + color: Color(0xFF141414), + ), + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12), + ), + ); +} + +// Usage: +CometChatConversations( + listItemView: (conversation) => getCustomListItem(conversation, context), +) +``` + + + ### leadingView Replace the avatar / left section. Typing-aware avatar example. @@ -504,25 +612,67 @@ Replace the avatar / left section. Typing-aware avatar example. ```dart -Map typingMap = {}; +// In your StatefulWidget, use the MessageListener mixin: +class _ConversationsScreenState extends State with MessageListener { + Map typingMap = {}; -CometChatConversations( - leadingView: (context, conversation) { - final entity = conversation.conversationWith; - final id = entity is User ? entity.uid : (entity as Group).guid; + @override + void initState() { + super.initState(); + CometChat.addMessageListener("typing_listener", this); + } + + @override + void dispose() { + CometChat.removeMessageListener("typing_listener"); + super.dispose(); + } + + @override + void onTypingStarted(TypingIndicator typingIndicator) { + setTypingIndicator(typingIndicator, true); + } + + @override + void onTypingEnded(TypingIndicator typingIndicator) { + setTypingIndicator(typingIndicator, false); + } + + void setTypingIndicator(TypingIndicator typingIndicator, bool isTypingStarted) { + final id = typingIndicator.receiverType == ReceiverTypeConstants.user + ? typingIndicator.sender.uid + : typingIndicator.receiverId; - if (typingMap.containsKey(id)) { - return Container( - decoration: BoxDecoration( - border: Border.all(color: Color(0xFFF76808), width: 2), - borderRadius: BorderRadius.circular(8), - ), - child: Image.asset("assets/typing_icon.png", height: 40, width: 40), - ); - } - return null; // Use default avatar - }, -) + setState(() { + if (isTypingStarted) { + typingMap[id] = typingIndicator; + } else { + typingMap.remove(id); + } + }); + } + + @override + Widget build(BuildContext context) { + return CometChatConversations( + leadingView: (context, conversation) { + final entity = conversation.conversationWith; + final id = entity is User ? entity.uid : (entity as Group).guid; + + if (typingMap.containsKey(id)) { + return Container( + decoration: BoxDecoration( + border: Border.all(color: Color(0xFFF76808), width: 2), + borderRadius: BorderRadius.circular(8), + ), + child: Image.asset("assets/typing_icon.png", height: 40, width: 40), + ); + } + return null; // Use default avatar + }, + ); + } +} ``` @@ -704,6 +854,14 @@ CometChatConversations( // Pin conversation }, ), + CometChatOption( + id: "mark_unread", + title: "Mark as unread", + iconWidget: Icon(Icons.mark_chat_unread_outlined), + onClick: () { + // Mark conversation as unread + }, + ), ]; }, ) @@ -744,6 +902,106 @@ CometChatConversations( +For a more complete popup menu with styling: + + + +```dart +CometChatConversations( + showBackButton: false, + appBarOptions: [ + PopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide(color: Color(0xFFF5F5F5), width: 1), + ), + color: Colors.white, + elevation: 4, + menuPadding: EdgeInsets.zero, + padding: EdgeInsets.zero, + icon: Padding( + padding: EdgeInsets.only(left: 12, right: 16), + child: CometChatAvatar( + width: 40, + height: 40, + image: CometChatUIKit.loggedInUser?.avatar, + name: CometChatUIKit.loggedInUser?.name, + ), + ), + onSelected: (value) { + switch (value) { + case '/create': + // Navigate to create conversation + break; + case '/logout': + CometChatUIKit.logout(); + break; + } + }, + position: PopupMenuPosition.under, + itemBuilder: (BuildContext context) { + return [ + PopupMenuItem( + height: 44, + padding: EdgeInsets.all(16), + value: '/create', + child: Row( + children: [ + Padding( + padding: EdgeInsets.only(right: 8), + child: Icon(Icons.add_comment_outlined, color: Color(0xFFA1A1A1), size: 24), + ), + Text("Create Conversation", style: TextStyle(fontSize: 14, color: Color(0xFF141414))), + ], + ), + ), + PopupMenuItem( + height: 44, + padding: EdgeInsets.all(16), + value: '/name', + child: Row( + children: [ + Padding( + padding: EdgeInsets.only(right: 8), + child: Icon(Icons.account_circle_outlined, color: Color(0xFFA1A1A1), size: 24), + ), + Text(CometChatUIKit.loggedInUser?.name ?? "", style: TextStyle(fontSize: 14, color: Color(0xFF141414))), + ], + ), + ), + PopupMenuItem( + height: 44, + padding: EdgeInsets.all(16), + value: '/logout', + child: Row( + children: [ + Padding( + padding: EdgeInsets.only(right: 8), + child: Icon(Icons.logout, color: Colors.red, size: 24), + ), + Text("Logout", style: TextStyle(fontSize: 14, color: Colors.red)), + ], + ), + ), + ]; + }, + ), + ], + onItemTap: (conversation) { + User? user; + Group? group; + if (conversation.conversationWith is User) { + user = conversation.conversationWith as User; + } else { + group = conversation.conversationWith as Group; + } + // Navigate to messages + }, +) +``` + + + --- @@ -937,6 +1195,17 @@ CometChatConversations( --- +## Accessibility + +The component renders a scrollable list of interactive items. Each conversation row is tappable and responds to both tap and long-press gestures. The context menu (options) is accessible via long-press. The unread badge count is exposed as text content. Avatar images include the conversation name for accessibility. + +For screen readers, the conversation list is rendered as a semantic list using Flutter's built-in accessibility features. Status indicators (online/offline, group type icons) use visual icons — consider providing custom `Semantics` widgets via `leadingView` if screen reader descriptions are needed for these visual indicators. + +When using selection mode, checkboxes are rendered with proper accessibility labels. The component respects system accessibility settings including text scaling and high contrast modes. + +--- + + ## Props All props are optional. Sorted alphabetically. @@ -1000,6 +1269,19 @@ Pass the builder instance, not the result of `.build()`. --- +### conversationsProtocol + +Custom protocol for fetching conversations. + +| | | +| --- | --- | +| Type | `ConversationsBuilderProtocol` | +| Default | `null` | + +Use this for advanced customization of how conversations are fetched. + +--- + ### conversationsStyle Style configuration for the component. @@ -1352,6 +1634,28 @@ Custom prefix icon for the search box. --- +### searchContentPadding + +Padding for search box content. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + +### searchPadding + +Padding for the search box. + +| | | +| --- | --- | +| Type | `EdgeInsetsGeometry` | +| Default | `null` | + +--- + ### searchReadOnly Makes the search box read-only (tap only). @@ -1715,6 +2019,7 @@ Custom submit icon for selection mode. | Event | Payload | Fires when | | --- | --- | --- | | `CometChatConversationEvents.ccConversationDeleted` | `Conversation` | Conversation deleted from list | +| `CometChatConversationEvents.ccUpdateConversation` | `Conversation` | Conversation updated (last message change, metadata update) | Subscribe using `CometChatConversationEvents.addConversationListListener()` and unsubscribe with `removeConversationListListener()`. From d306c56aa6cf2befaf1d5ec39fb0c9d533568a94 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 09:50:50 +0530 Subject: [PATCH 028/106] updates components --- ui-kit/flutter/ai-assistant-chat-history.mdx | 561 +++--- ui-kit/flutter/components-overview.mdx | 194 ++- ui-kit/flutter/conversations.mdx | 181 +- ui-kit/flutter/group-members.mdx | 1330 +++++++------- ui-kit/flutter/groups.mdx | 1631 +++++++++++++----- ui-kit/flutter/message-composer.mdx | 823 ++++----- ui-kit/flutter/message-list.mdx | 1193 +++++-------- ui-kit/flutter/search.mdx | 628 ++++--- ui-kit/flutter/threaded-messages-header.mdx | 396 +++-- ui-kit/flutter/users.mdx | 1585 ++++++++++++----- 10 files changed, 5091 insertions(+), 3431 deletions(-) diff --git a/ui-kit/flutter/ai-assistant-chat-history.mdx b/ui-kit/flutter/ai-assistant-chat-history.mdx index f01aa81dc..1b2961c0f 100644 --- a/ui-kit/flutter/ai-assistant-chat-history.mdx +++ b/ui-kit/flutter/ai-assistant-chat-history.mdx @@ -1,42 +1,130 @@ --- title: "AI Assistant Chat History" +description: "A widget that displays conversation history between users and an AI assistant" --- -## Overview + +```json +{ + "component": "CometChatAIAssistantChatHistory", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A widget that displays the conversation history between users and an AI assistant with date separators and new chat functionality", + "primaryOutput": { + "prop": "onMessageClicked", + "type": "void Function(BaseMessage? message)?" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "null", + "note": "User object for user message list (one of user/group required)" + }, + "group": { + "type": "Group?", + "default": "null", + "note": "Group object for group message list (one of user/group required)" + }, + "messagesRequestBuilder": { + "type": "MessagesRequestBuilder?", + "default": "null", + "note": "Custom request builder passed to CometChat's SDK" + } + }, + "callbacks": { + "onMessageClicked": "void Function(BaseMessage? message)?", + "onNewChatButtonClicked": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "onClose": "VoidCallback?" + }, + "visibility": { + "hideStickyDate": { + "type": "bool?", + "default": "null" + }, + "hideDateSeparator": { + "type": "bool?", + "default": "null" + } + }, + "viewSlots": { + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "backButton": "Widget?" + }, + "formatting": { + "dateSeparatorPattern": { + "type": "String Function(DateTime)?", + "default": "null" + }, + "dateTimeFormatterCallback": { + "type": "DateTimeFormatterCallback?", + "default": "null" + } + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CometChatAIAssistantChatHistory is typically used within AI assistant features to show past conversations", + "components": ["CometChatMessageList", "CometChatMessageComposer"], + "flow": "User opens chat history → Past messages displayed → User clicks message or starts new chat" + }, + "types": {} +} +``` + -The `AI Assistant Chat History` widget is a pre-built user interface widget designed to display the conversation history between users and an AI assistant within a chat application. It provides a structured and visually appealing way to present past interactions, making it easy for users to review previous messages and context. +## Where It Fits + +CometChatAIAssistantChatHistory is a pre-built user interface widget designed to display the conversation history between users and an AI assistant within a chat application. It provides a structured and visually appealing way to present past interactions, making it easy for users to review previous messages and context. -## Usage - -### Integration +## Minimal Render -You can launch `CometChatAIAssistantChatHistory` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. - -##### 1. Using Navigator to Launch `CometChatAIAssistantChatHistory` +The simplest way to render CometChatAIAssistantChatHistory: ```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatAIAssistantChatHistory())); // A user or group object is required to launch this widget. -``` +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +CometChatAIAssistantChatHistory( + user: user, // Required: User or Group object +) +``` - - Simply adding the `CometChatAIAssistantChatHistory` component to the layout will only display the loading indicator. To fetch messages for a specific entity, you need to supplement it with `User` or `Group` Object. - -*** +You can also launch it using Navigator: -##### 2. Embedding `ChatHistory` as a Widget in the build Method + + +```dart +Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatAIAssistantChatHistory( + user: user, // A user or group object is required + ), + ), +); +``` + + + +Or embed it as a widget: @@ -52,194 +140,203 @@ class ChatHistory extends StatefulWidget { } class _ChatHistoryState extends State { - @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: CometChatAIAssistantChatHistory() // A user or group object is required to launch this widget. - ) + body: SafeArea( + child: CometChatAIAssistantChatHistory( + user: user, // A user or group object is required + ), + ), ); } } ``` - - -*** - -### Actions +## Filtering -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. - -##### onNewChatButtonClicked - -`onNewChatButtonClicked` is triggered when you click on the new chat button. The `onNewChatButtonClicked` action doesn't have a predefined behavior. You can override this action using the following code snippet. +You can adjust the `MessagesRequestBuilder` to customize the message list. Numerous options are available to alter the builder to meet your specific needs. ```dart CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - onNewChatButtonClicked: () { - // TODO("Not yet implemented") - }, + user: user, + messagesRequestBuilder: MessagesRequestBuilder() + ..uid = user.uid, ) ``` - - -*** + +The following parameters in messageRequestBuilder will always be altered inside the list: +1. UID +2. GUID +3. types +4. categories + -##### onMessageClicked +For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/flutter/additional-message-filtering). -You can customize this behavior by using the provided code snippet to override the `onMessageClicked`. +## Actions and Events + +### Callback Props + +Component-level callbacks that fire on specific user interactions: + +| Callback | Signature | Fires When | +|----------|-----------|------------| +| `onMessageClicked` | `void Function(BaseMessage? message)?` | User clicks a message | +| `onNewChatButtonClicked` | `VoidCallback?` | User clicks the new chat button | +| `onError` | `OnError?` | An error occurs while fetching messages | +| `onLoad` | `OnLoad?` | List is successfully loaded | +| `onEmpty` | `OnEmpty?` | List is empty | +| `onClose` | `VoidCallback?` | User clicks the back/close button | ```dart CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. + user: user, + onNewChatButtonClicked: () { + // Start a new chat session + print('New chat initiated'); + }, onMessageClicked: (message) { - // TODO("Not yet implemented") + // Navigate to the message context + print('Message clicked: ${message?.id}'); + }, + onError: (e) { + print('Error: $e'); + }, + onLoad: (list) { + print('Messages loaded: ${list.length}'); + }, + onEmpty: () { + print('No messages found'); + }, + onClose: () { + Navigator.pop(context); }, ) ``` - - -*** +### Global UI Events + +The CometChatAIAssistantChatHistory component does not produce any global UI events. -##### onError +## Custom View Slots -You can customize this behavior by using the provided code snippet to override the `onError` and improve error handling. +Customize the appearance of CometChatAIAssistantChatHistory by replacing default views with your own widgets. + +| Slot | Signature | Replaces | +|------|-----------|----------| +| `loadingStateView` | `WidgetBuilder?` | Loading spinner | +| `emptyStateView` | `WidgetBuilder?` | Empty state display | +| `errorStateView` | `WidgetBuilder?` | Error state display | +| `backButton` | `Widget?` | Back/close button | + +### Example: Custom Back Button ```dart CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - onError: (e) { - // TODO("Not yet implemented") - }, + user: user, + backButton: IconButton( + icon: const Icon( + Icons.arrow_back, + color: Colors.red, + ), + onPressed: () { + Navigator.pop(context); + }, + ), ) ``` - - -##### onLoad - -Invoked when the list is successfully fetched and loaded, helping track component readiness. +### Example: Custom Loading State ```dart CometChatAIAssistantChatHistory( - onLoad: (list) { - // print("messages loaded: ${list.length}"); - }, + user: user, + loadingStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text('Fetching history...'), + ], + ), + ); + }, ) ``` - - -*** - -##### onEmpty - -Called when the list is empty, enabling custom handling such as showing a placeholder message. +### Example: Custom Empty State ```dart CometChatAIAssistantChatHistory( - onEmpty: () { - // print("Groups empty"); - }, + user: user, + emptyStateView: (context) { + return Center( + child: Text('No history yet. Start a new conversation!'), + ); + }, ) ``` - - -*** - -### Filters - -You can adjust the `MessagesRequestBuilder` in the CometChatAIAssistantChatHistory Widget to customize your list. Numerous options are available to alter the builder to meet your specific needs. For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/flutter/additional-message-filtering). +### Date Separator Pattern -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed +You can modify the date pattern of the chat history date separator using `dateSeparatorPattern`: ```dart CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - messagesRequestBuilder: MessagesRequestBuilder() - ..uid = user.uid + user: user, + dateSeparatorPattern: (DateTime dateTime) { + return DateFormat("dd/MM/yyyy").format(dateTime); + }, ) ``` - - - - -The following parameters in messageRequestBuilder will always be altered inside the list - -1. UID -2. GUID -3. types -4. categories - - - -*** - -### Events - -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The CometChatAIAssistantChatHistory Widget does not emit any events of its own. +## Styling -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the widget in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the widget. - -##### 1. CometChatAIAssistantChatHistoryStyle - -You can set the `style` to the `CometChatAIAssistantChatHistory` Widget to customize the styling. +Customize the appearance of CometChatAIAssistantChatHistory using `CometChatAIAssistantChatHistoryStyle`. ```dart final ccColor = CometChatThemeHelper.getColorPalette(context); + CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. + user: user, style: CometChatAIAssistantChatHistoryStyle( backgroundColor: const Color(0xFFFFFAF6), headerBackgroundColor: const Color(0xFFFFFAF6), headerTitleTextColor: ccColor.textPrimary, headerTitleTextStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts + fontFamily: 'TimesNewRoman', ), newChatIconColor: ccColor.iconSecondary, newChatTextColor: ccColor.textPrimary, @@ -258,176 +355,84 @@ CometChatAIAssistantChatHistory( ), itemTextColor: ccColor.textPrimary, ), -), +) ``` - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - - -```dart -CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - backButton: IconButton( - icon: const Icon( - Icons.ac_unit, - color: Colors.red, - ), - onPressed: () { - // TODO: Implement back button action - }, - ), -), -``` - - - - - -## CometChatMessageList Properties - -Below is a list of customizations along with corresponding code snippets: - -| Property | Data Type | Description | -| --------------------------- | --------------------------------------- | ------------------------------------------------------------- | -| `user` | `User?` | User object for the user message list. | -| `group` | `Group?` | Group object for the group message list. | -| `messagesRequestBuilder` | `MessagesRequestBuilder?` | Custom request builder passed to CometChat's SDK. | -| `loadingStateView` | `WidgetBuilder?` | View for the loading state. | -| `emptyStateView` | `WidgetBuilder?` | View for the empty state. | -| `errorStateView` | `WidgetBuilder?` | View for the error state behind the dialog. | -| `onMessageClicked` | `void Function(BaseMessage? message)?` | Callback triggered when a message is clicked. | -| `onError` | `OnError?` | Callback triggered when an error occurs while fetching users. | -| `onLoad` | `OnLoad?` | Callback triggered when the list is loaded. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `onNewChatButtonClicked` | `VoidCallback?` | Callback triggered when the new chat button is clicked. | -| `style` | `CometChatAIAssistantChatHistoryStyle?` | Sets the style for the AI Assistant chat history. | -| `dateSeparatorPattern` | `String Function(DateTime dateTime)?` | Custom pattern for the date separator. | -| `dateTimeFormatterCallback` | `DateTimeFormatterCallback?` | Callback to format the date and time. | -| `emptyStateText` | `String?` | Text to display when the list is empty. | -| `emptyStateSubtitleText` | `String?` | Subtitle text to display when the list is empty. | -| `errorStateText` | `String?` | Text to display when an error occurs. | -| `errorStateSubtitleText` | `String?` | Subtitle text to display when an error occurs. | -| `onClose` | `VoidCallback?` | Callback triggered when the back button is pressed. | -| `backButton` | `Widget?` | Custom widget for the back button. | -| `width` | `double?` | Sets the width of the list. | -| `height` | `double?` | Sets the height of the list. | -| `hideStickyDate` | `bool?` | Hide the sticky date separator. | -| `hideDateSeparator` | `bool?` | Hide the date separator. | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -#### DateSeparatorPattern - -You can modify the date pattern of the chat history date separator to your requirement using `dateSeparatorPattern`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - -**Example** - -Here is the complete example for reference: - - - -```dart -CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - dateSeparatorPattern: (DateTime dateTime) { - return DateFormat("dd/MM/yyyy").format(dateTime); - }, -) -``` - - - - - -*** - -#### loadingStateView - -Customizes the loading indicator when messages are being fetched. - -Use Cases: - -* Show a spinner or skeleton loader for smooth UX. -* Display a "Fetching history..." text. - - - -```dart -CometChatAIAssistantChatHistory( - loadingStateView: (context) { - // return leading view - }, -) -``` - - - - - -*** - -#### emptyStateView - -Defines a custom view to be displayed when no messages are available. - -Use Cases: - -* Show a friendly message like "No history yet.". - - - -```dart -CometChatAIAssistantChatHistory( - emptyStateView: (context) { - // return empty view - }, -) -``` - - - - - -*** - -#### errorStateView - -Custom error state view displayed when fetching history fails. - -Use Cases: - -* Show a retry button when an error occurs. -* Display a friendly message like "Couldn't load history. Check your connection.". - - - -```dart -CometChatAIAssistantChatHistory( - errorStateView: (context) { - // return error view - }, -) -``` - - - - - -*** \ No newline at end of file +### Style Properties + +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `Color?` | Background color of the message list | +| `border` | `BoxBorder?` | Border of the message list | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius of the message list | +| `emptyStateTextStyle` | `TextStyle?` | Style of empty state text | +| `emptyStateTextColor` | `Color?` | Color of empty state text | +| `emptyStateSubtitleStyle` | `TextStyle?` | Style of empty state subtitle | +| `emptyStateSubtitleColor` | `Color?` | Color of empty state subtitle | +| `errorStateTextStyle` | `TextStyle?` | Style of error state text | +| `errorStateTextColor` | `Color?` | Color of error state text | +| `errorStateSubtitleStyle` | `TextStyle?` | Style of error state subtitle | +| `errorStateSubtitleColor` | `Color?` | Color of error state subtitle | +| `dateSeparatorStyle` | `CometChatDateStyle?` | Style for date separator | +| `newChatIconColor` | `Color?` | Color of new chat icon | +| `newChaTitleStyle` | `TextStyle?` | Style of new chat title | +| `newChatTextColor` | `Color?` | Color of new chat text | +| `itemTextStyle` | `TextStyle?` | Style of item text | +| `itemTextColor` | `Color?` | Color of item text | +| `headerBackgroundColor` | `Color?` | Background color of header | +| `headerTitleTextStyle` | `TextStyle?` | Style of header title text | +| `headerTitleTextColor` | `Color?` | Color of header title text | +| `closeIconColor` | `Color?` | Color of close icon | +| `separatorHeight` | `double?` | Height of separator | +| `separatorColor` | `Color?` | Color of separator | +| `deleteChatHistoryDialogStyle` | `CometChatConfirmDialogStyle?` | Style for delete dialog | + +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `user` | `User?` | `null` | User object for user message list | +| `group` | `Group?` | `null` | Group object for group message list | +| `messagesRequestBuilder` | `MessagesRequestBuilder?` | `null` | Custom request builder | +| `loadingStateView` | `WidgetBuilder?` | `null` | Custom loading view | +| `emptyStateView` | `WidgetBuilder?` | `null` | Custom empty view | +| `errorStateView` | `WidgetBuilder?` | `null` | Custom error view | +| `onMessageClicked` | `void Function(BaseMessage?)?` | `null` | Message click callback | +| `onError` | `OnError?` | `null` | Error callback | +| `onLoad` | `OnLoad?` | `null` | Load callback | +| `onEmpty` | `OnEmpty?` | `null` | Empty callback | +| `onNewChatButtonClicked` | `VoidCallback?` | `null` | New chat button callback | +| `style` | `CometChatAIAssistantChatHistoryStyle?` | `null` | Style configuration | +| `dateSeparatorPattern` | `String Function(DateTime)?` | `null` | Date separator pattern | +| `dateTimeFormatterCallback` | `DateTimeFormatterCallback?` | `null` | Date/time formatter | +| `emptyStateText` | `String?` | `null` | Empty state text | +| `emptyStateSubtitleText` | `String?` | `null` | Empty state subtitle | +| `errorStateText` | `String?` | `null` | Error state text | +| `errorStateSubtitleText` | `String?` | `null` | Error state subtitle | +| `onClose` | `VoidCallback?` | `null` | Close callback | +| `backButton` | `Widget?` | `null` | Custom back button | +| `width` | `double?` | `null` | Widget width | +| `height` | `double?` | `null` | Widget height | +| `hideStickyDate` | `bool?` | `null` | Hide sticky date separator | +| `hideDateSeparator` | `bool?` | `null` | Hide date separator | + + + + Display messages in a conversation + + + Compose and send messages + + + Learn how to customize the look and feel + + + Support multiple languages in your app + + diff --git a/ui-kit/flutter/components-overview.mdx b/ui-kit/flutter/components-overview.mdx index d379c3615..f549bf175 100644 --- a/ui-kit/flutter/components-overview.mdx +++ b/ui-kit/flutter/components-overview.mdx @@ -1,47 +1,207 @@ --- title: "Overview" +description: "Browse all prebuilt UI components in the CometChat Flutter UI Kit — conversations, messages, users, groups, search, and AI." --- -CometChat's **UI Kit** is a set of pre-built UI Widget that allows you to easily craft an in-app chat with all the essential messaging features. + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Required setup | `CometChatUIKit.init()` + `CometChatUIKit.login()` before rendering any component | +| Callback actions | `on: (param) { }` | +| Data filtering | `RequestBuilder: RequestBuilder()` | +| Toggle features | `hide: true` or `show: true` | +| Custom rendering | `View: (context, entity) => Widget` | +| Style overrides | `style: CometChatStyle(...)` | + + + +## Architecture + +The UI Kit is a set of independent widgets that compose into chat layouts. A typical two-panel layout uses four core components: + +- **CometChatConversations** — sidebar listing recent conversations (users and groups) +- **CometChatMessageHeader** — toolbar showing avatar, name, online status, and typing indicator +- **CometChatMessageList** — scrollable message feed with reactions, receipts, and threads +- **CometChatMessageComposer** — rich text input with attachments, mentions, and voice notes + +Data flow: selecting a conversation in CometChatConversations yields a `User` or `Group` object. That object is passed as a prop (`user` or `group`) to CometChatMessageHeader, CometChatMessageList, and CometChatMessageComposer. The message components use the SDK internally — CometChatMessageComposer sends messages, CometChatMessageList receives them via real-time listeners. + +Components communicate through a publish/subscribe event bus (`CometChatMessageEvents`, `CometChatConversationEvents`, `CometChatGroupEvents`, etc.). A component emits events that other components or application code can subscribe to without direct references. See [Events](/ui-kit/flutter/events) for the full list. + +Each component accepts callback props (`on`), view slot props (`View`) for replacing UI sections, `RequestBuilder` props for data filtering, and style class overrides via `CometChatStyle`. + +--- ## Type of Widget -UI Widget based on the behaviour and functionality can be categorized into three types: Base Widget, Widget, and Composite Widget. +UI Widgets based on behavior and functionality can be categorized into three types: Base Widget, Widget, and Composite Widget. ### Base Widget -Base Widget form the building blocks of your app's user interface (UI). They focus solely on presenting visual elements based on input data, without handling any business logic. These Widget provide the foundational appearance and behavior for your UI. +Base Widgets form the building blocks of your app's user interface (UI). They focus solely on presenting visual elements based on input data, without handling any business logic. These widgets provide the foundational appearance and behavior for your UI. ### Widget -Widget build upon Base Widget by incorporating business logic. They not only render UI elements but also manage data loading, execute specific actions, and respond to events. This combination of visual presentation and functional capabilities makes Widget essential for creating dynamic and interactive UIs. +Widgets build upon Base Widgets by incorporating business logic. They not only render UI elements but also manage data loading, execute specific actions, and respond to events. This combination of visual presentation and functional capabilities makes Widgets essential for creating dynamic and interactive UIs. ### Composite Widget -Composite Widget are advanced UI elements that combine multiple Widget or other Composite Widget to achieve complex functionality. By layering Widget together, Composite Widget offer a sophisticated and flexible approach to designing UIs. They enable diverse functionalities and interactions, making them versatile tools for creating rich user experiences. +Composite Widgets are advanced UI elements that combine multiple Widgets or other Composite Widgets to achieve complex functionality. By layering widgets together, Composite Widgets offer a sophisticated and flexible approach to designing UIs. They enable diverse functionalities and interactions, making them versatile tools for creating rich user experiences. + +--- -## Actions +## Component Catalog -Actions direct the operational behavior of a component. They are split into two categories: Predefined Actions and User-Defined Actions. +All components are imported from `cometchat_chat_uikit`. -### Predefined Actions +### Conversations and Lists -These are actions that are inherently programmed into a UI component. They are ingrained in the component itself by default, and they execute automatically in response to user interaction,without needing any additional user input. +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatConversations | Scrollable list of recent conversations | `conversationsRequestBuilder`, `onItemTap`, `onError` | [Conversations](/ui-kit/flutter/conversations) | +| CometChatUsers | Scrollable list of users | `usersRequestBuilder`, `onItemTap`, `onError` | [Users](/ui-kit/flutter/users) | +| CometChatGroups | Scrollable list of groups | `groupsRequestBuilder`, `onItemTap`, `onError` | [Groups](/ui-kit/flutter/groups) | +| CometChatGroupMembers | Scrollable list of group members | `group`, `groupMemberRequestBuilder`, `onItemTap` | [Group Members](/ui-kit/flutter/group-members) | -### User-Defined Actions +### Messages -These are actions that must be explicitly specified by the user. They are not innately part of the component like predefined actions. Instead, they must be developed based on the unique needs of the user or the application. User-defined actions provide adaptability and allow for the creation of custom behaviors that align with the individual needs of the application. +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatMessageHeader | Toolbar with avatar, name, status, typing indicator | `user`, `group`, `backButton`, `hideBackButton` | [Message Header](/ui-kit/flutter/message-header) | +| CometChatMessageList | Scrollable message list with reactions, receipts, threads | `user`, `group`, `messagesRequestBuilder`, `scrollToBottomOnNewMessages` | [Message List](/ui-kit/flutter/message-list) | +| CometChatMessageComposer | Rich text input with attachments, mentions, voice notes | `user`, `group`, `onSendButtonTap`, `placeholderText` | [Message Composer](/ui-kit/flutter/message-composer) | +| CometChatThreadedHeader | Parent message bubble and reply count for threaded view | `parentMessage`, `onClose`, `hideReceipts` | [Threaded Header](/ui-kit/flutter/threaded-messages-header) | -To customize the behavior of a component, actions must be overridden by the user. This provides the user with control over how the component responds to specific events or interactions. +### Search and AI -Both Widget and Composite Widget expose actions to the user, which means that users can interact with these types of Widget through predefined or user-defined actions. On the other hand, Base Widget do not expose actions to the user as they are the foundational building blocks mainly responsible for rendering the user interface and do not carry any business logic or actions. +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatSearch | Real-time search input field | `onSearch`, `placeholder`, `style` | [Search](/ui-kit/flutter/search) | +| CometChatAIAssistantChatHistory | AI assistant conversation history display | `user`, `group`, `style` | [AI Assistant Chat History](/ui-kit/flutter/ai-assistant-chat-history) | -## Events +--- -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. +## Component API Pattern + +All components share a consistent API surface. + +### Actions + +Actions control component behavior. They split into two categories: + +**Predefined Actions** are built into the component and execute automatically on user interaction (e.g., tapping send dispatches the message). No configuration needed. + +**User-Defined Actions** are callback props that fire on specific events. Override them to customize behavior: + + + +```dart +CometChatMessageList( + user: chatUser, + onThreadRepliesClick: (message, context, {bubbleView}) { + openThreadPanel(message); + }, + onError: (error) { + logError(error); + }, +) +``` + + + +### Events + +Events enable decoupled communication between components. A component emits events that other parts of the application can subscribe to without direct references. + + + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// Subscribe to message sent events +CometChatMessageEvents.onMessageSent.listen((message) { + // react to sent message +}); +``` + + + +Each component page documents its emitted events in the Events section. + +### Filters + +List-based components accept `RequestBuilder` props to control which data loads: + + + +```dart +CometChatMessageList( + user: chatUser, + messagesRequestBuilder: MessagesRequestBuilder() + ..limit = 20, +) +``` + + + +### Custom View Slots + +Components expose named view slots to replace sections of the default UI: + + + +```dart +CometChatMessageHeader( + user: chatUser, + titleView: (context, user, group) => CustomTitle(), + subtitleView: (context, user, group) => CustomSubtitle(), + leadingView: (context, user, group) => CustomAvatar(), +) +``` + + + +### Styling + +Every component accepts a style class for customization: + + + +```dart +CometChatMessageList( + user: chatUser, + style: CometChatMessageListStyle( + backgroundColor: Colors.white, + borderRadius: 8, + ), +) +``` + + -Both Widget and Composite Widget have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these Widget allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. +--- ## Configurations -Configurations offer the ability to customize the properties of each individual component within a Composite Component. If a Composite Component includes multiple Widget, each of these Widget will have its own set of properties that can be configured. This means multiple sets of configurations are available, one for each constituent component. This allows for fine-tuned customization of the Composite Component, enabling you to tailor its behavior and appearance to match specific requirements in a granular manner. +Configurations offer the ability to customize the properties of each individual component within a Composite Component. If a Composite Component includes multiple Widgets, each of these Widgets will have its own set of properties that can be configured. This means multiple sets of configurations are available, one for each constituent component. This allows for fine-tuned customization of the Composite Component, enabling you to tailor its behavior and appearance to match specific requirements in a granular manner. + +--- + +## Next Steps + + + + Set up the Flutter UI Kit in your project + + + Customize colors, fonts, and styles + + + Add-on features like polls, stickers, and translation + + + Task-oriented tutorials for common patterns + + diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index d71e86706..be2091653 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -17,64 +17,134 @@ description: "Scrollable list of recent one-on-one and group conversations for t "props": { "data": { "conversationsRequestBuilder": { - "type": "ConversationsRequestBuilder", + "type": "ConversationsRequestBuilder?", "default": "SDK default (30 per page)", "note": "Pass the builder, not the result of .build()" + }, + "conversationsProtocol": { + "type": "ConversationsBuilderProtocol?", + "default": "null", + "note": "Custom protocol for fetching conversations" + }, + "scrollController": { + "type": "ScrollController?", + "default": "null", + "note": "Custom scroll controller for the list" + }, + "title": { + "type": "String?", + "default": "Chats", + "note": "Title text for the app bar" + }, + "controllerTag": { + "type": "String?", + "default": "null", + "note": "Tag for controller management" + }, + "mentionAllLabel": { + "type": "String?", + "default": "null", + "note": "Custom label for @all mentions" + }, + "mentionAllLabelId": { + "type": "String?", + "default": "null", + "note": "Custom label ID for @all mentions" } }, "callbacks": { - "onItemTap": "Function(Conversation conversation)", - "onItemLongPress": "Function(Conversation conversation)", - "onSelection": "Function(List? list)", - "onBack": "VoidCallback", - "onError": "OnError", - "onLoad": "OnLoad", - "onEmpty": "OnEmpty", - "onSearchTap": "GestureTapCallback" + "onItemTap": "Function(Conversation conversation)?", + "onItemLongPress": "Function(Conversation conversation)?", + "onSelection": "Function(List? list)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "onSearchTap": "GestureTapCallback?", + "datePattern": "String Function(Conversation conversation)?", + "dateTimeFormatterCallback": "DateTimeFormatterCallback?" }, "visibility": { - "receiptsVisibility": { "type": "bool", "default": true }, - "usersStatusVisibility": { "type": "bool", "default": true }, - "groupTypeVisibility": { "type": "bool", "default": true }, - "deleteConversationOptionVisibility": { "type": "bool", "default": true }, - "hideAppbar": { "type": "bool", "default": false }, - "hideError": { "type": "bool", "default": false }, - "hideSearch": { "type": "bool", "default": false }, - "showBackButton": { "type": "bool", "default": false } + "receiptsVisibility": { "type": "bool?", "default": true }, + "usersStatusVisibility": { "type": "bool?", "default": true }, + "groupTypeVisibility": { "type": "bool?", "default": true }, + "deleteConversationOptionVisibility": { "type": "bool?", "default": true }, + "hideAppbar": { "type": "bool?", "default": false }, + "hideError": { "type": "bool?", "default": false }, + "hideSearch": { "type": "bool?", "default": false }, + "showBackButton": { "type": "bool", "default": false }, + "dateBackgroundIsTransparent": { "type": "bool?", "default": null }, + "searchReadOnly": { "type": "bool", "default": false } }, "sound": { - "disableSoundForMessages": { "type": "bool", "default": false }, - "customSoundForMessages": { "type": "String", "default": "built-in" } + "disableSoundForMessages": { "type": "bool?", "default": false }, + "customSoundForMessages": { "type": "String?", "default": "built-in" } }, "selection": { "selectionMode": { - "type": "SelectionMode", + "type": "SelectionMode?", "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], "default": "null" }, "activateSelection": { - "type": "ActivateSelection", + "type": "ActivateSelection?", "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], "default": "null" } }, "viewSlots": { - "listItemView": "Widget Function(Conversation conversation)", - "leadingView": "Widget? Function(BuildContext context, Conversation conversation)", - "titleView": "Widget? Function(BuildContext context, Conversation conversation)", - "subtitleView": "Widget? Function(BuildContext context, Conversation conversation)", - "trailingView": "Widget? Function(Conversation conversation)", - "loadingStateView": "WidgetBuilder", - "emptyStateView": "WidgetBuilder", - "errorStateView": "WidgetBuilder", - "setOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)", - "addOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)" + "listItemView": "Widget Function(Conversation conversation)?", + "leadingView": "Widget? Function(BuildContext context, Conversation conversation)?", + "titleView": "Widget? Function(BuildContext context, Conversation conversation)?", + "subtitleView": "Widget? Function(BuildContext context, Conversation conversation)?", + "trailingView": "Widget? Function(Conversation conversation)?", + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "setOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)?", + "addOptions": "List? Function(Conversation, CometChatConversationsController, BuildContext)?" }, "formatting": { "textFormatters": { - "type": "List", + "type": "List?", "default": "default formatters from data source" + }, + "typingIndicatorText": { + "type": "String?", + "default": "typing..." } + }, + "icons": { + "backButton": { "type": "Widget?", "default": "built-in back arrow" }, + "protectedGroupIcon": { "type": "Widget?", "default": "built-in lock icon" }, + "privateGroupIcon": { "type": "Widget?", "default": "built-in lock icon" }, + "readIcon": { "type": "Widget?", "default": "built-in read icon" }, + "deliveredIcon": { "type": "Widget?", "default": "built-in delivered icon" }, + "sentIcon": { "type": "Widget?", "default": "built-in sent icon" }, + "submitIcon": { "type": "Widget?", "default": "built-in check icon" }, + "searchBoxIcon": { "type": "Widget?", "default": "built-in search icon" } + }, + "layout": { + "datePadding": { "type": "EdgeInsets?", "default": "null" }, + "dateHeight": { "type": "double?", "default": "null" }, + "dateWidth": { "type": "double?", "default": "null" }, + "badgeWidth": { "type": "double?", "default": "null" }, + "badgeHeight": { "type": "double?", "default": "null" }, + "badgePadding": { "type": "EdgeInsetsGeometry?", "default": "null" }, + "avatarWidth": { "type": "double?", "default": "null" }, + "avatarHeight": { "type": "double?", "default": "null" }, + "avatarPadding": { "type": "EdgeInsetsGeometry?", "default": "null" }, + "avatarMargin": { "type": "EdgeInsetsGeometry?", "default": "null" }, + "statusIndicatorWidth": { "type": "double?", "default": "null" }, + "statusIndicatorHeight": { "type": "double?", "default": "null" }, + "statusIndicatorBorderRadius": { "type": "BorderRadiusGeometry?", "default": "null" }, + "searchPadding": { "type": "EdgeInsetsGeometry?", "default": "null" }, + "searchContentPadding": { "type": "EdgeInsetsGeometry?", "default": "null" } + }, + "style": { + "conversationsStyle": { "type": "CometChatConversationsStyle", "default": "CometChatConversationsStyle()" }, + "listItemStyle": { "type": "ListItemStyle?", "default": "null" }, + "appBarOptions": { "type": "List?", "default": "null" } } }, "events": [ @@ -87,6 +157,16 @@ description: "Scrollable list of recent one-on-one and group conversations for t "name": "CometChatConversationEvents.ccUpdateConversation", "payload": "Conversation", "description": "Conversation updated" + }, + { + "name": "CometChatConversationEvents.ccMessageRead", + "payload": "BaseMessage", + "description": "Message marked as read" + }, + { + "name": "CometChatConversationEvents.ccMessageSent", + "payload": "BaseMessage, MessageStatus", + "description": "Message sent" } ], "sdkListeners": [ @@ -107,23 +187,35 @@ description: "Scrollable list of recent one-on-one and group conversations for t "onMessageDeleted", "onUserOnline", "onUserOffline", + "ccUserBlocked", "onGroupMemberJoined", "onGroupMemberLeft", "onGroupMemberKicked", "onGroupMemberBanned", "onGroupMemberUnbanned", "onGroupMemberScopeChanged", - "onMemberAddedToGroup" + "onMemberAddedToGroup", + "ccOwnershipChanged", + "ccGroupLeft", + "ccGroupDeleted", + "ccGroupMemberAdded", + "onIncomingCallReceived", + "onOutgoingCallAccepted", + "onOutgoingCallRejected", + "onIncomingCallCancelled", + "onCallEndedMessageReceived", + "onConnected" ], "compositionExample": { "description": "Sidebar conversations wired to message view", "components": [ "CometChatConversations", + "CometChatMessages", "CometChatMessageHeader", "CometChatMessageList", "CometChatMessageComposer" ], - "flow": "onItemTap emits Conversation -> extract User/Group via conversationWith -> pass to MessageHeader, MessageList, MessageComposer" + "flow": "onItemTap emits Conversation -> extract User/Group via conversationWith -> pass to CometChatMessages or individual MessageHeader, MessageList, MessageComposer" }, "types": { "CometChatOption": { @@ -137,6 +229,10 @@ description: "Scrollable list of recent one-on-one and group conversations for t "single": "SelectionMode.single", "multiple": "SelectionMode.multiple", "none": "SelectionMode.none" + }, + "ActivateSelection": { + "onClick": "ActivateSelection.onClick", + "onLongClick": "ActivateSelection.onLongClick" } } } @@ -2034,3 +2130,20 @@ Subscribe using `CometChatConversationEvents.addConversationListListener()` and | Toggle visibility of UI elements | Widget props | `Visibility` boolean props | `receiptsVisibility: false` | | Replace a section of the list item | Widget props | `View` render props | `listItemView: (conversation) => CustomWidget()` | | Change colors, fonts, spacing | Widget props | `conversationsStyle` | `conversationsStyle: CometChatConversationsStyle(backgroundColor: Colors.white)` | + +--- + + + + Display and select from a list of users + + + Display and select from a list of groups + + + Display messages in a conversation + + + Customize the look and feel of components + + diff --git a/ui-kit/flutter/group-members.mdx b/ui-kit/flutter/group-members.mdx index 693396536..b5beb1fb3 100644 --- a/ui-kit/flutter/group-members.mdx +++ b/ui-kit/flutter/group-members.mdx @@ -1,987 +1,1103 @@ --- title: "Group Members" +description: "Displays all members of a group in a searchable, scrollable list with member scope badges and management actions." --- -## Overview + +```json +{ + "component": "CometChatGroupMembers", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Displays all members of a group in a searchable, scrollable list with member scope badges and management actions.", + "primaryOutput": { + "prop": "onItemTap", + "type": "Function(GroupMember groupMember)?" + }, + "props": { + "data": { + "group": { + "type": "Group", + "default": "required", + "note": "The group object to fetch members from" + }, + "groupMembersRequestBuilder": { + "type": "GroupMembersRequestBuilder?", + "default": "null", + "note": "Custom request builder for filtering members" + }, + "groupMembersProtocol": { + "type": "GroupMembersBuilderProtocol?", + "default": "null", + "note": "Custom protocol for fetching group members" + }, + "searchKeyword": { + "type": "String?", + "default": "null", + "note": "Pre-fills search and filters list" + }, + "controllerTag": { + "type": "String?", + "default": "null", + "note": "Tag for controller management" + } + }, + "callbacks": { + "onItemTap": "Function(GroupMember groupMember)?", + "onItemLongPress": "Function(GroupMember groupMember)?", + "onSelection": "Function(List?)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "stateCallBack": "Function(CometChatGroupMembersController controller)?" + }, + "visibility": { + "showBackButton": { "type": "bool", "default": true }, + "hideSearch": { "type": "bool", "default": false }, + "hideSeparator": { "type": "bool?", "default": null }, + "hideError": { "type": "bool?", "default": null }, + "hideAppbar": { "type": "bool?", "default": null }, + "usersStatusVisibility": { "type": "bool?", "default": true }, + "hideKickMemberOption": { "type": "bool?", "default": null }, + "hideBanMemberOption": { "type": "bool?", "default": null }, + "hideScopeChangeOption": { "type": "bool?", "default": null } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode?", + "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], + "default": "null" + }, + "activateSelection": { + "type": "ActivateSelection?", + "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], + "default": "null" + } + }, + "viewSlots": { + "listItemView": "Widget Function(GroupMember)?", + "leadingView": "Widget? Function(BuildContext, GroupMember)?", + "titleView": "Widget? Function(BuildContext, GroupMember)?", + "subtitleView": "Widget? Function(BuildContext, GroupMember)?", + "trailingView": "Function(BuildContext, GroupMember)?", + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "setOptions": "List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?", + "addOptions": "List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?", + "appBarOptions": "List?" + }, + "icons": { + "backButton": { "type": "Widget?", "default": "built-in back arrow" }, + "searchBoxIcon": { "type": "Widget?", "default": "built-in search icon" }, + "submitIcon": { "type": "Widget?", "default": "built-in check icon" }, + "selectIcon": { "type": "Widget?", "default": "built-in selection icon" } + }, + "formatting": { + "searchPlaceholder": { "type": "String?", "default": "null" }, + "height": { "type": "double?", "default": "null" }, + "width": { "type": "double?", "default": "null" } + }, + "style": { + "style": { "type": "CometChatGroupMembersStyle?", "default": "null" } + } + }, + "events": [ + { "name": "CometChatGroupEvents.ccGroupMemberScopeChanged", "payload": "Action, GroupMember, String newScope, String oldScope, Group", "description": "Member scope changed" }, + { "name": "CometChatGroupEvents.ccGroupMemberBanned", "payload": "Action, GroupMember, User bannedBy, Group", "description": "Member banned from group" }, + { "name": "CometChatGroupEvents.ccGroupMemberKicked", "payload": "Action, GroupMember, User kickedBy, Group", "description": "Member kicked from group" } + ], + "sdkListeners": [ + "onGroupMemberScopeChanged", + "onGroupMemberKicked", + "onGroupMemberLeft", + "onGroupMemberBanned", + "onGroupMemberJoined", + "onMemberAddedToGroup", + "onUserOnline", + "onUserOffline" + ], + "compositionExample": { + "description": "Group member list wired to group details or member actions", + "components": [ + "CometChatGroupMembers", + "CometChatGroups", + "CometChatMessages" + ], + "flow": "CometChatGroups emits Group -> pass to CometChatGroupMembers -> onItemTap emits GroupMember for actions" + }, + "types": { + "GroupMember": { + "uid": "String", + "name": "String", + "avatar": "String?", + "scope": "String (owner/admin/moderator/participant)", + "joinedAt": "DateTime?" + }, + "CometChatOption": { + "id": "String?", + "title": "String?", + "icon": "String?", + "iconWidget": "Widget?", + "onClick": "VoidCallback?" + }, + "SelectionMode": { + "single": "SelectionMode.single", + "multiple": "SelectionMode.multiple", + "none": "SelectionMode.none" + } + } +} +``` + -`CometChatGroupMembers` is a versatile [Widget](/ui-kit/flutter/components-overview#components) designed to showcase all users who are either added to or invited to a group, thereby enabling them to participate in group discussions, access shared content, and engage in collaborative activities. `CometChatGroupMembers` have the capability to communicate in real-time through messaging, voice and video calls, and various other interactions. Additionally, they can interact with each other, share files, and join calls based on the permissions established by the group administrator or owner. - - - +## Where It Fits -The `CometChatGroupMembers` widget is composed of the following BaseWidgets: - -| Widgets | Description | -| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [CometChatListBase](/ui-kit/flutter/list-base) | `CometChatListBase` serves as a container widget equipped with a title (navigationBar), search functionality (search-bar), background settings, and a container for embedding a list widget. | -| [CometChatListItem](/ui-kit/flutter/list-item) | This widget renders information extracted from a `User` object onto a tile, featuring a title, subtitle, leading widget, and trailing widget. experience, facilitating seamless navigation and interaction within the widget. | +`CometChatGroupMembers` displays all members of a group with their roles (owner, admin, moderator, participant). It provides member management actions like kick, ban, and scope change. Wire it to `CometChatGroups` to show members when a group is selected. -*** + + +```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -## Usage +class GroupMembersScreen extends StatelessWidget { + final Group group; -### Integration + const GroupMembersScreen({super.key, required this.group}); -`CometChatGroupMembers` , as a Composite Widget, offers flexible integration options, allowing it to be launched directly via button clicks or any user-triggered action. + @override + Widget build(BuildContext context) { + return Scaffold( + body: SafeArea( + child: CometChatGroupMembers( + group: group, + onItemTap: (groupMember) { + // Handle member tap - show profile or actions + print("Tapped: ${groupMember.name}"); + }, + ), + ), + ); + } +} +``` + + -You can launch `CometChatGroupMembers` directly using `Navigator.push` , or you can define it as a widget within the `build` method of your `State` class. + + + -##### 1. Using Navigator to Launch `CometChatGroupMembers` +The `CometChatGroupMembers` widget is composed of the following BaseWidgets: - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatGroupMembers(group: Group(guid: "", name: "", type: "")))); // A group object is required to launch this widget. -``` +| Widgets | Description | +| --- | --- | +| [CometChatListBase](/ui-kit/flutter/list-base) | Container widget with title, search functionality, and background settings | +| [CometChatListItem](/ui-kit/flutter/list-item) | Renders member information with title, subtitle, leading, and trailing widgets | - +--- - -##### 2. Embedding `CometChatGroupMembers` as a Widget in the build Method +## Minimal Render ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class GroupMembers extends StatefulWidget { - const GroupMembers({super.key}); +class GroupMembersDemo extends StatelessWidget { + final Group group; - @override - State createState() => _GroupMembersState(); -} + const GroupMembersDemo({super.key, required this.group}); -class _GroupMembersState extends State { @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), - ) // A group object is required to launch this widget. - ) + body: SafeArea( + child: CometChatGroupMembers( + group: group, + ), + ), ); } } ``` - - -*** +You can also launch it using `Navigator.push`: -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +```dart +Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatGroupMembers( + group: Group(guid: "group_id", name: "Group Name", type: GroupTypeConstants.public), + ), + ), +); +``` -##### 1. onItemTap +--- -This method proves valuable when users seek to override onItemClick functionality within `CometChatGroupMembers` , empowering them with greater control and customization options. +## Filtering Group Members -The `onItemTap` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Pass a `GroupMembersRequestBuilder` to `groupMembersRequestBuilder`. Pass the builder instance — not the result of `.build()`. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - onItemTap: (groupMember) { - // TODO("Not yet implemented") - }, + group: group, + groupMembersRequestBuilder: GroupMembersRequestBuilder(group.guid) + ..limit = 10, ) ``` - - -*** +### Filter Recipes + +| Recipe | Code | +| --- | --- | +| Limit to 10 per page | `GroupMembersRequestBuilder(guid)..limit = 10` | +| Search by keyword | `GroupMembersRequestBuilder(guid)..searchKeyword = "john"` | +| Filter by scopes | `GroupMembersRequestBuilder(guid)..scopes = ["admin", "moderator"]` | + +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. + -##### 2. onItemLongPress +### GroupMembersRequestBuilder Properties -This method becomes invaluable when users seek to override long-click functionality within `CometChatGroupMembers` , offering them enhanced control and flexibility in their interactions. +| Property | Description | Code | +| --- | --- | --- | +| `guid` | Group ID (required) | `GroupMembersRequestBuilder("group_id")` | +| `limit` | Number of members to fetch per request | `..limit = 30` | +| `searchKeyword` | Search members by name | `..searchKeyword = "John"` | +| `scopes` | Filter by member scopes | `..scopes = ["admin"]` | +| `build()` | Builds and returns a `GroupMembersRequest` object | `.build()` | -The `onItemLongPress` action doesn't have a predefined behavior. You can override this action using the following code snippet. +### Custom Protocol Builder + +Use `GroupMembersBuilderProtocol` to customize both the initial list and search results: ```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +class CustomProtocolBuilder extends GroupMembersBuilderProtocol { + const CustomProtocolBuilder(super.builder); + + @override + GroupMembersRequest getRequest() { + return requestBuilder.build(); + } + + @override + GroupMembersRequest getSearchRequest(String val) { + requestBuilder.searchKeyword = val; + return requestBuilder.build(); + } +} + +// Usage CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - onItemLongPress: (groupMember) { - // TODO("Not yet implemented") - }, + group: group, + groupMembersProtocol: CustomProtocolBuilder( + GroupMembersRequestBuilder(group.guid)..scopes = ["admin", "moderator"], + ), ) ``` - - -*** +--- + + +## Actions and Events + +### Callback Props -##### 3. onBack +#### onItemTap -Enhance your application's functionality by leveraging the `onBack` feature. This capability allows you to customize the behavior associated with navigating back within your app. Utilize the provided code snippet to override default behaviors and tailor the user experience according to your specific requirements. +Fires when a member row is tapped. Use for showing member profile or custom actions. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - onBack: () { - // TODO("Not yet implemented") + group: group, + onItemTap: (groupMember) { + print("Selected: ${groupMember.name}"); }, ) ``` - - -*** +#### onItemLongPress -##### 4. onError - -You can customize this behavior by using the provided code snippet to override the `onError` and improve error handling. +Fires when a member row is long-pressed. Useful for showing context menus. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - onError: (e) { - // TODO("Not yet implemented") + group: group, + onItemLongPress: (groupMember) { + // Show custom context menu }, ) ``` - - -*** - -##### 5. onSelection - -When the `onSelection` event is triggered, it furnishes the list of selected members. This event can be invoked by any button or action within the interface. You have the flexibility to implement custom actions or behaviors based on the selected members. +#### onSelection -This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Fires when members are selected in multi-select mode. Requires `selectionMode` to be set. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. + group: group, selectionMode: SelectionMode.multiple, activateSelection: ActivateSelection.onClick, - onSelection: (groupMembersList) { - // TODO("Not yet implemented") + onSelection: (selectedList) { + print("Selected ${selectedList?.length ?? 0} members"); }, ) ``` - - -*** - -##### onLoad +#### onError -Invoked when the list is successfully fetched and loaded, helping track component readiness.. +Fires on internal errors (network failure, auth issue, SDK exception). ```dart CometChatGroupMembers( - onLoad: (list) { - // print("members loaded: ${list.length}"); - }, + group: group, + onError: (error) { + print("CometChatGroupMembers error: $error"); + }, ) ``` - - -*** -##### onEmpty +#### onBack -Called when the list is empty, enabling custom handling such as showing a placeholder message. +Fires when the back button is pressed. ```dart CometChatGroupMembers( - onEmpty: () { - // print("Group Members empty"); - }, + group: group, + showBackButton: true, + onBack: () { + Navigator.pop(context); + }, ) ``` - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a `Widget` . You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. - -##### 1. GroupMembersRequestBuilder +#### onLoad -| Property | Description | Code | -| ------------------ | -------------------------------------------------------- | ------------------------ | -| **GUID** | Group ID for the group whose members are to be fetched. | `guid: String` | -| **Limit** | Number of results to limit the query. | `limit: int?` | -| **Search Keyword** | Keyword for searching members within the group. | `searchKeyword: String?` | -| **Scopes** | List of scopes for filtering members (e.g., moderators). | `scopes: List?` | - -**Example** - -In the example below, we are applying a filter to the Group List based on limit and scope. +Fires when the member list is successfully loaded. ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - groupMembersRequestBuilder: GroupMembersRequestBuilder("") - ..limit = 10 + group: group, + onLoad: (list) { + print("Loaded ${list.length} members"); + }, ) ``` - - -##### 2. GroupMembersProtocol - -The `GroupMembersProtocol` uses [GroupsRequestBuilder](/sdk/flutter/retrieve-groups) enables you to filter and customize the search list based on available parameters in GroupsRequestBuilder. - -This feature allows you to keep uniformity between the displayed Group Members List and Searched Group Members List. - -Here is the complete example for reference: - -**Example** - - - -```dart custom_protocol_builder.dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -class CustomProtocolBuilder extends GroupMembersBuilderProtocol { - const CustomProtocolBuilder(super.builder); - - @override - GroupMembersRequest getRequest() { - return requestBuilder.build(); - } - - @override - GroupMembersRequest getSearchRequest(String val) { - requestBuilder.searchKeyword = val; - return requestBuilder.build(); - } -} -``` - - +#### onEmpty - +Fires when the member list is empty. -```dart main.dart +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - groupMembersProtocol: CustomProtocolBuilder(GroupMembersRequestBuilder("")..searchKeyword = "searchKeyword"), + group: group, + onEmpty: () { + print("No members found"); + }, ) ``` - - -*** - -### Events +### Global UI Events -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget` . By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +`CometChatGroupEvents` emits events subscribable from anywhere in the application. Add a listener in `initState` and remove it in `dispose`. -Events emitted by the Join Group widget is as follows. +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccGroupMemberScopeChanged` | A member's scope is changed | `Action, User, String scopeChangedTo, String scopeChangedFrom, Group` | +| `ccGroupMemberBanned` | A member is banned | `Action, User, User bannedBy, Group` | +| `ccGroupMemberKicked` | A member is kicked | `Action, User, User kickedBy, Group` | -| Event | Description | -| ----------------------------- | ----------------------------------------------------------------- | -| **ccGroupMemberBanned** | Triggers when the group member banned from the group successfully | -| **ccGroupMemberKicked** | Triggers when the group member kicked from the group successfully | -| **ccGroupMemberScopeChanged** | Triggers when the group member scope is changed in the group | +When to use: sync external UI with member changes. For example, update a member count badge when a member is kicked. -**Example** -```dart your_screen.dart +```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:cometchat_sdk/models/action.dart' as cc; -import 'package:flutter/material.dart'; - -class YourScreen extends StatefulWidget { - const YourScreen({super.key}); - - @override - State createState() => _YourScreenState(); -} class _YourScreenState extends State with CometChatGroupEventListener { @override void initState() { super.initState(); - CometChatGroupEvents.addGroupsListener("listenerId", this); // Add the listener + CometChatGroupEvents.addGroupsListener("listenerId", this); } @override - void dispose(){ + void dispose() { + CometChatGroupEvents.removeGroupsListener("listenerId"); super.dispose(); - CometChatGroupEvents.removeGroupsListener("listenerId"); // Remove the listener } @override void ccGroupMemberScopeChanged(cc.Action message, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { - // TODO("Not yet implemented") + print("${updatedUser.name} scope changed to $scopeChangedTo"); } @override void ccGroupMemberBanned(cc.Action message, User bannedUser, User bannedBy, Group bannedFrom) { - // TODO("Not yet implemented") + print("${bannedUser.name} was banned from ${bannedFrom.name}"); } @override void ccGroupMemberKicked(cc.Action message, User kickedUser, User kickedBy, Group kickedFrom) { - // TODO("Not yet implemented") + print("${kickedUser.name} was kicked from ${kickedFrom.name}"); } @override Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - -*** +### SDK Events (Real-Time, Automatic) -## Customization +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -To fit your app's design requirements, you can customize the appearance of the Groups widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberScopeChanged` | Updates member scope badge | +| `onGroupMemberKicked` | Removes member from list | +| `onGroupMemberLeft` | Removes member from list | +| `onGroupMemberBanned` | Removes member from list | +| `onGroupMemberJoined` | Adds new member to list | +| `onMemberAddedToGroup` | Adds new member to list | +| `onUserOnline` | Updates online status indicator | +| `onUserOffline` | Updates offline status indicator | -### Style - -You can set the `CometChatGroupMembersStyle` to the `CometChatGroupMembers` Widget to customize the styling. - - - -```dart -CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - style: CometChatGroupMembersStyle( - titleStyle: TextStyle(color: Color(0xFFF76808)), - separatorColor: Color(0xFFF76808), - ownerMemberScopeBackgroundColor: Color(0xFFF76808), - adminMemberScopeBackgroundColor: Color(0xFFFEEDE1), - adminMemberScopeBorder: Border.all(color: Color(0xFFF76808)), - adminMemberScopeTextColor: Color(0xFFF76808), - moderatorMemberScopeBackgroundColor: Color(0xFFFEEDE1), - moderatorMemberScopeTextColor: Color(0xFFF76808), - backIconColor: Color(0xFFF76808), - ), -) -``` +--- - - +## Custom View Slots - - - +Each slot replaces a section of the default UI. Slots that accept a member parameter receive the `GroupMember` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `listItemView` | `Widget Function(GroupMember)` | Entire list item row | +| `leadingView` | `Widget? Function(BuildContext, GroupMember)` | Avatar / left section | +| `titleView` | `Widget? Function(BuildContext, GroupMember)` | Member name | +| `subtitleView` | `Widget? Function(BuildContext, GroupMember)` | Secondary text | +| `trailingView` | `Function(BuildContext, GroupMember)` | Scope badge / right section | +| `loadingStateView` | `WidgetBuilder` | Loading spinner | +| `emptyStateView` | `WidgetBuilder` | Empty state | +| `errorStateView` | `WidgetBuilder` | Error state | +| `setOptions` | `List? Function(Group, GroupMember, Controller, BuildContext)` | Context menu actions (replaces default) | +| `addOptions` | `List? Function(Group, GroupMember, Controller, BuildContext)` | Context menu actions (adds to default) | +| `appBarOptions` | `List` | App bar action widgets | -### Functionality +### listItemView -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Replace the entire list item row. - + ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - hideSeparator: true, - hideSearch: true, - showBackButton: false + group: group, + listItemView: (groupMember) { + return ListTile( + leading: CometChatAvatar( + image: groupMember.avatar, + name: groupMember.name, + ), + title: Text(groupMember.name ?? ''), + subtitle: Text(groupMember.scope ?? 'participant'), + trailing: Icon(Icons.chevron_right), + ); + }, ) ``` - - -## List of properties exposed by `CometChatGroupMembers` - -| Property | Data Type | Description | -| ---------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | -| `groupMembersProtocol` | `GroupMembersBuilderProtocol?` | Custom request builder protocol for fetching group members. | -| `groupMembersRequestBuilder` | `GroupMembersRequestBuilder?` | Custom request builder for fetching group members. | -| `subtitleView` | `Widget? Function(BuildContext, GroupMember)?` | Widget to set subtitle for each group member. | -| `hideSeparator` | `bool?` | Toggle visibility of separator. | -| `listItemView` | `Widget Function(GroupMember)?` | Custom view for each group member item. | -| `style` | `CometChatGroupMembersStyle?` | Sets style for \[CometChatGroupMembers]. | -| `controller` | `ScrollController?` | Sets controller for the list. | -| `options` | `List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?` | Options visible at the slide of each group member. | -| `searchPlaceholder` | `String?` | Placeholder text for the search input. | -| `backButton` | `Widget?` | Widget for the back button in the app bar. | -| `showBackButton` | `bool` | Flag to show/hide the back button. | -| `searchBoxIcon` | `Widget?` | Widget for the search box icon. | -| `hideSearch` | `bool` | Flag to show/hide the search input box. | -| `selectionMode` | `SelectionMode?` | Specifies mode group members module is opening in. | -| `onSelection` | `Function(List?)?` | Callback for handling group member selection. | -| `loadingStateView` | `WidgetBuilder?` | View displayed during loading state. | -| `emptyStateView` | `WidgetBuilder?` | View displayed when the list is empty. | -| `errorStateView` | `WidgetBuilder?` | View displayed when an error occurs. | -| `hideError` | `bool?` | Toggle visibility of error dialog. | -| `stateCallBack` | `Function(CometChatGroupMembersController)?` | Callback to access controller functions from the parent. | -| `appBarOptions` | `List?` | Options available in the app bar. | -| `group` | `Group` | Group object passed to fetch members. | -| `trailingView` | `Function(BuildContext, GroupMember)?` | Custom widget for the trailing section of the group member list item. | -| `submitIcon` | `Widget?` | Widget for the submit icon. | -| `selectIcon` | `Widget?` | Widget for the selection icon. | -| `onBack` | `VoidCallback?` | Callback triggered when going back. | -| `onItemTap` | `Function(GroupMember)?` | Callback triggered when tapping a group member item. | -| `onItemLongPress` | `Function(GroupMember)?` | Callback triggered on long press of a group member item. | -| `activateSelection` | `ActivateSelection?` | Lets the widget know if group members can be selected. | -| `onError` | `OnError?` | Callback for handling errors. | -| `height` | `double?` | Height of the widget. | -| `width` | `double?` | Width of the widget. | -| `controllerTag` | `String?` | Tag for accessing the widget's GetXController. | -| `hideAppbar` | `bool?` | Flag to hide the app bar. | -| `searchKeyword` | `String?` | Keyword to fetch the initial list with. | -| `onLoad` | `OnLoad?` | Callback triggered when the list is loaded. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `leadingStateView` | `Widget? Function(BuildContext, GroupMember)?` | Widget for the leading section of each group member. | -| `titleView` | `Widget? Function(BuildContext, GroupMember)?` | Custom title view for each group member. | -| `usersStatusVisibility` | `bool?` | Controls visibility of the user status indicator on the avatar (default: true). | -| `hideBanMemberOption` | `bool?` | Flag to hide the ban member option. | -| `hideKickMemberOption` | `bool?` | Flag to hide the kick member option. | -| `hideScopeChangeOption` | `bool?` | Flag to hide the scope change option. | -| `setOptions` | `List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?` | List of actions available on long press of group member item. | -| `addOptions` | `List? Function(Group, GroupMember, CometChatGroupMembersController, BuildContext)?` | Adds to the current list of actions on long press of a group member item. | - -*** - -### Advanced - -For advanced-level customization, you can set custom widgets to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widgets and then incorporate those into the widget. - -The `CometChatGroupMembers` widget does not provide additional functionalities beyond this level of customization. - -#### setOptions - -Defines a set of available actions that users can perform when they interact with a group member item. - -* Provide actions like "View Profile", "Send Message", "Remove from Group". -* Restrict certain actions to admins (e.g., "Promote to Admin", "Ban User"). - -By customizing these options, developers can provide a streamlined and contextually relevant user experience + +### leadingView + +Replace the avatar / left section. Online status indicator example. ```dart CometChatGroupMembers( - setOptions: (group, groupMember, controller, context) { - // return options + group: group, + leadingView: (context, groupMember) { + return Stack( + children: [ + CometChatAvatar( + image: groupMember.avatar, + name: groupMember.name, + style: CometChatAvatarStyle(borderRadius: BorderRadius.circular(20)), + ), + Positioned( + bottom: 0, + right: 0, + child: Container( + width: 12, + height: 12, + decoration: BoxDecoration( + color: groupMember.status == "online" ? Color(0xFF09C26F) : Colors.grey, + shape: BoxShape.circle, + border: Border.all(color: Colors.white, width: 2), + ), + ), + ), + ], + ); }, ) ``` - - -*** - -#### addOptions +### titleView -Adds custom actions to the existing options available when interacting with a group member. - -* Extend functionality by adding "Block User", "Report User", or "View Activity". -* Customize actions based on member roles. +Replace the member name. Role badge inline example. ```dart CometChatGroupMembers( - addOptions: (group, groupMember, controller, context) { - // return options + group: group, + titleView: (context, groupMember) { + return Row( + children: [ + Text( + groupMember.name ?? '', + style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16), + ), + if (groupMember.scope == GroupMemberScope.owner) ...[ + SizedBox(width: 4), + Icon(Icons.star, size: 16, color: Color(0xFFF76808)), + ], + ], + ); }, ) ``` - - -*** -#### loadingStateView +### subtitleView -Displays a custom loading view while group members are being fetched. +Replace the secondary text. Join date example. -* Show a loading spinner with "Fetching group members...". -* Implement a skeleton loader for a smoother UI experience. + + + ```dart CometChatGroupMembers( - loadingStateView: (context) { - // return loading view + group: group, + subtitleView: (context, groupMember) { + final dateTime = groupMember.joinedAt ?? DateTime.now(); + return Text( + "Joined ${DateFormat('dd/MM/yyyy').format(dateTime)}", + style: TextStyle(color: Color(0xFF727272), fontSize: 14), + ); }, ) ``` - - -*** - -#### emptyStateView +### trailingView -Configures a view to be displayed when no group members are found. +Replace the scope badge / right section. Custom scope badge example. -* Display a message like "No members in this group yet.". -* Show a button to Invite Members. + + + ```dart CometChatGroupMembers( - emptyStateView: (context) { - // return empty view + group: group, + trailingView: (context, groupMember) { + Color backgroundColor = Color(0xFFEDEAFA); + Color textColor = Color(0xFF6852D6); + String scope = groupMember.scope ?? GroupMemberScope.participant; + + if (groupMember.uid == group.owner) { + scope = GroupMemberScope.owner; + backgroundColor = Color(0xFF6852D6); + textColor = Colors.white; + } + + return Container( + padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.circular(1000), + ), + child: Text( + scope.capitalizeFirst ?? "", + style: TextStyle(color: textColor, fontSize: 12, fontWeight: FontWeight.w400), + ), + ); }, ) ``` - - -*** -#### errorStateView +### setOptions -Defines a custom error state view when there is an issue loading group members. - -* Display a retry button with "Failed to load members. Tap to retry.". -* Show an illustration for a better user experience. +Replace the context menu / long-press actions on each member item. ```dart CometChatGroupMembers( - errorStateView: (context) { - // return error view + group: group, + setOptions: (group, groupMember, controller, context) { + return [ + CometChatOption( + id: "view_profile", + title: "View Profile", + iconWidget: Icon(Icons.person_outline), + onClick: () { + // Navigate to member profile + }, + ), + CometChatOption( + id: "message", + title: "Send Message", + iconWidget: Icon(Icons.message_outlined), + onClick: () { + // Start direct message + }, + ), + ]; }, ) ``` - - -*** - -#### leadingView - -Sets a custom leading view for each group member item, usually used for profile images or avatars. +### addOptions -* Show a circular avatar with an online/offline indicator. -* Add a role-based badge (Admin, Moderator, Member). +Add to the existing context menu actions without removing defaults. ```dart CometChatGroupMembers( - leadingView: (context, groupMember) { - // return leading view - }, + group: group, + addOptions: (group, groupMember, controller, context) { + return [ + CometChatOption( + id: "report", + title: "Report User", + iconWidget: Icon(Icons.flag_outlined), + onClick: () { + // Report user logic + }, + ), + ]; + }, ) ``` - - -*** - -#### titleView +### appBarOptions -Customizes the title view, typically displaying the member's name. +Add custom widgets to the app bar. -* Customize fonts, colors, or styles for usernames. -* Add role-specific indicators like "(Group Admin)". + + + ```dart CometChatGroupMembers( - titleView: (context, groupMember) { - // return title view - }, + group: group, + appBarOptions: [ + IconButton( + onPressed: () { + // Navigate to add members + }, + icon: Icon(Icons.person_add_alt_1, color: Color(0xFF6852D6)), + ), + ], ) ``` - - -*** -#### ListItemView +### loadingStateView -With this function, you can assign a custom ListItem to the `CometChatGroupMembers` Widget. +Custom view displayed while members are being fetched. -```dart widget +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - listItemView: (groupMember) { - return Placeholder(); // Replace this placeholder with your custom widget. + group: group, + loadingStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + CircularProgressIndicator(), + SizedBox(height: 16), + Text("Loading members..."), + ], + ), + ); }, ) ``` - - -Here is the complete example for reference: - -**Example** +### emptyStateView -You can indeed create a custom widget named `custom_list_item.dart` for more complex or unique list items. +Custom view displayed when no members are found. -```dart custom_list_item.dart - Widget _getTailView(GroupMember groupMember, Group group) { - Color? backgroundColor; - BoxBorder? border; - String scope = groupMember.scope ?? GroupMemberScope.participant; - Color? textColor; - TextStyle? textStyle; - - if (groupMember.uid == group.owner) { - scope = GroupMemberScope.owner; - backgroundColor = Color(0xFF6852D6); - textColor = Colors.white; - } else if (scope == GroupMemberScope.admin) { - backgroundColor = Color(0xFFEDEAFA); - border = Border.all(color: Color(0xFF6852D6), width: 1); - textColor = Color(0xFF6852D6); - } else if (scope == GroupMemberScope.moderator) { - backgroundColor = Color(0xFFEDEAFA); - textColor = Color(0xFF6852D6); - } else { - return const SizedBox(); - } - - return Container( - alignment: Alignment.center, - padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4 ?? 0), - decoration: BoxDecoration( - color: backgroundColor, - border: border, - borderRadius: BorderRadius.circular(1000), - ), - child: Text( - scope.capitalizeFirst ?? "", - style: TextStyle( - fontSize: 12, fontWeight: FontWeight.w400, color: textColor) - .merge(textStyle) - .copyWith(color: textColor), +```dart +CometChatGroupMembers( + group: group, + emptyStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.people_outline, size: 64, color: Color(0xFF727272)), + SizedBox(height: 16), + Text("No members found"), + ], ), ); - } - - Widget getCustomListItemView( - GroupMember member, - Group group, - BuildContext context, - ) { - Widget? subtitle; - Widget? tail; - Color? backgroundColor; - Widget? icon; - - tail = _getTailView(member, group); - - StatusIndicatorUtils statusIndicatorUtils = - StatusIndicatorUtils.getStatusIndicatorFromParams( - context: context, - groupMember: member, - onlineStatusIndicatorColor: Color(0xFF09C26F), - usersStatusVisibility: true, - ); - - backgroundColor = statusIndicatorUtils.statusIndicatorColor; - icon = statusIndicatorUtils.icon; - - return Padding( - padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16), - child: CometChatListItem( - id: member.uid, - avatarName: member.name, - avatarURL: member.avatar, - title: member.name, - key: UniqueKey(), - subtitleView: subtitle, - tailView: tail, - avatarStyle: const CometChatAvatarStyle( - borderRadius: BorderRadius.all(Radius.circular(12)), - ), - avatarHeight: 40, - avatarWidth: 40, - statusIndicatorColor: backgroundColor, - statusIndicatorIcon: icon, - hideSeparator: true, - style: ListItemStyle( - background: Colors.transparent, - titleStyle: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF141414)), - )), - ); - } -``` - - - - - - - -```dart main.dart -CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - listItemView: (member) { - return getCustomListItemView(member, controller.group!, context); - }, + }, ) ``` - - - - - - -*** +### errorStateView -#### SubtitleView - -You can customize the subtitle view for each item to meet your specific preferences and needs. +Custom view displayed when an error occurs. -```dart widget +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - subtitleView: (context, groupMember) { - return Placeholder(); // Replace this placeholder with your custom widget. + group: group, + errorStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.error_outline, size: 64, color: Colors.red), + SizedBox(height: 16), + Text("Failed to load members"), + ElevatedButton( + onPressed: () { + // Retry logic + }, + child: Text("Retry"), + ), + ], + ), + ); }, ) ``` - - -Here is the complete example for reference: +--- + + +## Styling -**Example** +Set `CometChatGroupMembersStyle` to customize the appearance. -```dart main.dart +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - subtitleView: (context, member) { - String subtitle = ""; - - final dateTime = member.joinedAt ?? DateTime.now(); - subtitle = "Joined at ${DateFormat('dd/MM/yyyy').format(dateTime)}"; - - return Text(subtitle, - style: TextStyle( - color: Color(0xFF727272), - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ); - }, + group: group, + style: CometChatGroupMembersStyle( + titleStyle: TextStyle(color: Color(0xFFF76808)), + separatorColor: Color(0xFFF76808), + ownerMemberScopeBackgroundColor: Color(0xFFF76808), + adminMemberScopeBackgroundColor: Color(0xFFFEEDE1), + adminMemberScopeBorder: Border.all(color: Color(0xFFF76808)), + adminMemberScopeTextColor: Color(0xFFF76808), + moderatorMemberScopeBackgroundColor: Color(0xFFFEEDE1), + moderatorMemberScopeTextColor: Color(0xFFF76808), + backIconColor: Color(0xFFF76808), + ), ) ``` - - - + -*** +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of the component | +| `border` | `BoxBorder?` | Border for the widget | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius for the widget | +| `titleStyle` | `TextStyle?` | Style for the header title | +| `backIconColor` | `Color?` | Back button icon color | +| `searchBackground` | `Color?` | Background color of search box | +| `searchBorderRadius` | `BorderRadius?` | Border radius for search box | +| `searchTextStyle` | `TextStyle?` | Style for search input text | +| `searchPlaceholderStyle` | `TextStyle?` | Style for search placeholder | +| `searchIconColor` | `Color?` | Search icon color | +| `loadingIconColor` | `Color?` | Loading indicator color | +| `emptyStateTextStyle` | `TextStyle?` | Style for empty state title | +| `emptyStateSubtitleTextStyle` | `TextStyle?` | Style for empty state subtitle | +| `errorStateTextStyle` | `TextStyle?` | Style for error state title | +| `errorStateSubtitleStyle` | `TextStyle?` | Style for error state subtitle | +| `onlineStatusColor` | `Color?` | Online status indicator color | +| `separatorColor` | `Color?` | Color of list item separators | +| `separatorHeight` | `double?` | Height of list item separators | +| `listPadding` | `EdgeInsetsGeometry?` | Padding for the list | +| `ownerMemberScopeBackgroundColor` | `Color?` | Background color for owner scope badge | +| `ownerMemberScopeTextColor` | `Color?` | Text color for owner scope badge | +| `ownerMemberScopeBorder` | `BoxBorder?` | Border for owner scope badge | +| `ownerMemberScopeTextStyle` | `TextStyle?` | Text style for owner scope badge | +| `adminMemberScopeBackgroundColor` | `Color?` | Background color for admin scope badge | +| `adminMemberScopeTextColor` | `Color?` | Text color for admin scope badge | +| `adminMemberScopeBorder` | `BoxBorder?` | Border for admin scope badge | +| `adminMemberScopeTextStyle` | `TextStyle?` | Text style for admin scope badge | +| `moderatorMemberScopeBackgroundColor` | `Color?` | Background color for moderator scope badge | +| `moderatorMemberScopeTextColor` | `Color?` | Text color for moderator scope badge | +| `moderatorMemberScopeBorder` | `BoxBorder?` | Border for moderator scope badge | +| `moderatorMemberScopeTextStyle` | `TextStyle?` | Text style for moderator scope badge | +| `checkboxCheckedBackgroundColor` | `Color?` | Background color for checked checkbox | +| `checkboxBackgroundColor` | `Color?` | Background color for unchecked checkbox | +| `checkboxSelectedIconColor` | `Color?` | Color for checkbox icon when selected | +| `checkboxBorder` | `BorderSide?` | Border for checkbox | +| `checkboxBorderRadius` | `BorderRadiusGeometry?` | Border radius for checkbox | +| `listItemSelectedBackgroundColor` | `Color?` | Background color for selected list item | +| `submitIconColor` | `Color?` | Color for submit icon | +| `retryButtonBackgroundColor` | `Color?` | Background color for retry button | +| `retryButtonTextColor` | `Color?` | Text color for retry button | +| `retryButtonTextStyle` | `TextStyle?` | Text style for retry button | +| `retryButtonBorder` | `BorderSide?` | Border for retry button | +| `retryButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius for retry button | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for member avatars | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle?` | Style for status indicators | +| `listItemStyle` | `ListItemStyle?` | Style for list items | +| `confirmDialogStyle` | `CometChatConfirmDialogStyle?` | Style for confirmation dialogs | +| `changeScopeStyle` | `CometChatChangeScopeStyle?` | Style for change scope dialog | +| `optionsBackgroundColor` | `Color?` | Background color for options menu | +| `optionsIconColor` | `Color?` | Color for options icon | +| `optionsTextStyle` | `TextStyle?` | Text style for options | + +--- + -#### AppBarOptions +## Common Patterns -You can set the Custom `appBarOptions` to the `CometChatGroupMembers` widget. +### Hide member management options -```dart widget +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - appBarOptions: [ - Placeholder(), - Placeholder(), - Placeholder() - ] // Replace this list of placeholder widgets with your list of custom widgets. + group: group, + hideKickMemberOption: true, + hideBanMemberOption: true, + hideScopeChangeOption: true, ) ``` - - -Here is the complete example for reference: - -**Example** +### Multi-select with selection callback ```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - appBarOptions: [ - IconButton( - onPressed: () {}, - icon: Icon( - Icons.person_add_alt_1, - color: Color(0xFF6852D6), - ), - ), - ], // Replaced the list of placeholder widgets with a list of custom widgets. + group: group, + selectionMode: SelectionMode.multiple, + activateSelection: ActivateSelection.onClick, + onSelection: (selectedMembers) { + if (selectedMembers != null && selectedMembers.isNotEmpty) { + print("Selected ${selectedMembers.length} members"); + // Perform batch action on selected members + } + }, ) ``` - - - - - - -*** - -#### trailingView - -Used to generate a custom trailing widget for the `CometChatGroupMembers` widget. You can add a Tail widget using the following method. +### Hide all chrome — minimal list -```dart widget +```dart CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - trailingView: (context, groupMembers) { - return Placeholder(); // Replace this placeholder with your custom widget. - }, + group: group, + hideSearch: true, + hideAppbar: true, + hideSeparator: true, ) ``` - - -Here is the complete example for reference: - -**Example** +### Filter admins and moderators only -```dart main.dart - CometChatGroupMembers( - group: Group(guid: "", name: "", type: ""), // A group object is required to launch this widget. - trailingView: (context, groupMember) { - Color? backgroundColor = Color(0xFFEDEAFA); - BoxBorder? border = Border.all(color: Color(0xFF6852D6), width: 1); - String scope = groupMember.scope ?? GroupMemberScope.participant; - Color? textColor = Color(0xFF6852D6); - - if (groupMember.uid == group.owner){ - scope = GroupMemberScope.owner; - } - - return Container( - alignment: Alignment.center, - padding: EdgeInsets.symmetric( - horizontal: 12, vertical:4 ?? 0), - decoration: BoxDecoration( - color: backgroundColor, - border: border, - borderRadius: - BorderRadius.circular(1000), - ), - child: Text( - scope.capitalizeFirst ?? "", - style:TextStyle( - fontSize: 12, - fontWeight: FontWeight.w400, - color: textColor) - ), - ); - }, - ); +```dart +CometChatGroupMembers( + group: group, + groupMembersRequestBuilder: GroupMembersRequestBuilder(group.guid) + ..scopes = [GroupMemberScope.admin, GroupMemberScope.moderator], +) ``` - - - - - +--- + + +## Props Reference + +| Prop | Type | Default | Description | +| --- | --- | --- | --- | +| `group` | `Group` | **required** | The group object to fetch members from | +| `groupMembersProtocol` | `GroupMembersBuilderProtocol?` | `null` | Custom request builder protocol | +| `groupMembersRequestBuilder` | `GroupMembersRequestBuilder?` | `null` | Custom request builder for filtering members | +| `searchKeyword` | `String?` | `null` | Pre-fills search and filters list | +| `controllerTag` | `String?` | `null` | Tag for controller management | +| `onSelection` | `Function(List?)?` | `null` | Callback when members are selected | +| `onItemTap` | `Function(GroupMember)?` | `null` | Callback on tapping a member item | +| `onItemLongPress` | `Function(GroupMember)?` | `null` | Callback on long pressing a member item | +| `onBack` | `VoidCallback?` | `null` | Callback on closing this screen | +| `onError` | `OnError?` | `null` | Callback in case any error occurs | +| `onLoad` | `OnLoad?` | `null` | Callback when list is fetched and loaded | +| `onEmpty` | `OnEmpty?` | `null` | Callback when the list is empty | +| `stateCallBack` | `Function(CometChatGroupMembersController)?` | `null` | Access controller functions from parent | +| `showBackButton` | `bool` | `true` | Show/hide back button | +| `hideSearch` | `bool` | `false` | Show/hide search input | +| `hideSeparator` | `bool?` | `null` | Toggle visibility of separator | +| `hideError` | `bool?` | `null` | Toggle visibility of error dialog | +| `hideAppbar` | `bool?` | `null` | Hides the appbar | +| `usersStatusVisibility` | `bool?` | `true` | Hide status indicator on avatar | +| `hideKickMemberOption` | `bool?` | `null` | Hide kick member option | +| `hideBanMemberOption` | `bool?` | `null` | Hide ban member option | +| `hideScopeChangeOption` | `bool?` | `null` | Hide scope change option | +| `selectionMode` | `SelectionMode?` | `null` | Selection mode (single/multiple/none) | +| `activateSelection` | `ActivateSelection?` | `null` | When to activate selection | +| `subtitleView` | `Widget? Function(BuildContext, GroupMember)?` | `null` | Custom subtitle for each member | +| `listItemView` | `Widget Function(GroupMember)?` | `null` | Custom view for each member | +| `trailingView` | `Function(BuildContext, GroupMember)?` | `null` | Custom trailing widget | +| `leadingView` | `Widget? Function(BuildContext, GroupMember)?` | `null` | Custom leading view | +| `titleView` | `Widget? Function(BuildContext, GroupMember)?` | `null` | Custom title view | +| `loadingStateView` | `WidgetBuilder?` | `null` | View for loading state | +| `emptyStateView` | `WidgetBuilder?` | `null` | View for empty state | +| `errorStateView` | `WidgetBuilder?` | `null` | View for error state | +| `backButton` | `Widget?` | `null` | Custom back button widget | +| `searchBoxIcon` | `Widget?` | `null` | Custom search icon | +| `selectIcon` | `Widget?` | `null` | Custom selection icon | +| `submitIcon` | `Widget?` | `null` | Custom selection complete icon | +| `appBarOptions` | `List?` | `null` | App bar options | +| `options` | `List? Function(...)?` | `null` | Options visible at slide of each member | +| `setOptions` | `List? Function(...)?` | `null` | Replace default long press actions | +| `addOptions` | `List? Function(...)?` | `null` | Add to default long press actions | +| `searchPlaceholder` | `String?` | `null` | Placeholder text of search input | +| `height` | `double?` | `null` | Height of the widget | +| `width` | `double?` | `null` | Width of the widget | +| `style` | `CometChatGroupMembersStyle?` | `null` | Style for the component | +| `controller` | `ScrollController?` | `null` | Scroll controller for the list | + +--- + -*** + + + Display and manage available groups + + + Add new members to a group + + + View and manage banned members + + + Learn how to customize the look and feel + + \ No newline at end of file diff --git a/ui-kit/flutter/groups.mdx b/ui-kit/flutter/groups.mdx index a613f6f0f..6c79bfe4c 100644 --- a/ui-kit/flutter/groups.mdx +++ b/ui-kit/flutter/groups.mdx @@ -1,169 +1,347 @@ --- title: "Groups" +description: "Searchable, scrollable list of all available groups with icon, name, member count, and group type indicator." --- -## Overview - -`CometChatGroups` functions as a standalone [Widget](/ui-kit/flutter/components-overview#components) designed to create a screen displaying a list of groups, with the added functionality of enabling users to search for specific groups. Acting as a container widget, `CometChatGroups` encapsulates and formats the `CometChatListBase` and `CometChatGroupList` widgets without introducing any additional behavior of its own. - - - - + +```json +{ + "component": "CometChatGroups", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Searchable, scrollable list of all available groups with icon, name, member count, and group type indicator.", + "primaryOutput": { + "prop": "onItemTap", + "type": "Function(BuildContext context, Group group)?" + }, + "props": { + "data": { + "groupsRequestBuilder": { + "type": "GroupsRequestBuilder?", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "groupsProtocol": { + "type": "GroupsBuilderProtocol?", + "default": "null", + "note": "Custom protocol for fetching groups" + }, + "scrollController": { + "type": "ScrollController?", + "default": "null", + "note": "Custom scroll controller for the list" + }, + "title": { + "type": "String?", + "default": "Groups", + "note": "Title text for the app bar" + }, + "controllerTag": { + "type": "String?", + "default": "null", + "note": "Tag for controller management" + }, + "searchPlaceholder": { + "type": "String?", + "default": "null", + "note": "Placeholder text for search input" + }, + "searchKeyword": { + "type": "String?", + "default": "null", + "note": "Pre-fills search and filters list" + }, + "height": { + "type": "double?", + "default": "null" + }, + "width": { + "type": "double?", + "default": "null" + } + }, + "callbacks": { + "onItemTap": "Function(BuildContext context, Group group)?", + "onItemLongPress": "Function(BuildContext context, Group group)?", + "onSelection": "Function(List?)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "stateCallBack": "Function(CometChatGroupsController controller)?" + }, + "visibility": { + "groupTypeVisibility": { "type": "bool?", "default": true }, + "hideAppbar": { "type": "bool?", "default": false }, + "hideError": { "type": "bool?", "default": false }, + "hideSearch": { "type": "bool", "default": false }, + "showBackButton": { "type": "bool", "default": true } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode?", + "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], + "default": "null" + }, + "activateSelection": { + "type": "ActivateSelection?", + "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], + "default": "null" + } + }, + "viewSlots": { + "listItemView": "Widget Function(Group group)?", + "leadingView": "Widget? Function(BuildContext context, Group group)?", + "titleView": "Widget? Function(BuildContext context, Group group)?", + "subtitleView": "Widget? Function(BuildContext context, Group group)?", + "trailingView": "Widget? Function(BuildContext context, Group group)?", + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "setOptions": "List? Function(Group, CometChatGroupsController, BuildContext)?", + "addOptions": "List? Function(Group, CometChatGroupsController, BuildContext)?", + "appBarOptions": "List Function(BuildContext context)?" + }, + "icons": { + "backButton": { "type": "Widget?", "default": "built-in back arrow" }, + "searchBoxIcon": { "type": "Widget?", "default": "built-in search icon" }, + "submitIcon": { "type": "Widget?", "default": "built-in check icon" }, + "passwordGroupIcon": { "type": "Widget?", "default": "built-in lock icon" }, + "privateGroupIcon": { "type": "Widget?", "default": "built-in shield icon" } + }, + "style": { + "groupsStyle": { "type": "CometChatGroupsStyle?", "default": "null" } + } + }, + "events": [ + { "name": "CometChatGroupEvents.ccGroupCreated", "payload": "Group", "description": "Group created" }, + { "name": "CometChatGroupEvents.ccGroupDeleted", "payload": "Group", "description": "Group deleted" }, + { "name": "CometChatGroupEvents.ccGroupLeft", "payload": "Action, User, Group", "description": "User left group" }, + { "name": "CometChatGroupEvents.ccGroupMemberJoined", "payload": "User, Group", "description": "User joined group" }, + { "name": "CometChatGroupEvents.ccGroupMemberAdded", "payload": "List, List, Group, User", "description": "Members added" }, + { "name": "CometChatGroupEvents.ccGroupMemberKicked", "payload": "Action, User, User, Group", "description": "Member kicked" }, + { "name": "CometChatGroupEvents.ccGroupMemberBanned", "payload": "Action, User, User, Group", "description": "Member banned" }, + { "name": "CometChatGroupEvents.ccGroupMemberUnbanned", "payload": "Action, User, User, Group", "description": "Member unbanned" }, + { "name": "CometChatGroupEvents.ccGroupMemberScopeChanged", "payload": "Action, User, String, String, Group", "description": "Member scope changed" }, + { "name": "CometChatGroupEvents.ccOwnershipChanged", "payload": "Group, GroupMember", "description": "Ownership transferred" } + ], + "sdkListeners": [ + "onGroupMemberJoined", + "onGroupMemberLeft", + "onMemberAddedToGroup", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onGroupMemberScopeChanged", + "onConnected" + ], + "compositionExample": { + "description": "Group directory wired to message view", + "components": [ + "CometChatGroups", + "CometChatMessages", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemTap emits Group -> pass to CometChatMessages or individual message components" + }, + "types": { + "CometChatOption": { + "id": "String?", + "title": "String?", + "icon": "String?", + "iconWidget": "Widget?", + "onClick": "VoidCallback?" + }, + "SelectionMode": { + "single": "SelectionMode.single", + "multiple": "SelectionMode.multiple", + "none": "SelectionMode.none" + }, + "ActivateSelection": { + "onClick": "ActivateSelection.onClick", + "onLongClick": "ActivateSelection.onLongClick" + } + } +} +``` + -The `CometChatGroups` widget is composed of the following BaseWidget: -| Widgets | Description | -| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [CometChatListBase](/ui-kit/flutter/list-base) | `CometChatListBase` serves as a container widget equipped with a title (navigationBar), search functionality (search-bar), background settings, and a container for embedding a list view. | -| [CometChatListItem](/ui-kit/flutter/list-item) | This widget renders information extracted from a `Group` object onto a tile, featuring a title, subtitle, leading view, and trailing view. | +## Where It Fits -## Usage +`CometChatGroups` is a directory list widget. It renders available groups and emits the selected `Group` via `onItemTap`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a group chat layout. -### Integration + + +```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -As `CometChatGroups` is a custom **widget**, it can be launched directly by user actions such as button clicks or other interactions. +class GroupChatApp extends StatefulWidget { + const GroupChatApp({super.key}); -You can launch `CometChatGroups` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. + @override + State createState() => _GroupChatAppState(); +} -##### 1. Using Navigator to Launch `CometChatGroups` +class _GroupChatAppState extends State { + Group? selectedGroup; - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => const CometChatGroups())); + @override + Widget build(BuildContext context) { + return Scaffold( + body: Row( + children: [ + SizedBox( + width: 400, + child: CometChatGroups( + onItemTap: (context, group) { + setState(() { + selectedGroup = group; + }); + }, + ), + ), + Expanded( + child: selectedGroup != null + ? CometChatMessages(group: selectedGroup) + : const Center(child: Text('Select a group')), + ), + ], + ), + ); + } +} ``` - - -##### 2. Embedding `CometChatGroups` as a Widget in the build Method + + + + +--- + + +## Minimal Render ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class Groups extends StatefulWidget { - const Groups({super.key}); - - @override - State createState() => _GroupsState(); -} - -class _GroupsState extends State { +class GroupsDemo extends StatelessWidget { + const GroupsDemo({super.key}); @override Widget build(BuildContext context) { return const Scaffold( - body: SafeArea( - child: CometChatGroups() - ) + body: SafeArea( + child: CometChatGroups(), + ), ); } } ``` - - -*** +You can also launch it using `Navigator.push`: -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +```dart +Navigator.push( + context, + MaterialPageRoute(builder: (context) => const CometChatGroups()) +); +``` -##### 1. onItemTap +--- -This method proves valuable when users seek to override onItemTap functionality within CometChatGroups, empowering them with greater control and customization options. +## Filtering Groups -The `onItemTap` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Pass a `GroupsRequestBuilder` to `groupsRequestBuilder`. Pass the builder instance — not the result of `.build()`. ```dart CometChatGroups( - onItemTap: (context, group) { - // TODO("Not yet implemented") - }, + groupsRequestBuilder: GroupsRequestBuilder() + ..joinedOnly = true + ..limit = 10, ) ``` - - -*** +### Filter Recipes -##### 2. onBack +| Recipe | Code | +| --- | --- | +| Joined groups only | `GroupsRequestBuilder()..joinedOnly = true` | +| Limit to 10 per page | `GroupsRequestBuilder()..limit = 10` | +| Search by keyword | `GroupsRequestBuilder()..searchKeyword = "design"` | +| Filter by tags | `GroupsRequestBuilder()..tags = ["vip"]` | +| With tags data | `GroupsRequestBuilder()..withTags = true` | -Enhance your application's functionality by leveraging the `onBack` feature. This capability allows you to customize the behavior associated with navigating back within your app. Utilize the provided code snippet to override default behaviors and tailor the user experience according to your specific requirements. +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. - - -```dart -CometChatGroups( - onBack: () { - // TODO("Not yet implemented") - }, -) -``` - +### GroupsRequestBuilder Properties - +| Property | Description | Code | +| --- | --- | --- | +| `limit` | Number of groups to fetch per request. | `..limit = 30` | +| `searchKeyword` | Search groups by name. | `..searchKeyword = "Team"` | +| `joinedOnly` | Fetch only joined groups. Default `false`. | `..joinedOnly = true` | +| `tags` | Filter groups by specific tags. | `..tags = ["vip"]` | +| `withTags` | Include tags in the Group object. Default `false`. | `..withTags = true` | +| `build()` | Builds and returns a `GroupsRequest` object. | `.build()` | -*** +Refer to [GroupsRequestBuilder](/sdk/flutter/retrieve-groups) for the full builder API. -##### 3. onError +--- + +## Actions and Events + +### Callback Props + +#### onItemTap -You can customize this behavior by using the provided code snippet to override the `onError` and improve error handling. +Fires when a group row is tapped. Primary navigation hook — set the active group and render the message view. ```dart CometChatGroups( - onError: (e) { - // TODO("Not yet implemented") + onItemTap: (context, group) { + print("Selected: ${group.name}"); }, ) ``` - - -*** - -##### 4. onItemLongPress +#### onItemLongPress -This method becomes invaluable when users seek to override long-click functionality within CometChatGroups, offering them enhanced control and flexibility in their interactions. - -The `onItemLongPress` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Fires when a group row is long-pressed. Useful for showing context menus or custom actions. ```dart CometChatGroups( onItemLongPress: (context, group) { - // TODO("Not yet implemented") + // Show custom context menu }, ) ``` - - -*** - -##### 5. onSelection +#### onSelection -When the `onSelection` event is triggered, it furnishes the list of selected groups. This event can be invoked by any button or action within the interface. You have the flexibility to implement custom actions or behaviors based on the selected groups. - -This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Fires when groups are selected in multi-select mode. Requires `selectionMode` to be set. @@ -171,648 +349,1149 @@ This action does not come with any predefined behavior. However, you have the fl CometChatGroups( selectionMode: SelectionMode.multiple, activateSelection: ActivateSelection.onClick, - onSelection: (groupList) { - // TODO("Not yet implemented") - } + onSelection: (selectedList) { + print("Selected ${selectedList?.length ?? 0} groups"); + }, ) ``` - - -*** -##### onLoad +#### onError -Invoked when the list is successfully fetched and loaded, helping track component readiness. +Fires on internal errors (network failure, auth issue, SDK exception). ```dart CometChatGroups( - onLoad: (list) { - // print("Groups loaded: ${list.length}"); - }, + onError: (error) { + print("CometChatGroups error: $error"); + }, ) ``` - - -*** - -##### onEmpty +#### onBack -Called when the list is empty, enabling custom handling such as showing a placeholder message. +Fires when the back button is pressed. ```dart CometChatGroups( - onEmpty: () { - // print("Groups empty"); - }, + showBackButton: true, + onBack: () { + Navigator.pop(context); + }, ) ``` - - -*** +#### onLoad -### Filters +Fires when the group list is successfully loaded. -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. + + +```dart +CometChatGroups( + onLoad: (list) { + print("Loaded ${list.length} groups"); + }, +) +``` + + -##### 1. GroupsRequestBuilder +#### onEmpty -The [GroupsRequestBuilder](/sdk/flutter/retrieve-groups) enables you to filter and customize the group list based on available parameters in GroupsRequestBuilder. This feature allows you to create more specific and targeted queries when fetching groups. The following are the parameters available in [GroupsRequestBuilder](/sdk/flutter/retrieve-groups) +Fires when the group list is empty. ```dart CometChatGroups( - groupsRequestBuilder: GroupsRequestBuilder() - ..limit = 10 + onEmpty: () { + print("No groups found"); + }, ) ``` - - -| Property | Description | Code | -| ------------------ | --------------------------------------------------------- | ----------------------- | -| **Joined Only** | Flag to include only joined groups. Defaults to `false`. | `joinedOnly: bool` | -| **Limit** | Number of results to limit the query. | `limit: int` | -| **Search Keyword** | Keyword for searching groups. | `searchKeyword: String` | -| **Tags** | Tags for filtering groups. | `tags: List` | -| **With Tags** | Flag to include tags in the results. Defaults to `false`. | `withTags: bool` | - -*** +### Global UI Events -### Events +`CometChatGroupEvents` emits events subscribable from anywhere in the application. Add a listener in `initState` and remove it in `dispose`. -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `CometChatGroups` Widget. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccGroupCreated` | A new group is created | `Group` | +| `ccGroupDeleted` | A group is deleted | `Group` | +| `ccGroupLeft` | A user leaves a group | `Action, User, Group` | +| `ccGroupMemberJoined` | A user joins a group | `User, Group` | +| `ccGroupMemberAdded` | Members are added to a group | `List, List, Group, User` | +| `ccGroupMemberKicked` | A member is kicked | `Action, User, User, Group` | +| `ccGroupMemberBanned` | A member is banned | `Action, User, User, Group` | +| `ccGroupMemberUnbanned` | A member is unbanned | `Action, User, User, Group` | +| `ccGroupMemberScopeChanged` | A member's scope changes | `Action, User, String, String, Group` | +| `ccOwnershipChanged` | Group ownership is transferred | `Group, GroupMember` | -The list of events emitted by the `CometChatGroups` widget is as follows. +When to use: sync external UI with group state changes. For example, update a group count badge when a group is created or deleted. -| Events | Description | -| --------------------------- | -------------------------------------------------------------------------------------------------------- | -| `ccGroupCreated` | This gets triggered when the logged in user creates a group. | -| `ccGroupDeleted` | This gets triggered when the logged in user deletes a group. | -| `ccGroupLeft` | This gets triggered when the logged in user leaves a group. | -| `ccGroupMemberScopeChanged` | This gets triggered when the logged in user changes the scope of another group member. | -| `ccGroupMemberBanned` | This gets triggered when the logged in user bans a group member from the group. | -| `ccGroupMemberKicked` | This gets triggered when the logged in user kicks another group member from the group. | -| `ccGroupMemberUnbanned` | This gets triggered when the logged in user unbans a user banned from the group. | -| `ccGroupMemberJoined` | This gets triggered when the logged in user joins a group. | -| `ccGroupMemberAdded` | This gets triggered when the logged in user adds new members to the group. | -| `ccOwnershipChanged` | This gets triggered when the logged in user transfers the ownership of their group to some other member. | -```dart your_screen.dart +```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:cometchat_sdk/models/action.dart' as cc; -import 'package:flutter/material.dart'; - -class YourScreen extends StatefulWidget { - const YourScreen({super.key}); - - @override - State createState() => _YourScreenState(); -} class _YourScreenState extends State with CometChatGroupEventListener { @override void initState() { super.initState(); - CometChatGroupEvents.addGroupsListener("listenerId", this); // Add the listener + CometChatGroupEvents.addGroupsListener("listenerId", this); } @override - void dispose(){ + void dispose() { + CometChatGroupEvents.removeGroupsListener("listenerId"); super.dispose(); - CometChatGroupEvents.removeGroupsListener("listenerId"); // Remove the listener } - @override void ccGroupCreated(Group group) { - // TODO("Not yet implemented") + print("Group created: ${group.name}"); } @override void ccGroupDeleted(Group group) { - // TODO("Not yet implemented") + print("Group deleted: ${group.name}"); } @override void ccGroupLeft(cc.Action message, User leftUser, Group leftGroup) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberScopeChanged(cc.Action message, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberBanned(cc.Action message, User bannedUser, User bannedBy, Group bannedFrom) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberKicked(cc.Action message, User kickedUser, User kickedBy, Group kickedFrom) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberUnbanned(cc.Action message, User unbannedUser, User unbannedBy, Group unbannedFrom) { - // TODO("Not yet implemented") + print("User ${leftUser.name} left ${leftGroup.name}"); } @override void ccGroupMemberJoined(User joinedUser, Group joinedGroup) { - // TODO("Not yet implemented") - } - - @override - void ccGroupMemberAdded(List messages, List usersAdded, Group groupAddedIn, User addedBy) { - // TODO("Not yet implemented") + print("User ${joinedUser.name} joined ${joinedGroup.name}"); } @override void ccOwnershipChanged(Group group, GroupMember newOwner) { - // TODO("Not yet implemented") + print("Ownership of ${group.name} transferred to ${newOwner.name}"); } @override Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - -*** - -## Customization +### SDK Events (Real-Time, Automatic) -To fit your app's design requirements, you can customize the appearance of the groups widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -### Style +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberJoined` | Updates member count, sets `hasJoined` if current user joined | +| `onGroupMemberLeft` | Updates member count | +| `onMemberAddedToGroup` | Updates member count, adds group to list if current user was added | +| `onGroupMemberKicked` | Updates member count | +| `onGroupMemberBanned` | Updates member count | +| `onGroupMemberScopeChanged` | Updates member scope | -Enhance your `CometChatGroups` Widget by setting the `CometChatGroupsStyle` to customize its appearance. +Automatic: group membership changes, member count updates. - - -```dart -CometChatGroups( - groupsStyle: CometChatGroupsStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleTextColor: Color(0xFFF76808), - separatorColor: Color(0xFFF76808), - ), -) -``` +--- - - +## Custom View Slots - - - +Each slot replaces a section of the default UI. Slots that accept a group parameter receive the `Group` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `listItemView` | `Widget Function(Group)` | Entire list item row | +| `leadingView` | `Widget? Function(BuildContext, Group)` | Avatar / left section | +| `titleView` | `Widget? Function(BuildContext, Group)` | Name / title text | +| `subtitleView` | `Widget? Function(BuildContext, Group)` | Member count subtitle | +| `trailingView` | `Widget? Function(BuildContext, Group)` | Right section | +| `loadingStateView` | `WidgetBuilder` | Loading spinner | +| `emptyStateView` | `WidgetBuilder` | Empty state | +| `errorStateView` | `WidgetBuilder` | Error state | +| `setOptions` | `List? Function(Group, Controller, BuildContext)` | Context menu actions (replaces default) | +| `addOptions` | `List? Function(Group, Controller, BuildContext)` | Context menu actions (adds to default) | +| `appBarOptions` | `List Function(BuildContext)` | App bar action widgets | -### Functionality +### listItemView -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Replace the entire list item row. - + ```dart CometChatGroups( - title: "Your Title", - backButton: Icon(Icons.add_alert, color: Color(0xFF6851D6)), - searchPlaceholder: "Search Group", + listItemView: (group) { + return ListTile( + title: Text( + group.name, + style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500), + ), + subtitle: Text( + "${group.membersCount} Members • ${group.description}", + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: Color(0xFF727272)), + ), + trailing: ElevatedButton( + onPressed: () { + CometChat.joinGroup( + group.guid, + group.type, + onSuccess: (group) { + // Handle success + }, + onError: (error) { + // Handle error + }, + ); + }, + style: ElevatedButton.styleFrom( + backgroundColor: Color(0xFFEDEAFA), + elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(1000)), + ), + child: Text("JOIN", style: TextStyle(color: Color(0xFF6852D6), fontSize: 12)), + ), + ); + }, ) ``` - - -## List of properties exposed by `CometChatGroups` - -| Property | Data Type | Description | -| ---------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------- | -| `groupsProtocol` | `GroupsBuilderProtocol?` | Custom groups request builder protocol. | -| `groupsRequestBuilder` | `GroupsRequestBuilder?` | Custom request builder for fetching groups. | -| `subtitleView` | `Widget? Function(BuildContext, Group)?` | Widget to set subtitle for each group item. | -| `listItemView` | `Widget Function(Group)?` | Custom view for each group item. | -| `groupsStyle` | `CometChatGroupsStyle?` | Styling options for the groups list. | -| `scrollController` | `ScrollController?` | Controller for scrolling the list. | -| `searchPlaceholder` | `String?` | Placeholder text for the search input box. | -| `backButton` | `Widget?` | Widget for the back button in the app bar. | -| `showBackButton` | `bool` | Flag to show/hide the back button. | -| `searchBoxIcon` | `Widget?` | Widget for the search box icon. | -| `hideSearch` | `bool` | Flag to show/hide the search input box. | -| `selectionMode` | `SelectionMode?` | Mode defining how groups can be selected. | -| `onSelection` | `Function(List?)?` | Callback for handling group selection. | -| `title` | `String?` | Title of the widget. | -| `stateCallBack` | `Function(CometChatGroupsController)?` | Callback to access controller functions. | -| `hideError` | `bool?` | Toggle visibility of error dialog. | -| `loadingStateView` | `WidgetBuilder?` | View displayed during loading state. | -| `emptyStateView` | `WidgetBuilder?` | View displayed when the list is empty. | -| `errorStateView` | `WidgetBuilder?` | View displayed when an error occurs. | -| `appBarOptions` | `List Function(BuildContext)?` | Options available in the app bar. | -| `passwordGroupIcon` | `Widget?` | Widget for password-protected group icon. | -| `privateGroupIcon` | `Widget?` | Widget for private group icon. | -| `activateSelection` | `ActivateSelection?` | Controls whether selection is allowed. | -| `onBack` | `VoidCallback?` | Callback triggered when going back. | -| `onItemTap` | `Function(BuildContext, Group)?` | Callback triggered when tapping a group. | -| `onItemLongPress` | `Function(BuildContext, Group)?` | Callback triggered on long press of a group. | -| `onError` | `OnError?` | Callback for handling errors. | -| `submitIcon` | `Widget?` | Widget for displaying the submit icon. | -| `hideAppbar` | `bool` | Flag to show/hide the app bar. | -| `controllerTag` | `String?` | Identifier tag for controller management. | -| `height` | `double?` | Height of the widget. | -| `width` | `double?` | Width of the widget. | -| `searchKeyword` | `String?` | Keyword used to fetch initial group list. | -| `onLoad` | `OnLoad?` | Callback triggered when the list loads. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `groupTypeVisibility` | `bool` | Hide the group type icon visible on the group icon. | -| `setOptions` | `List? Function(Group, CometChatGroupsController, BuildContext)?` | Actions available on long-press of a group. | -| `addOptions` | `List? Function(Group, CometChatGroupsController, BuildContext)?` | Additional long-press actions for groups. | -| `titleView` | `Widget? Function(BuildContext, Group)?` | Custom title view for each group. | -| `leadingView` | `Widget? Function(BuildContext, Group)?` | Widget for the leading section of each group. | -| `trailingView` | `Widget? Function(BuildContext, Group)?` | Widget for the trailing section of each group. | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -*** - -#### setOptions - -This method sets a predefined list of actions that users can perform when they long press a user in the list. These options typically include: - -* Enable actions like "Mute Notifications", "Leave Group", "Pin Group". -* Provide admin-only actions like "Manage Members", "Delete Group". - -By customizing these options, developers can provide a streamlined and contextually relevant user experience + +### leadingView + +Replace the avatar / left section. Joined status badge example. ```dart CometChatGroups( - setOptions: (group, controller, context) { - // return options + leadingView: (context, group) { + return Stack( + children: [ + CometChatAvatar( + image: group.icon, + name: group.name, + style: CometChatAvatarStyle(borderRadius: BorderRadius.circular(8)), + ), + if (group.hasJoined) + Positioned( + bottom: -2, + left: 0, + right: 0, + child: Container( + padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2), + decoration: BoxDecoration(color: Color(0xFF09C26F)), + child: Text( + "Joined", + textAlign: TextAlign.center, + style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600), + ), + ), + ), + ], + ); }, ) ``` - - -*** - -#### addOptions - -This method extends the existing set of actions available when users long press a group item. Unlike setOptionsDefines, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: - -* Adding a "Report Spam" action -* Introducing a "Save to Notes" option -* Integrating third-party actions such as "Share to Cloud Storage" +### titleView -This method provides flexibility in modifying user interaction capabilities. +Replace the name / title text. Group type badge inline example. ```dart CometChatGroups( - addOptions: (group, controller, context) { - // return options + titleView: (context, group) { + return Row( + children: [ + Text( + group.name, + style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16), + ), + SizedBox(width: 4), + Container( + padding: EdgeInsets.symmetric(horizontal: 4, vertical: 2), + decoration: BoxDecoration( + color: group.type == GroupTypeConstants.public + ? Color(0xFF0B7BEA) + : Color(0xFF09C26F), + borderRadius: BorderRadius.circular(7), + ), + child: Text( + group.type, + style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600), + ), + ), + ], + ); }, ) ``` - - -*** - -#### loadingStateView +### subtitleView -Configures a custom loading view displayed while groups are being fetched. +Replace the member count subtitle text. -* Show a spinner with "Loading groups..." text. -* Display a skeleton loader for a smooth UI experience. + + + ```dart CometChatGroups( - loadingStateView: (context) { - // return loading view + subtitleView: (context, group) { + return Text( + "${group.membersCount} Members • ${group.description ?? 'No description'}", + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 14, color: Color(0xFF727272)), + ); }, ) ``` - - -*** - -#### emptyStateView -Defines a view that appears when no groups are available. +### trailingView -* Show a message like "No groups found, create one now!". -* Display an illustration with a "Create New Group" button. +Replace the right section. Join status button example. ```dart CometChatGroups( - emptyStateView: (context) { - // return empty view + trailingView: (context, group) { + return Container( + padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), + decoration: BoxDecoration( + color: Color(0xFFEDEAFA), + borderRadius: BorderRadius.circular(1000), + ), + child: Text( + group.hasJoined ? "JOINED" : "+ JOIN", + style: TextStyle(color: Color(0xFF6852D6), fontSize: 12, fontWeight: FontWeight.w700), + ), + ); }, ) ``` - - -*** - -#### errorStateView +### setOptions -Configures the UI when an error occurs while fetching groups. - -* Display a retry button with "Failed to load groups, try again.". -* Show a friendly error illustration. +Replace the context menu / long-press actions on each group item. ```dart CometChatGroups( - errorStateView: (context) { - // return error view + setOptions: (group, controller, context) { + return [ + CometChatOption( + id: "leave", + title: "Leave Group", + icon: AssetConstants.close, + onClick: () { + CometChat.leaveGroup(group.guid, onSuccess: (response) { + print("Left group"); + }, onError: (error) { + print("Error: $error"); + }); + }, + ), + CometChatOption( + id: "view_members", + title: "View Members", + iconWidget: Icon(Icons.people_outline), + onClick: () { + // Navigate to group members + }, + ), + ]; }, ) ``` - - -*** - -#### leadingView - -Sets a custom leading view that appears at the start of each group item. +### addOptions -* Display the group profile picture. -* Add an icon indicating Public or Private groups. +Add to the existing context menu actions without removing defaults. ```dart CometChatGroups( - leadingView: (context, group) { - // return leading view - }, + addOptions: (group, controller, context) { + return [ + CometChatOption( + id: "mute", + title: "Mute Notifications", + iconWidget: Icon(Icons.notifications_off_outlined), + onClick: () { + // Mute notifications logic + }, + ), + CometChatOption( + id: "pin", + title: "Pin Group", + iconWidget: Icon(Icons.push_pin_outlined), + onClick: () { + // Pin group logic + }, + ), + ]; + }, ) ``` - - -*** -#### titleView +### appBarOptions -Customizes the title view of each group item, which typically displays the group name. +Add custom widgets to the app bar. -* Style group names with custom fonts and colors. -* Show a verified badge for official groups. + + + ```dart CometChatGroups( - titleView: (context, group) { - // return title view - }, + appBarOptions: (context) => [ + IconButton( + onPressed: () { + // Navigate to create group + }, + icon: Icon(Icons.group_add, color: Color(0xFF6852D6)), + ), + ], ) ``` - - -*** - -#### trailingView +--- -Allows custom elements to be added at the end of each group item, such as buttons or indicators. +## Styling -* Show unread message counts. -* Add a quick Join or Leave button. +Set `CometChatGroupsStyle` to customize the appearance. ```dart CometChatGroups( - trailingView: (context, group) { - // return trailing view - }, + groupsStyle: CometChatGroupsStyle( + backgroundColor: Colors.white, + titleTextColor: Color(0xFFF76808), + separatorColor: Color(0xFFF76808), + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + ), ) ``` - - -*** + + + + +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color` | Background color of the component | +| `border` | `Border` | Border for the widget | +| `borderRadius` | `BorderRadiusGeometry` | Border radius for the widget | +| `titleTextColor` | `Color` | Color of the header title | +| `titleTextStyle` | `TextStyle` | Style for the header title | +| `backIconColor` | `Color` | Back button icon color | +| `searchBackgroundColor` | `Color` | Background color of search box | +| `searchBorder` | `BorderSide` | Border for search box | +| `searchBorderRadius` | `BorderRadius` | Border radius for search box | +| `searchPlaceHolderTextColor` | `Color` | Placeholder text color in search | +| `searchPlaceHolderTextStyle` | `TextStyle` | Placeholder text style in search | +| `searchIconColor` | `Color` | Search icon color | +| `searchInputTextColor` | `Color` | Search input text color | +| `searchInputTextStyle` | `TextStyle` | Search input text style | +| `separatorColor` | `Color` | Color of list item separators | +| `separatorHeight` | `double` | Height of list item separators | +| `itemTitleTextColor` | `Color` | Color of group name in list items | +| `itemTitleTextStyle` | `TextStyle` | Style for group name in list items | +| `itemSubtitleTextColor` | `Color` | Color of member count subtitle | +| `itemSubtitleTextStyle` | `TextStyle` | Style for member count subtitle | +| `listItemSelectedBackgroundColor` | `Color` | Background color for selected items | +| `privateGroupIconBackground` | `Color` | Background color for private group icon | +| `protectedGroupIconBackground` | `Color` | Background color for password group icon | +| `emptyStateTextColor` | `Color` | Text color for empty state title | +| `emptyStateTextStyle` | `TextStyle` | Text style for empty state title | +| `emptyStateSubTitleTextColor` | `Color` | Text color for empty state subtitle | +| `emptyStateSubTitleTextStyle` | `TextStyle` | Text style for empty state subtitle | +| `errorStateTextColor` | `Color` | Text color for error state title | +| `errorStateTextStyle` | `TextStyle` | Text style for error state title | +| `errorStateSubTitleTextColor` | `Color` | Text color for error state subtitle | +| `errorStateSubTitleTextStyle` | `TextStyle` | Text style for error state subtitle | +| `retryButtonBackgroundColor` | `Color` | Background color for retry button | +| `retryButtonBorderRadius` | `BorderRadius` | Border radius for retry button | +| `retryButtonBorder` | `BorderSide` | Border for retry button | +| `retryButtonTextColor` | `Color` | Text color for retry button | +| `retryButtonTextStyle` | `TextStyle` | Text style for retry button | +| `submitIconColor` | `Color` | Color of submit icon in selection mode | +| `checkBoxBackgroundColor` | `Color` | Background color of unchecked checkbox | +| `checkBoxCheckedBackgroundColor` | `Color` | Background color of checked checkbox | +| `checkboxSelectedIconColor` | `Color` | Color of checkmark icon | +| `checkBoxBorderRadius` | `BorderRadius` | Border radius for checkbox | +| `checkBoxBorder` | `BorderSide` | Border for checkbox | +| `avatarStyle` | `CometChatAvatarStyle` | Style for group avatars | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle` | Style for group type indicators | + +--- + -#### ListItemView +## Common Patterns -With this function, you can assign a custom ListItem to the `CometChatGroups` Widget. +### Custom empty state with CTA ```dart CometChatGroups( - listItemView: (group) { - return Placeholder(); // Replace this placeholder with your custom widget. + emptyStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.group_outlined, size: 64, color: Color(0xFF727272)), + SizedBox(height: 16), + Text("No groups found", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500)), + SizedBox(height: 8), + ElevatedButton( + onPressed: () { + // Navigate to create group + }, + child: Text("Create a Group"), + ), + ], + ), + ); }, ) ``` - - -**Example** - -Here is the complete example for reference: +### Joined groups only ```dart - CometChatGroups( - listItemView: (group) { - return ListTile( - title: Text( - group.name, - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w500, - ), - ), - subtitle: Text( - "${group.membersCount} Members • ${group.description}", - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w400, - color: Color(0XFF727272), - ), - ), - trailing: ElevatedButton( - onPressed: () { - CometChat.joinGroup( - group.guid, - group.type, - onSuccess: (group) { - //handle success, for example, show a toast or navigate to a new screen - }, - onError: (excep) { - //handle exception, for example, show an error toast or dialog - }, - ); - }, - child: Text( - "JOIN", - style: TextStyle( - color: Color(0xFF6852D6), - fontSize: 12, - fontWeight: FontWeight.w500, - letterSpacing: 0), - ), - style: ElevatedButton.styleFrom( - backgroundColor: Color(0xFFEDEAFA), - elevation: 0, - padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), - visualDensity: VisualDensity.compact, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(1000), - ), - )), - ); - }, - ); +CometChatGroups( + groupsRequestBuilder: GroupsRequestBuilder() + ..joinedOnly = true, +) ``` - - - - - - -*** - -#### SubtitleView - -You can customize the subtitle view for each item to meet your specific preferences and needs. +### Multi-select with selection callback ```dart CometChatGroups( - subtitleView: (context, group) { - return Text( - "${group.membersCount} Members • ${group.description}", - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w400, - color: Color(0XFF727272), - ), - ); + selectionMode: SelectionMode.multiple, + activateSelection: ActivateSelection.onClick, + onSelection: (selectedGroups) { + if (selectedGroups != null && selectedGroups.isNotEmpty) { + print("Selected ${selectedGroups.length} groups"); + // Perform batch action on selected groups + } }, ) ``` - - - - - - -*** - -#### AppBarOptions - -You can set the Custom `appBarOptions` to the `CometChatGroups` widget. +### Hide all chrome — minimal list ```dart CometChatGroups( - appBarOptions: (context) { - return [ - IconButton( - onPressed: () {}, - icon: Icon( - Icons.group_add, - color: Color(0xFF6852D6), - ), - ), - ]; - }, + hideSearch: true, + hideAppbar: true, + groupTypeVisibility: false, ) ``` - - - - - +--- + +## Accessibility + +The component renders a scrollable list of interactive items. Each group row supports: + +- Tap gesture for selection/navigation +- Long-press gesture for context menu actions +- Checkbox selection in multi-select mode with proper touch targets +- Group type indicators (public/private/password) with visual icons + +For screen readers: +- Group names are readable as list item titles +- Group type indicators use icons — consider adding `Semantics` widgets via `leadingView` if screen reader descriptions are needed +- Selection state is communicated through checkbox widgets + +The component respects system accessibility settings including text scaling and high contrast modes. + +--- + + +## Props + +All props are optional unless noted. + +### activateSelection + +Controls when selection mode activates. + +| | | +| --- | --- | +| Type | `ActivateSelection` | +| Default | `null` | + +Values: `ActivateSelection.onClick`, `ActivateSelection.onLongClick` + +--- + +### addOptions + +Adds additional context menu actions to the default options. + +| | | +| --- | --- | +| Type | `List? Function(Group, CometChatGroupsController, BuildContext)` | +| Default | `null` | + +--- + +### appBarOptions + +Custom widgets to display in the app bar. + +| | | +| --- | --- | +| Type | `List Function(BuildContext context)` | +| Default | `null` | + +--- + +### backButton + +Custom back button widget. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in back arrow | + +--- + +### controllerTag + +Identifier tag for controller management. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### emptyStateView + +Custom view displayed when there are no groups. + +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in empty state | + +--- + +### errorStateView + +Custom view displayed when an error occurs. + +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in error state | + +--- + +### groupsProtocol + +Custom protocol for fetching groups. + +| | | +| --- | --- | +| Type | `GroupsBuilderProtocol` | +| Default | `null` | + +--- + + +### groupsRequestBuilder + +Controls which groups load and in what order. + +| | | +| --- | --- | +| Type | `GroupsRequestBuilder` | +| Default | SDK default (30 per page) | + +Pass the builder instance, not the result of `.build()`. + +--- + +### groupsStyle + +Styling options for the groups list. + +| | | +| --- | --- | +| Type | `CometChatGroupsStyle` | +| Default | `null` | + +--- + +### groupTypeVisibility + +Shows or hides the group type icon (public/private/password) on group avatars. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + +### height + +Height of the widget. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + +### hideAppbar + +Hides the app bar including title and search. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### hideError + +Hides the error state view. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### hideSearch + +Hides the search input box. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### leadingView + +Custom renderer for the avatar / left section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, Group group)` | +| Default | Built-in avatar | + +--- + +### listItemView + +Custom renderer for the entire list item row. + +| | | +| --- | --- | +| Type | `Widget Function(Group group)` | +| Default | Built-in list item | + +--- + + +### loadingStateView + +Custom view displayed during loading state. + +| | | +| --- | --- | +| Type | `WidgetBuilder` | +| Default | Built-in shimmer | + +--- + +### onBack + +Callback triggered when the back button is pressed. + +| | | +| --- | --- | +| Type | `VoidCallback` | +| Default | `null` | + +--- + +### onEmpty + +Callback triggered when the group list is empty. + +| | | +| --- | --- | +| Type | `OnEmpty` | +| Default | `null` | + +--- + +### onError + +Callback triggered when an error occurs. + +| | | +| --- | --- | +| Type | `OnError` | +| Default | `null` | + +--- + +### onItemLongPress + +Callback triggered on long press of a group item. + +| | | +| --- | --- | +| Type | `Function(BuildContext context, Group group)` | +| Default | `null` | + +--- + +### onItemTap + +Callback triggered when tapping a group item. + +| | | +| --- | --- | +| Type | `Function(BuildContext context, Group group)` | +| Default | `null` | + +--- + +### onLoad + +Callback triggered when the list is successfully loaded. + +| | | +| --- | --- | +| Type | `OnLoad` | +| Default | `null` | + +--- + +### onSelection + +Callback triggered when groups are selected. Requires `selectionMode` to be set. + +| | | +| --- | --- | +| Type | `Function(List? list)` | +| Default | `null` | + +--- + +### passwordGroupIcon + +Custom icon widget for password-protected groups. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in lock icon | + +--- + +### privateGroupIcon + +Custom icon widget for private groups. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in shield icon | + +--- + + +### scrollController + +Controller for scrolling the list. + +| | | +| --- | --- | +| Type | `ScrollController` | +| Default | `null` | + +--- + +### searchBoxIcon + +Custom search box icon widget. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in search icon | + +--- + +### searchKeyword + +Pre-fills the search and filters the group list. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### searchPlaceholder + +Placeholder text for the search input box. + +| | | +| --- | --- | +| Type | `String` | +| Default | `null` | + +--- + +### selectionMode + +Enables single or multi-select mode. + +| | | +| --- | --- | +| Type | `SelectionMode` | +| Default | `null` | + +Values: `SelectionMode.single`, `SelectionMode.multiple`, `SelectionMode.none` + +--- + +### setOptions + +Replaces the default context menu actions. + +| | | +| --- | --- | +| Type | `List? Function(Group, CometChatGroupsController, BuildContext)` | +| Default | `null` | + +--- + +### showBackButton + +Shows or hides the back button. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + +### stateCallBack + +Callback to access controller functions from parent. + +| | | +| --- | --- | +| Type | `Function(CometChatGroupsController controller)` | +| Default | `null` | + +--- + +### submitIcon + +Custom submit icon widget for selection mode. + +| | | +| --- | --- | +| Type | `Widget` | +| Default | Built-in check icon | + +--- + +### subtitleView + +Custom renderer for the member count subtitle. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, Group group)` | +| Default | Built-in member count | + +--- + +### title + +Title text displayed in the app bar. + +| | | +| --- | --- | +| Type | `String` | +| Default | `"Groups"` | + +--- + +### titleView + +Custom renderer for the name / title text. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, Group group)` | +| Default | Built-in title | + +--- + +### trailingView + +Custom renderer for the right section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, Group group)` | +| Default | `null` | + +--- + +### width + +Width of the widget. + +| | | +| --- | --- | +| Type | `double` | +| Default | `null` | + +--- + + +## Events + +`CometChatGroups` subscribes to `CometChatGroupEvents`: + +| Event | Payload | Internal behavior | +| --- | --- | --- | +| `ccGroupCreated` | `Group` | Adds new group to list | +| `ccGroupDeleted` | `Group` | Removes group from list | +| `ccGroupLeft` | `Action, User, Group` | Removes private group or updates hasJoined | +| `ccGroupMemberJoined` | `User, Group` | Updates group in list | +| `ccGroupMemberAdded` | `List, List, Group, User` | Updates group in list | +| `ccGroupMemberKicked` | `Action, User, User, Group` | Updates group in list | +| `ccGroupMemberBanned` | `Action, User, User, Group` | Updates group in list | +| `ccOwnershipChanged` | `Group, GroupMember` | Updates group in list | + +--- + +## Customization Matrix + +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on group interaction | Component props | `on` callbacks | `onItemTap: (ctx, group) => setActive(group)` | +| Filter which groups appear | Component props | `groupsRequestBuilder` | `groupsRequestBuilder: GroupsRequestBuilder()..joinedOnly = true` | +| Toggle visibility of UI elements | Component props | `hide` / `show` boolean props | `hideSearch: true` | +| Replace a section of the list item | Component props | `View` render props | `listItemView: (group) => CustomWidget()` | +| Change colors, fonts, spacing | Component props | `groupsStyle` | `groupsStyle: CometChatGroupsStyle(titleTextColor: Colors.red)` | + + +--- -*** + + + Display and manage user contacts + + + Display recent one-on-one and group conversations + + + Display and manage members of a group + + + Learn how to customize the look and feel + + diff --git a/ui-kit/flutter/message-composer.mdx b/ui-kit/flutter/message-composer.mdx index 201a42ddb..206701160 100644 --- a/ui-kit/flutter/message-composer.mdx +++ b/ui-kit/flutter/message-composer.mdx @@ -1,8 +1,95 @@ --- title: "Message Composer" +description: "A widget that enables users to write and send messages with attachments and reactions" --- -## Overview + +```json +{ + "component": "CometChatMessageComposer", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A widget that enables users to write and send a variety of messages, including text, image, video, and custom messages. Features such as Live Reaction, Attachments, and Message Editing are also supported.", + "primaryOutput": { + "prop": "onSendButtonTap", + "type": "Function(BuildContext, BaseMessage, PreviewMessageMode?)?" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "null", + "note": "User object for the message composer (one of user or group is required)" + }, + "group": { + "type": "Group?", + "default": "null", + "note": "Group object for the message composer (one of user or group is required)" + }, + "text": { + "type": "String?", + "default": "null", + "note": "Initial text for the input field" + }, + "parentMessageId": { + "type": "int", + "default": "0", + "note": "ID of the parent message for threaded replies" + } + }, + "callbacks": { + "onChange": "Function(String)?", + "onSendButtonTap": "Function(BuildContext, BaseMessage, PreviewMessageMode?)?", + "onError": "OnError?" + }, + "visibility": { + "hideVoiceRecordingButton": { "type": "bool?", "default": null }, + "hideSendButton": { "type": "bool?", "default": null }, + "hideAttachmentButton": { "type": "bool?", "default": null }, + "hideStickersButton": { "type": "bool?", "default": null }, + "disableMentions": { "type": "bool?", "default": null }, + "disableTypingEvents": { "type": "bool", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "bool", "default": false }, + "customSoundForMessage": { "type": "String?", "default": null } + }, + "viewSlots": { + "auxiliaryButtonView": "ComposerWidgetBuilder?", + "secondaryButtonView": "ComposerWidgetBuilder?", + "sendButtonView": "Widget?", + "headerView": "ComposerWidgetBuilder?", + "footerView": "ComposerWidgetBuilder?" + }, + "formatting": { + "placeholderText": { "type": "String?", "default": null }, + "maxLine": { "type": "int?", "default": null }, + "padding": { "type": "EdgeInsetsGeometry?", "default": null } + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CometChatMessageComposer is typically used at the bottom of a messaging screen, paired with CometChatMessageHeader and CometChatMessageList", + "components": ["CometChatMessageHeader", "CometChatMessageList", "CometChatMessages"], + "flow": "User types message → Composer sends message → MessageList updates" + }, + "types": { + "CometChatMessageComposerStyle": { + "backgroundColor": "Color?", + "border": "BoxBorder?", + "borderRadius": "BorderRadiusGeometry?", + "sendButtonIconColor": "Color?", + "sendButtonIconBackgroundColor": "Color?", + "textStyle": "TextStyle?", + "placeHolderTextStyle": "TextStyle?" + } + } +} +``` + + +## Where It Fits `CometChatMessageComposer` is a [Widget](/ui-kit/flutter/components-overview#components) that enables users to write and send a variety of messages, including text, image, video, and custom messages. @@ -14,368 +101,258 @@ Features such as **Live Reaction**, **Attachments**, and **Message Editing** are `CometChatMessageComposer` is comprised of the following [Base Widgets](/ui-kit/flutter/components-overview#base-components): -| Base Widgets | Description | -| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -| [MessageInput](/ui-kit/flutter/message-input) | This provides a basic layout for the contents of this component, such as the TextField and buttons | -| [ActionSheet](/ui-kit/flutter/action-sheet) | The ActionSheet widget presents a list of options in either a list or grid mode, depending on the user's preference | - -## Usage - -### Integration - -You can launch `CometChatMessageComposer` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. - -##### 1. Using Navigator to Launch `CometChatMessageComposer` - - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatMessageComposer())); // A user or group object is required to launch this widget. -``` - - - - - -##### 2. Embedding `CometChatMessageComposer` as a Widget in the build Method +| Base Widgets | Description | +| ------------ | ----------- | +| [MessageInput](/ui-kit/flutter/message-input) | This provides a basic layout for the contents of this component, such as the TextField and buttons | +| [ActionSheet](/ui-kit/flutter/action-sheet) | The ActionSheet widget presents a list of options in either a list or grid mode | ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class MessageComposer extends StatefulWidget { - const MessageComposer({super.key}); - - @override - State createState() => _MessageComposerState(); -} -class _MessageComposerState extends State { +// CometChatMessageComposer is typically used at the bottom of a messaging screen +class MessagingScreen extends StatelessWidget { + final User user; + + const MessagingScreen({required this.user}); @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: Column( - children: [ - const Spacer(), - CometChatMessageComposer() - ], - ) // A user or group object is required to launch this widget. - ) + body: Column( + children: [ + CometChatMessageHeader(user: user), + Expanded(child: CometChatMessageList(user: user)), + CometChatMessageComposer(user: user), + ], + ), ); } } ``` - - -*** +## Minimal Render -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. - -##### 1. OnSendButtonClick - -The `OnSendButtonClick` event gets activated when the send message button is clicked. It has a predefined function of sending messages entered in the composer `EditText`. However, you can overide this action with the following code snippet. +The simplest way to render `CometChatMessageComposer`: ```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// For a user conversation CometChatMessageComposer( user: user, - onSendButtonTap: (BuildContext context, BaseMessage baseMessage, PreviewMessageMode? previewMessageMode) { - // TODO("Not yet implemented") - }, ) -``` +// For a group conversation +CometChatMessageComposer( + group: group, +) +``` - -*** -##### 2. onChange +## Actions and Events + +### Callback Props + +Component-level callbacks that fire on specific user interactions: -This action handles changes in the value of text in the input field of the CometChatMessageComposer widget. +| Callback | Signature | Fires When | +|----------|-----------|------------| +| `onSendButtonTap` | `Function(BuildContext, BaseMessage, PreviewMessageMode?)?` | User taps the send button | +| `onChange` | `Function(String)?` | Text in the input field changes | +| `onError` | `OnError?` | An error occurs | +| `stateCallBack` | `Function(CometChatMessageComposerController)?` | Access controller functions | ```dart CometChatMessageComposer( user: user, + onSendButtonTap: (BuildContext context, BaseMessage baseMessage, PreviewMessageMode? previewMessageMode) { + // Handle send button tap + }, onChange: (String? text) { - // TODO("Not yet implemented") + // Handle text change + }, + onError: (e) { + // Handle error }, ) ``` - - -*** +## Custom View Slots + +Customize the appearance of `CometChatMessageComposer` by replacing default views with your own widgets. -##### 3. onError +| Slot | Signature | Replaces | +|------|-----------|----------| +| `auxiliaryButtonView` | `ComposerWidgetBuilder?` | Auxiliary button area (AI, stickers) | +| `secondaryButtonView` | `ComposerWidgetBuilder?` | Secondary button area (attachment, voice) | +| `sendButtonView` | `Widget?` | Send button | +| `headerView` | `ComposerWidgetBuilder?` | Header section above input | +| `footerView` | `ComposerWidgetBuilder?` | Footer section below input | +| `attachmentOptions` | `ComposerActionsBuilder?` | Attachment options list | -This action doesn't change the behavior of the widget but rather listens for any errors that occur in the MessageList widget. +### Example: Custom Auxiliary Button View ```dart CometChatMessageComposer( user: user, - onError: (e) { - // TODO("Not yet implemented") + auxiliaryButtonView: (context, user, group, id) { + final existingAuxiliaryOptions = CometChatUIKit.getDataSource() + .getAuxiliaryOptions(user, group, context, id, Color(0xFFA1A1A1)); + return Row( + children: [ + existingAuxiliaryOptions, + Icon( + Icons.location_pin, + color: Color(0xFF6852D6), + ), + ], + ); }, ) ``` - - -*** - -### Filters - -`CometChatMessageComposer` widget does not have any available filters. - -*** - -### Events - -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The `CometChatMessageComposer` Widget does not emit any events of its own. - -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the `CometChatMessageComposer` widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the widget in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the widget. - -##### 1. CometChatMessageComposerStyle + + + -To modify the styling, you can apply the `CometChatMessageComposerStyle` to the `CometChatMessageComposer` Widget using the `messageComposerStyle` property. +### Example: Custom Secondary Button View ```dart CometChatMessageComposer( user: user, - messageComposerStyle: CometChatMessageComposerStyle( - sendButtonIconBackgroundColor: Color(0xFFF76808), - secondaryButtonIconColor: Color(0xFFF76808), - auxiliaryButtonIconColor: Color(0xFFF76808) - ) + secondaryButtonView: (context, user, group, id) { + return Icon( + Icons.attach_file, + color: Color(0xFF6852D6), + ); + }, ) ``` - - - + -##### 2. MediaRecorder Style - -To customize the styles of the MediaRecorder widget within the `CometChatMessageComposer` Widget, use the `mediaRecorderStyle` property. For more details, please refer to [MediaRecorder](/ui-kit/flutter/component-styling#media-recorder) styles. +### Example: Custom Send Button View ```dart CometChatMessageComposer( user: user, - messageComposerStyle: CometChatMessageComposerStyle( - mediaRecorderStyle: CometChatMediaRecorderStyle( - recordIndicatorBackgroundColor: Color(0xFFF44649), - recordIndicatorBorderRadius: BorderRadius.circular(20), - pauseButtonBorderRadius: BorderRadius.circular(8), - deleteButtonBorderRadius: BorderRadius.circular(8), - stopButtonBorderRadius: BorderRadius.circular(8), - ), + sendButtonView: IconButton( + onPressed: () {}, + padding: EdgeInsets.all(4), + style: IconButton.styleFrom( + alignment: Alignment.center, + backgroundColor: Color(0xFFEDEAFA), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(4), + ), + ), + icon: Transform.rotate( + angle: 150, + child: Icon( + Icons.send, + size: 20, + color: Color(0xFF6852D6), + ), + ), ), ) ``` - - - + -*** - -##### 3. AI Options Style - -To customize the styles of the AI Options widget within the `CometChatMessageComposer` Widget, use the `aiOptionStyle`. +### Example: Custom Header View ```dart CometChatMessageComposer( user: user, -messageComposerStyle: CometChatMessageComposerStyle( - aiOptionStyle: AIOptionsStyle( - backgroundColor: Color(0xFFE4EBF5), - border: Border.all(width: 3, color: Colors.red), - ) - ), + headerView: (context, user, group, id) { + return Container( + margin: EdgeInsets.only(bottom: 2, left: 8, right: 8), + padding: EdgeInsets.all(8), + decoration: BoxDecoration( + color: Color(0xFFEDEAFA), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Icon(Icons.volume_off, size: 20, color: Color(0xFF6852D6)), + Text( + "User has paused their notifications", + style: TextStyle(fontSize: 14, fontWeight: FontWeight.w400), + ), + ], + ), + ); + }, ) ``` - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - + +### Example: Custom Footer View + ```dart CometChatMessageComposer( user: user, - placeholderText: "Type a message...", - disableMentions: true, + footerView: (context, user, group, id) { + return Container( + width: MediaQuery.of(context).size.width / 1.08, + color: Colors.yellow, + padding: const EdgeInsets.all(8), + child: const Center(child: Text("Your Footer Widget")), + ); + }, ) ``` - - -Below is a list of customizations along with corresponding code snippets - -## Message Composer Properties - -| Property | Data Type | Description | -| ----------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------ | -| `user` | `User?` | Sets user for the message composer. | -| `group` | `Group?` | Sets group for the message composer. | -| `messageComposerStyle` | `CometChatMessageComposerStyle?` | Sets style for the message composer. | -| `placeholderText` | `String?` | Hint text for the input field. | -| `text` | `String?` | Initial text for the input field. | -| `onChange` | `Function(String text)?` | Callback triggered when text changes. | -| `textEditingController` | `TextEditingController?` | Controls the state of the text field. | -| `maxLine` | `int?` | Maximum number of lines allowed in the input field. | -| `disableMentions` | `bool?` | Disables mentions in the composer. | -| `disableTypingEvents` | `bool` | Disables typing events. | -| `disableSoundForMessages` | `bool` | Disables sound for sent messages. | -| `customSoundForMessage` | `String?` | URL for custom sound when a message is sent. | -| `customSoundForMessagePackage` | `String?` | Package name for the custom sound. | -| `parentMessageId` | `int` | ID of the parent message (default is 0). | -| `padding` | `EdgeInsetsGeometry?` | Sets padding for the message composer. | -| `messageInputPadding` | `EdgeInsetsGeometry?` | Sets padding for the message input field. | -| `sendButtonView` | `Widget?` | Custom send button widget. | -| `attachmentIcon` | `Widget?` | Custom attachment icon. | -| `attachmentIconURL` | `String?` | URL of the attachment icon. | -| `voiceRecordingIcon` | `Widget?` | Custom voice recording icon. | -| `aiIcon` | `Widget?` | Custom AI button icon. | -| `aiIconURL` | `String?` | URL for the AI button icon. | -| `aiIconPackageName` | `String?` | Package name for the AI icon. | -| `auxiliaryButtonView` | `ComposerWidgetBuilder?` | UI component forwarded to message input as auxiliary button. | -| `secondaryButtonView` | `ComposerWidgetBuilder?` | UI component forwarded to message input as secondary button. | -| `auxiliaryButtonsAlignment` | `AuxiliaryButtonsAlignment?` | Controls position of auxiliary button view. | -| `hideVoiceRecordingButton` | `bool?` | Option to hide the voice recording button. | -| `recorderStartButtonIcon` | `Widget?` | Custom start button icon for the recorder. | -| `recorderPauseButtonIcon` | `Widget?` | Custom pause button icon for the recorder. | -| `recorderDeleteButtonIcon` | `Widget?` | Custom delete button icon for the recorder. | -| `recorderStopButtonIcon` | `Widget?` | Custom stop button icon for the recorder. | -| `recorderSendButtonIcon` | `Widget?` | Custom send button icon for the recorder. | -| `attachmentOptions` | `ComposerActionsBuilder?` | Provides options for file attachments. | -| `hideAttachmentButton` | `bool?` | Hide/display attachment button. | -| `hideImageAttachmentOption` | `bool?` | Hide/display image attachment option. | -| `hideVideoAttachmentOption` | `bool?` | Hide/display video attachment option. | -| `hideAudioAttachmentOption` | `bool?` | Hide/display audio attachment option. | -| `hideFileAttachmentOption` | `bool?` | Hide/display file attachment option. | -| `hidePollsOption` | `bool?` | Hide/display polls option. | -| `hideCollaborativeDocumentOption` | `bool?` | Hide/display collaborative document option. | -| `hideCollaborativeWhiteboardOption` | `bool?` | Hide/display collaborative whiteboard option. | -| `hideTakePhotoOption` | `bool?` | Hide/display take photo option. | -| `onSendButtonTap` | `Function(BuildContext, BaseMessage, PreviewMessageMode?)?` | Callback triggered when the send button is tapped. | -| `onError` | `OnError?` | Callback to handle errors. | -| `stateCallBack` | `Function(CometChatMessageComposerController controller)?` | Callback to manage state of the message composer. | -| `hideSendButton` | `bool?` | Hide/display the send button. | -| `hideStickersButton` | `bool?` | Hide/display the sticker button. | -| `sendButtonIcon` | `Widget?` | Custom send button icon. | -| `disableMentionAll` | `bool?` | Controls whether group mentions like @all appear in suggestions. | -| `mentionAllLabelId` | `String?` | Allows setting a custom label id for group mentions (@channel, @everyone, etc.). | -| `mentionAllLabel` | `String?` | Allows setting a custom label for group mentions (@channel, @everyone, etc.). | - -*** - -### Advanced - -For advanced-level customization, you can set custom widgets to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your widgets and then incorporate those into the widget. - -*** - -#### TextFormatters - -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide) - -**Example** - -Here is the complete example for reference: - - -```dart -CometChatMessageComposer( - user: user, - textFormatters: [ - CometChatMentionsFormatter( - style: CometChatMentionsStyle( - mentionSelfTextBackgroundColor: Color(0xFFF76808), - mentionTextBackgroundColor: Colors.white, - mentionTextColor: Colors.black, - mentionSelfTextColor: Colors.white, - ) - ) - ], -) -``` - + +![Image](/images/046c76af-message_composer_footer_view_cometchat_screens-5812a879cc6949aa04be485821255e0a.png) + + +![Image](/images/e57c8a15-message_composer_footer_view_cometchat_screens-49ac543fd44c8879b857da46340db0fe.png) - - - - - -*** - -#### AttachmentOptions - -By using `attachmentOptions`, you can set a list of custom `MessageComposerActions` for the `CometChatMessageComposer` Widget. This will override the existing list of `MessageComposerActions`. - -**Example** - -Here is the complete example for reference: +### Example: Custom Attachment Options @@ -383,263 +360,213 @@ Here is the complete example for reference: CometChatMessageComposer( user: user, attachmentOptions: (context, user, group, id) { - return [ - CometChatMessageComposerAction( - id: "Custom Option 1", - title: "Custom Option 1", - icon: Icon( - Icons.play_circle, - color: Colors.black, - ), - ), - CometChatMessageComposerAction( - id: "Custom Option 2", - title: "Custom Option 2", - icon: Icon( - Icons.add_box, - color: Colors.black, - ), - ), - CometChatMessageComposerAction( - id: "Custom Option 3", - title: "Custom Option 3", - icon: Icon( - Icons.change_circle, - color: Colors.black, - ), - ), - CometChatMessageComposerAction( - id: "Custom Option 4", - title: "Custom Option 4", - icon: Icon( - Icons.sunny, - color: Colors.black, - ), - ) - ]; - }, + return [ + CometChatMessageComposerAction( + id: "Custom Option 1", + title: "Custom Option 1", + icon: Icon(Icons.play_circle, color: Colors.black), + ), + CometChatMessageComposerAction( + id: "Custom Option 2", + title: "Custom Option 2", + icon: Icon(Icons.add_box, color: Colors.black), + ), + ]; + }, ) ``` - - -*** -#### AuxiliaryButton Widget - -You can insert a custom widget into the `CometChatMessageComposer` widget to add additional functionality using the `auxiliaryButtonView` property. - -**Example** - -Here is the complete example for reference: +## Styling + +Customize the appearance of `CometChatMessageComposer` using `CometChatMessageComposerStyle`. + +### Style Properties + +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `Color?` | Background color of the message composer | +| `border` | `BoxBorder?` | Border of the message composer | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius of the message composer | +| `closeIconTint` | `Color?` | Color for the close icon | +| `dividerColor` | `Color?` | Color of the divider | +| `dividerHeight` | `double?` | Height of the divider | +| `sendButtonIconColor` | `Color?` | Color of the send button icon | +| `sendButtonIconBackgroundColor` | `Color?` | Background color of the send button | +| `sendButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius of the send button | +| `secondaryButtonIconColor` | `Color?` | Color of the secondary button icon | +| `secondaryButtonIconBackgroundColor` | `Color?` | Background color of the secondary button | +| `auxiliaryButtonIconColor` | `Color?` | Color of the auxiliary button icon | +| `auxiliaryButtonIconBackgroundColor` | `Color?` | Background color of the auxiliary button | +| `textStyle` | `TextStyle?` | Style of the text | +| `textColor` | `Color?` | Color of the text | +| `placeHolderTextStyle` | `TextStyle?` | Style of the placeholder text | +| `placeHolderTextColor` | `Color?` | Color of the placeholder text | +| `filledColor` | `Color?` | Background color of the text input | +| `mentionsStyle` | `CometChatMentionsStyle?` | Style for mentions | +| `mediaRecorderStyle` | `CometChatMediaRecorderStyle?` | Style for media recorder | +| `aiOptionStyle` | `AIOptionsStyle?` | Style for AI options | + +### Example: Custom Styling ```dart CometChatMessageComposer( - user: user, - auxiliaryButtonView: (context, user, group, id) { - final existingAuxiliaryOptions = CometChatUIKit.getDataSource() - .getAuxiliaryOptions(user, group, context, id, Color(0xFFA1A1A1)); - return Row( - children: [ - existingAuxiliaryOptions, - Icon( - Icons.location_pin, - color: Color(0xFF6852D6), - ), - ], - ); - }, + user: user, + messageComposerStyle: CometChatMessageComposerStyle( + sendButtonIconBackgroundColor: Color(0xFFF76808), + secondaryButtonIconColor: Color(0xFFF76808), + auxiliaryButtonIconColor: Color(0xFFF76808), + ), ) ``` - - - + -*** - -#### SecondaryButton Widget - -You can add a custom widget into the SecondaryButton widget for additional functionality using the `secondaryButtonView` property. - -**Example** - -Here is the complete example for reference: +### Example: Custom Media Recorder Style ```dart CometChatMessageComposer( - user: user, - secondaryButtonView: (context, user, group, id) { - return Icon( - Icons.attach_file, - color: Color(0xFF6852D6), - ); - } + user: user, + messageComposerStyle: CometChatMessageComposerStyle( + mediaRecorderStyle: CometChatMediaRecorderStyle( + recordIndicatorBackgroundColor: Color(0xFFF44649), + recordIndicatorBorderRadius: BorderRadius.circular(20), + pauseButtonBorderRadius: BorderRadius.circular(8), + deleteButtonBorderRadius: BorderRadius.circular(8), + stopButtonBorderRadius: BorderRadius.circular(8), + ), + ), ) ``` - - - - - -*** - -#### SendButton Widget - -You can set a custom widget in place of the already existing send button widget. Using the `sendButtonView` property. - -**Example** - -Here is the complete example for reference: - - - -```dart - CometChatMessageComposer( - user: user, - sendButtonView: IconButton( - onPressed: () {}, - padding: EdgeInsets.all(4), - style: IconButton.styleFrom( - alignment: Alignment.center, - backgroundColor: Color(0xFFEDEAFA), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(4), - )), - icon: Transform.rotate( - angle: 150, - child: Icon( - Icons.send, - size: 20, - color: Color(0xFF6852D6), - ), - ) - ), - ) -``` - - - - - - - + -*** - -#### Header Widget - -You can set custom headerView to the `CometChatMessageComposer` widget using the `headerView` property - -**Example** - -Here is the complete example for reference: +### Example: Custom AI Options Style ```dart CometChatMessageComposer( - user: user, - headerView: (context, user, group, id) { - return Container( - margin: EdgeInsets.only( - bottom: 2, - left: 8, - right: 8), - padding: EdgeInsets.all(8), - decoration: BoxDecoration( - color: Color(0xFFEDEAFA), - borderRadius: BorderRadius.circular(8), - ), - child: Row( - children: [ - Icon( - Icons.volume_off, - size: 20, - color: Color(0xFF6852D6), - ), - Text( - "User has paused their notifications", - style: TextStyle( - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ), - ], - ), - ); - }, - ) + user: user, + messageComposerStyle: CometChatMessageComposerStyle( + aiOptionStyle: AIOptionsStyle( + backgroundColor: Color(0xFFE4EBF5), + border: Border.all(width: 3, color: Colors.red), + ), + ), +) ``` - - - - - - -*** - -#### Footer Widget +## Advanced -You can set a custom footer widget to the `CometChatMessageComposer` widget using the `footerView` property: +### Text Formatters -**Example** - -Here is the complete example for reference: +Assigns the list of text formatters. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/flutter/mentions-formatter-guide). ```dart CometChatMessageComposer( user: user, - footerView: (context, user, group, id) { - return Container( - width: MediaQuery.of(context).size.width/1.08, - color: Colors.yellow, - padding: const EdgeInsets.all(8), - child: const Center(child: Text("Your Footer Widget")), - ); - }, + textFormatters: [ + CometChatMentionsFormatter( + style: CometChatMentionsStyle( + mentionSelfTextBackgroundColor: Color(0xFFF76808), + mentionTextBackgroundColor: Colors.white, + mentionTextColor: Colors.black, + mentionSelfTextColor: Colors.white, + ), + ), + ], ) ``` - - - - -![Image](/images/046c76af-message_composer_footer_view_cometchat_screens-5812a879cc6949aa04be485821255e0a.png) - - - - -![Image](/images/e57c8a15-message_composer_footer_view_cometchat_screens-49ac543fd44c8879b857da46340db0fe.png) - - - - + + + -*** +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `user` | `User?` | `null` | User object for the message composer | +| `group` | `Group?` | `null` | Group object for the message composer | +| `messageComposerStyle` | `CometChatMessageComposerStyle?` | - | Sets style for the message composer | +| `placeholderText` | `String?` | - | Hint text for the input field | +| `text` | `String?` | - | Initial text for the input field | +| `onChange` | `Function(String)?` | - | Callback triggered when text changes | +| `textEditingController` | `TextEditingController?` | - | Controls the state of the text field | +| `maxLine` | `int?` | - | Maximum number of lines allowed | +| `disableMentions` | `bool?` | `null` | Disables mentions in the composer | +| `disableTypingEvents` | `bool` | `false` | Disables typing events | +| `disableSoundForMessages` | `bool` | `false` | Disables sound for sent messages | +| `customSoundForMessage` | `String?` | - | URL for custom sound | +| `parentMessageId` | `int` | `0` | ID of the parent message | +| `padding` | `EdgeInsetsGeometry?` | - | Sets padding for the message composer | +| `messageInputPadding` | `EdgeInsetsGeometry?` | - | Sets padding for the message input field | +| `sendButtonView` | `Widget?` | - | Custom send button widget | +| `attachmentIcon` | `Widget?` | - | Custom attachment icon | +| `voiceRecordingIcon` | `Widget?` | - | Custom voice recording icon | +| `aiIcon` | `Widget?` | - | Custom AI button icon | +| `auxiliaryButtonView` | `ComposerWidgetBuilder?` | - | UI component for auxiliary button | +| `secondaryButtonView` | `ComposerWidgetBuilder?` | - | UI component for secondary button | +| `auxiliaryButtonsAlignment` | `AuxiliaryButtonsAlignment?` | - | Controls position of auxiliary button view | +| `hideVoiceRecordingButton` | `bool?` | `null` | Hide/display voice recording button | +| `attachmentOptions` | `ComposerActionsBuilder?` | - | Provides options for file attachments | +| `hideAttachmentButton` | `bool?` | `null` | Hide/display attachment button | +| `hideImageAttachmentOption` | `bool?` | `null` | Hide/display image attachment option | +| `hideVideoAttachmentOption` | `bool?` | `null` | Hide/display video attachment option | +| `hideAudioAttachmentOption` | `bool?` | `null` | Hide/display audio attachment option | +| `hideFileAttachmentOption` | `bool?` | `null` | Hide/display file attachment option | +| `hidePollsOption` | `bool?` | `null` | Hide/display polls option | +| `hideCollaborativeDocumentOption` | `bool?` | `null` | Hide/display collaborative document option | +| `hideCollaborativeWhiteboardOption` | `bool?` | `null` | Hide/display collaborative whiteboard option | +| `hideTakePhotoOption` | `bool?` | `null` | Hide/display take photo option | +| `onSendButtonTap` | `Function(...)?` | - | Callback when send button is tapped | +| `onError` | `OnError?` | - | Callback to handle errors | +| `hideSendButton` | `bool?` | `null` | Hide/display the send button | +| `hideStickersButton` | `bool?` | `null` | Hide/display the sticker button | +| `sendButtonIcon` | `Widget?` | - | Custom send button icon | +| `disableMentionAll` | `bool` | `false` | Disables @all mentions in groups | +| `mentionAllLabel` | `String?` | - | Custom label for group mentions | +| `mentionAllLabelId` | `String?` | - | Custom label ID for group mentions | +| `headerView` | `ComposerWidgetBuilder?` | - | Custom header view | +| `footerView` | `ComposerWidgetBuilder?` | - | Custom footer view | +| `textFormatters` | `List?` | - | List of text formatters | + + + + Display user or group details in the header + + + Display messages in a conversation + + + Configure mentions look and feel + + + Learn how to customize the look and feel + + diff --git a/ui-kit/flutter/message-list.mdx b/ui-kit/flutter/message-list.mdx index aaf056e49..41a73db4c 100644 --- a/ui-kit/flutter/message-list.mdx +++ b/ui-kit/flutter/message-list.mdx @@ -1,493 +1,500 @@ --- title: "Message List" +description: "A composite widget that displays a list of messages with real-time operations" --- -## Overview + +```json +{ + "component": "CometChatMessageList", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A composite widget that displays a list of messages with real-time operations. Includes various message types such as Text Messages, Media Messages, Stickers, and more.", + "primaryOutput": { + "prop": "onThreadRepliesClick", + "type": "void Function(BaseMessage, BuildContext, {CometChatMessageTemplate?})?" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "null", + "note": "User object for user message list (one of user or group is required)" + }, + "group": { + "type": "Group?", + "default": "null", + "note": "Group object for group message list (one of user or group is required)" + }, + "messagesRequestBuilder": { + "type": "MessagesRequestBuilder?", + "default": "null", + "note": "Custom request builder for filtering messages" + }, + "templates": { + "type": "List?", + "default": "null", + "note": "Message templates for the list" + } + }, + "callbacks": { + "onThreadRepliesClick": "void Function(BaseMessage, BuildContext, {CometChatMessageTemplate?})?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?", + "onReactionClick": "Function(String?, BaseMessage)?", + "onReactionLongPress": "Function(String?, BaseMessage)?", + "onReactionListItemClick": "Function(String?, BaseMessage?)?" + }, + "visibility": { + "hideTimestamp": { "type": "bool?", "default": null }, + "avatarVisibility": { "type": "bool?", "default": true }, + "receiptsVisibility": { "type": "bool?", "default": true }, + "disableReactions": { "type": "bool?", "default": false }, + "hideStickyDate": { "type": "bool?", "default": false }, + "hideReplyInThreadOption": { "type": "bool?", "default": false }, + "hideEditMessageOption": { "type": "bool?", "default": false }, + "hideDeleteMessageOption": { "type": "bool?", "default": false }, + "hideGroupActionMessages": { "type": "bool?", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "bool?", "default": null }, + "customSoundForMessages": { "type": "String?", "default": null } + }, + "viewSlots": { + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "headerView": "Widget? Function(BuildContext, {User?, Group?, int?})?", + "footerView": "Widget? Function(BuildContext, {User?, Group?, int?})?" + }, + "formatting": { + "alignment": { "type": "ChatAlignment", "default": "ChatAlignment.standard" }, + "datePattern": { "type": "String Function(BaseMessage)?", "default": null }, + "dateSeparatorPattern": { "type": "String Function(DateTime)?", "default": null } + } + }, + "events": [], + "sdkListeners": [ + "onMessageReceived", + "onMessageEdited", + "onMessageDeleted", + "onTypingStarted", + "onTypingEnded" + ], + "compositionExample": { + "description": "CometChatMessageList is typically used within CometChatMessages, paired with CometChatMessageHeader and CometChatMessageComposer", + "components": ["CometChatMessageHeader", "CometChatMessageComposer", "CometChatMessages"], + "flow": "User/Group → MessageList displays messages → Real-time updates via SDK listeners" + }, + "types": { + "CometChatMessageListStyle": { + "backgroundColor": "Color?", + "border": "BoxBorder?", + "borderRadius": "BorderRadiusGeometry?", + "incomingMessageBubbleStyle": "CometChatIncomingMessageBubbleStyle?", + "outgoingMessageBubbleStyle": "CometChatOutgoingMessageBubbleStyle?", + "avatarStyle": "CometChatAvatarStyle?" + } + } +} +``` + -`MessageList` is a [Composite Widget](/ui-kit/flutter/components-overview#composite-components) that displays a list of messages and effectively manages real-time operations. It includes various types of messages such as Text Messages, Media Messages, Stickers, and more. +## Where It Fits -`MessageList` is primarily a list of the base widget [MessageBubble](/ui-kit/flutter/message-bubble-styling). The MessageBubble Widget is utilized to create different types of chat bubbles depending on the message type. +`CometChatMessageList` is a [Composite Widget](/ui-kit/flutter/components-overview#composite-components) that displays a list of messages and effectively manages real-time operations. It includes various types of messages such as Text Messages, Media Messages, Stickers, and more. + +`CometChatMessageList` is primarily a list of the base widget [MessageBubble](/ui-kit/flutter/message-bubble-styling). The MessageBubble Widget is utilized to create different types of chat bubbles depending on the message type. -## Usage - -### Integration - -You can launch `CometChatMessageList` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. - -##### 1. Using Navigator to Launch `CometChatMessageList` - - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatMessageList())); // A user or group object is required to launch this widget. -``` - - - - - - - -Simply adding the `MessageList` component to the layout will only display the loading indicator. To fetch messages for a specific entity, you need to supplement it with `User` or `Group` Object. - - - -*** - -##### 2. Embedding `CometChatMessageList` as a Widget in the build Method - ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class MessageList extends StatefulWidget { - const MessageList({super.key}); - @override - State createState() => _MessageListState(); -} - -class _MessageListState extends State { +// CometChatMessageList is typically used within CometChatMessages +// or as part of a custom messaging screen +class MessagingScreen extends StatelessWidget { + final User user; + + const MessagingScreen({required this.user}); @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: CometChatMessageList() // A user or group object is required to launch this widget. - ) + body: Column( + children: [ + CometChatMessageHeader(user: user), + Expanded(child: CometChatMessageList(user: user)), + CometChatMessageComposer(user: user), + ], + ), ); } } ``` - - -*** - -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. - -##### onThreadRepliesClick +## Minimal Render -`onThreadRepliesClick` is triggered when you click on the threaded message bubble. The `onThreadRepliesClick` action doesn't have a predefined behavior. You can override this action using the following code snippet. +The simplest way to render `CometChatMessageList`: ```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + +// For a user conversation CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - onThreadRepliesClick: (message, context, {template}) { { - // TODO("Not yet implemented") - }, + user: user, ) -``` +// For a group conversation +CometChatMessageList( + group: group, +) +``` - -*** + +Simply adding the `MessageList` component to the layout will only display the loading indicator. To fetch messages for a specific entity, you need to supplement it with `User` or `Group` Object. + + + +## Filtering CometChatMessageList -##### onError +Use the `messagesRequestBuilder` prop to filter which messages appear in the list. -You can customize this behavior by using the provided code snippet to override the `onError` and improve error handling. +### Filter Recipes + +| Recipe | Code | +|--------|------| +| Limit messages | `MessagesRequestBuilder()..limit = 30` | +| Search messages | `MessagesRequestBuilder()..searchKeyword = "keyword"` | +| Filter by type | `MessagesRequestBuilder()..types = ["text"]` | +| Filter by category | `MessagesRequestBuilder()..categories = ["message"]` | ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - onError: (e) { - // TODO("Not yet implemented") - }, + user: user, + messagesRequestBuilder: MessagesRequestBuilder() + ..uid = user.uid + ..searchKeyword = "searchKeyword" + ..limit = 30, ) ``` - - -*** + +The following parameters in messageRequestBuilder will always be altered inside the message list: +1. UID +2. GUID +3. types +4. categories + + +For the full MessagesRequestBuilder API, see the [SDK documentation](/sdk/flutter/additional-message-filtering). + +## Actions and Events + +### Callback Props -##### onLoad +Component-level callbacks that fire on specific user interactions: -Invoked when the list is successfully fetched and loaded, helping track component readiness. +| Callback | Signature | Fires When | +|----------|-----------|------------| +| `onThreadRepliesClick` | `void Function(BaseMessage, BuildContext, {CometChatMessageTemplate?})?` | User clicks on thread indicator | +| `onError` | `OnError?` | An error occurs while fetching messages | +| `onLoad` | `OnLoad?` | List is successfully fetched and loaded | +| `onEmpty` | `OnEmpty?` | List is empty | +| `onReactionClick` | `Function(String?, BaseMessage)?` | User clicks on a reaction pill | +| `onReactionLongPress` | `Function(String?, BaseMessage)?` | User long presses on a reaction pill | +| `onReactionListItemClick` | `Function(String?, BaseMessage?)?` | User clicks on a reaction list item | +| `addMoreReactionTap` | `Function(BaseMessage)?` | User clicks "Add More Reactions" button | ```dart CometChatMessageList( - onLoad: (list) { - // print("messages loaded: ${list.length}"); - }, + user: user, + onThreadRepliesClick: (message, context, {template}) { + // Handle thread replies click + }, + onError: (e) { + // Handle error + }, + onLoad: (list) { + print("Messages loaded: ${list.length}"); + }, + onEmpty: () { + print("No messages"); + }, + onReactionClick: (emoji, message) { + // Handle reaction click + }, ) ``` - - -*** - -##### onEmpty +### SDK Events (Real-Time, Automatic) -Called when the list is empty, enabling custom handling such as showing a placeholder message. - - - -```dart -CometChatMessageList( - onEmpty: () { - // print("Groups empty"); - }, -) -``` +The component automatically handles these SDK listeners for real-time updates: - +| SDK Listener | Handled Automatically | +|--------------|----------------------| +| `onMessageReceived` | Adds new message to the list | +| `onMessageEdited` | Updates edited message in the list | +| `onMessageDeleted` | Removes deleted message from the list | +| `onTypingStarted` | Shows typing indicator | +| `onTypingEnded` | Hides typing indicator | - +## Custom View Slots -*** +Customize the appearance of `CometChatMessageList` by replacing default views with your own widgets. -##### onReactionLongPress +| Slot | Signature | Replaces | +|------|-----------|----------| +| `loadingStateView` | `WidgetBuilder?` | Loading spinner | +| `emptyStateView` | `WidgetBuilder?` | Empty state display | +| `errorStateView` | `WidgetBuilder?` | Error state display | +| `headerView` | `Widget? Function(BuildContext, {User?, Group?, int?})?` | Header section | +| `footerView` | `Widget? Function(BuildContext, {User?, Group?, int?})?` | Footer section | +| `emptyChatGreetingView` | `WidgetBuilder?` | Empty chat greeting for AI | +| `newMessageIndicatorView` | `WidgetBuilder?` | New message indicator | -Function triggered when a user long presses on a reaction pill, allowing developers to override the default behavior. +### Example: Custom Header View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget - onReactionLongPress: (emoji, message) { - // print("onReactionClick"); + user: user, + headerView: (context, {group, parentMessageId, user}) { + return Container( + width: double.maxFinite, + color: Color(0xFFEDEAFA), + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + Icon(Icons.notes_outlined, color: Color(0xFF6852D6)), + SizedBox(width: 8), + Text('Notes', style: TextStyle(color: Color(0xFF6852D6))), + ], + ), + ); }, ) ``` - - -*** - -##### addMoreReactionTap + + + -Function triggered when a user clicks on the 'Add More Reactions' button, allowing developers to handle this action. +### Example: Custom Footer View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget - addMoreReactionTap: (message) { - // print("addMoreReactionTap"); + user: user, + footerView: (context, {group, parentMessageId, user}) { + return Container( + width: double.maxFinite, + color: Color(0xFFEDEAFA), + padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Row( + children: [ + Icon(Icons.sunny, color: Color(0xFF6852D6)), + SizedBox(width: 8), + Text('Ice Breakers', style: TextStyle(color: Color(0xFF6852D6))), + ], + ), + ); }, ) ``` - - -*** - -##### onReactionClick + + + -The listener to be set for reacting to a message.Pass a non-null instance of onReactionClick to enable it. +### Example: Custom Loading State View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget - onReactionClick: (emoji, message) { - // print("onReactionClick"); + user: user, + loadingStateView: (context) { + return Center( + child: CircularProgressIndicator(), + ); }, ) ``` - - -*** - -##### onReactionListItemClick - -Function triggered when a reaction list item is clicked, allowing developers to override its behavior in CometChatReactionsList. +### Example: Custom Empty State View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget - onReactionListItemClick: (reaction, message) { - // print("onReactionListItemClick"); + user: user, + emptyStateView: (context) { + return Center( + child: Text("No messages yet. Start the conversation!"), + ); }, ) ``` - - -*** - -### Filters - -You can adjust the `MessagesRequestBuilder` in the MessageList Widget to customize your message list. Numerous options are available to alter the builder to meet your specific needs. For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/flutter/additional-message-filtering). - -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed +### Example: Custom Error State View ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - messagesRequestBuilder: MessagesRequestBuilder() - ..uid = user.uid - ..searchKeyword = "searchKeyword" + user: user, + errorStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text("Couldn't load messages"), + ElevatedButton( + onPressed: () { + // Retry logic + }, + child: Text("Retry"), + ), + ], + ), + ); + }, ) ``` - - - -The following parameters in messageRequestBuilder will always be altered inside the message list +## Styling -1. UID -2. GUID -3. types -4. categories +Customize the appearance of `CometChatMessageList` using `CometChatMessageListStyle`. - +### Style Properties -*** +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `Color?` | Background color of the message list | +| `border` | `BoxBorder?` | Border of the message list | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius of the message list | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for avatar in message bubble | +| `emptyStateTextStyle` | `TextStyle?` | Style for empty state text | +| `emptyStateTextColor` | `Color?` | Color for empty state text | +| `errorStateTextStyle` | `TextStyle?` | Style for error state text | +| `errorStateTextColor` | `Color?` | Color for error state text | +| `incomingMessageBubbleStyle` | `CometChatIncomingMessageBubbleStyle?` | Style for incoming message bubble | +| `outgoingMessageBubbleStyle` | `CometChatOutgoingMessageBubbleStyle?` | Style for outgoing message bubble | +| `messageInformationStyle` | `CometChatMessageInformationStyle?` | Style for message information | +| `messageOptionSheetStyle` | `CometChatMessageOptionSheetStyle?` | Style for message option sheet | +| `mentionsStyle` | `CometChatMentionsStyle?` | Style for mentions | +| `reactionsStyle` | `CometChatReactionsStyle?` | Style for reactions | +| `aiSmartRepliesStyle` | `CometChatAISmartRepliesStyle?` | Style for smart replies | -### Events - -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `Widget`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The MessageList Widget does not emit any events of its own. - -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the widget in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the widget. - -##### 1. MessageList Style - -You can set the `style` to the `CometChatMessageList` Widget to customize the styling. +### Example: Custom Styling ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. + user: user, style: CometChatMessageListStyle( - backgroundColor: Color(0xFFFEEDE1), - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808), - ) - ) + backgroundColor: Color(0xFFFEEDE1), + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), + ), ) ``` - - -*** - -##### 2. Avatar Style - -To apply customized styles to the `Avatar` widget in the `CometChatGroups` widget, you can use the following code snippet. For further insights on `Avatar` Styles [refer](/ui-kit/flutter/component-styling#avatar) +### Example: Custom Avatar Style ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - style: CometChatMessageListStyle( - avatarStyle: CometChatAvatarStyle( - border: Border.all(width: 5), - borderRadius: 20, - backgroundColor: Colors.red - ), - ), - ), + user: user, + style: CometChatMessageListStyle( + avatarStyle: CometChatAvatarStyle( + border: Border.all(width: 5), + borderRadius: 20, + backgroundColor: Colors.red, + ), + ), +) ``` - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - - - - +### Example: Custom Mentions Style ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - readIcon: Icon(Icons.mark_chat_read, color: Colors.white), + user: user, + textFormatters: [ + CometChatMentionsFormatter( + style: CometChatMentionsStyle( + mentionSelfTextBackgroundColor: Color(0xFFF76808), + mentionTextBackgroundColor: Colors.white, + mentionTextColor: Colors.black, + mentionSelfTextColor: Colors.white, + ), + ), + ], ) ``` - - -## CometChatMessageList Properties - -Below is a list of customizations along with corresponding code snippets: - -| Property | Data Type | Description | -| ------------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------- | -| `user` | `User?` | User object for the user message list. | -| `group` | `Group?` | Group object for the group message list. | -| `messagesRequestBuilder` | `MessagesRequestBuilder?` | Custom request builder passed to CometChat's SDK. | -| `style` | `CometChatMessageListStyle?` | Sets style for the message list. | -| `scrollController` | `ScrollController?` | Controller for the message list. | -| `emptyStateText` | `String?` | Text to display when the list is empty. | -| `errorStateText` | `String?` | Text to display when an error occurs. | -| `loadingStateView` | `WidgetBuilder?` | View for the loading state. | -| `emptyStateView` | `WidgetBuilder?` | View for the empty state. | -| `errorStateView` | `WidgetBuilder?` | View for the error state behind the dialog. | -| `stateCallBack` | `Function(CometChatMessageListController controller)?` | Access controller functions from the parent. | -| `disableSoundForMessages` | `bool?` | Disables sound for sent/received messages. | -| `customSoundForMessages` | `String?` | URL for the custom sound for outgoing messages. | -| `customSoundForMessagePackage` | `String?` | Package name if the sound URL is from another package. | -| `readIcon` | `Widget?` | Custom read icon for message receipt. | -| `deliveredIcon` | `Widget?` | Custom delivered icon for message receipt. | -| `sentIcon` | `Widget?` | Custom sent icon for message receipt. | -| `waitIcon` | `Widget?` | Custom wait icon for message receipt. | -| `alignment` | `ChatAlignment` | Chat alignment setting. | -| `avatarVisibility` | `bool?` | Toggle visibility of avatars. | -| `datePattern` | `String Function(BaseMessage message)?` | Custom date pattern visible in message receipts. | -| `hideTimestamp` | `bool?` | Toggle visibility of timestamps. | -| `templates` | `List?` | Templates for the message list. | -| `onThreadRepliesClick` | `ThreadRepliesClick?` | Callback for clicking on the thread indicator. | -| `headerView` | `Widget? Function(BuildContext, {User? user, Group? group, int? parentMessageId})?` | Custom header view. | -| `footerView` | `Widget? Function(BuildContext, {User? user, Group? group, int? parentMessageId})?` | Custom footer view. | -| `dateSeparatorPattern` | `String Function(DateTime)?` | Pattern for the date separator. | -| `onError` | `OnError?` | Callback triggered when an error occurs. | -| `receiptsVisibility` | `bool?` | Controls visibility of read receipts. | -| `dateSeparatorStyle` | `CometChatDateStyle?` | Style for the date separator. | -| `disableReactions` | `bool?` | Toggle visibility of reactions. | -| `addReactionIcon` | `Widget?` | Custom icon for adding a reaction. | -| `addMoreReactionTap` | `Function(BaseMessage message)?` | Custom `onTap` for adding reactions. | -| `favoriteReactions` | `List?` | List of frequently used reactions. | -| `textFormatters` | `List?` | List of text formatters for text messages. | -| `disableMentions` | `bool?` | Disables formatting of mentions. | -| `padding` | `EdgeInsetsGeometry?` | Sets padding for the message list. | -| `margin` | `EdgeInsetsGeometry?` | Sets margin for the message list. | -| `width` | `double?` | Sets the width of the message list. | -| `height` | `double?` | Sets the height of the message list. | -| `reactionsRequestBuilder` | `ReactionsRequestBuilder?` | Fetches reactions for a specific message. | -| `onLoad` | `OnLoad?` | Callback triggered when the list is loaded. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `onReactionClick` | `Function(String? emoji, BaseMessage message)?` | Custom action for clicking on a reaction pill. | -| `onReactionLongPress` | `Function(String? emoji, BaseMessage message)?` | Custom action for long pressing on a reaction pill. | -| `onReactionListItemClick` | `Function(String? reaction, BaseMessage? message)?` | Custom action for clicking on a reaction list item. | -| `hideStickyDate` | `bool?` | Hide the date separator. | -| `hideReplyInThreadOption` | `bool?` | Hide the "Reply in Thread" option. | -| `hideTranslateMessageOption` | `bool?` | Hide the "Translate Message" option. | -| `hideEditMessageOption` | `bool?` | Hide the "Edit Message" option. | -| `hideDeleteMessageOption` | `bool?` | Hide the "Delete Message" option. | -| `hideReactionOption` | `bool?` | Hide the "Reaction" option. | -| `hideMessagePrivatelyOption` | `bool?` | Hide the "Message Privately" option. | -| `hideCopyMessageOption` | `bool?` | Hide the "Copy Message" option. | -| `hideMessageInfoOption` | `bool?` | Hide the "Message Info" option. | -| `hideGroupActionMessages` | `bool?` | Hide group action messages. | -| `enableConversationStarters` | `bool?` | Enables conversation starters in new conversations. | -| `enableSmartReplies` | `bool?` | Enables smart replies in the chat. | -| `hideShareMessageOption` | `bool?` | Hide the "Share Message" option. | -| `smartRepliesDelayDuration` | `int?` | Delay in milliseconds before triggering Smart Replies. | -| `smartRepliesKeywords` | `List?` | Keywords that trigger Smart Replies. | -| `addTemplate` | `List?` | Add custom message templates to the existing templates. | -| `dateTimeFormatterCallback` | `DateTimeFormatterCallback?` | Callback that can be used to format the date and time. | -| `hideModerationView` | `bool?` | Hide the moderation view | -| `hideThreadView` | `bool?` | Hide the thread view | -| `suggestedMessages` | `List?` | List of predefined replies for the AI assistant | -| `hideSuggestedMessages` | `bool?` | Hide the suggested messages | -| `emptyChatGreetingView` | `WidgetBuilder?` | View for empty chat view in AI assistant | -| `setAiAssistantTools` | `Map?` | Registers tool names with their corresponding callback functions | -| `streamingSpeed` | `int?` | Sets the speed of streaming for AI assistant | -| `hideDateSeparator` | `bool?` | Hide the date separator | -| `mentionAllLabelId` | `String?` | Allows setting a custom label id for group mentions (@channel, @everyone, etc.). | -| `mentionAllLabel` | `String?` | Allows setting a custom label for group mentions (@channel, @everyone, etc.). | -| `hideFlagOption` | `bool?` | Hide the visibility of the "Report" option in the message actions menu. | -| `hideFlagRemarkField` | `bool?` | Hide the remark text area in the flag message dialog. | -| `unreadMessageThreshold` | `int?` | Sets the threshold for unread messages, determining when a message is marked as unread. | -| `startFromUnreadMessages` | `bool?` | Starts the message list from the first unread message. | -| `showMarkAsUnreadOption` | `bool?` | show the visibility of the "Mark unread" option in the message actions menu. | -| `newMessageIndicatorView` | `Widget?` | Custom view for the unread message indicator. | -| `enableConversationSummary` | `bool?` | Enables conversation summary generation. | -| `generateConversationSummary` | `bool?` | Triggers conversation summary generation. | -| `hideReplyOption` | `bool?` | Hides the reply message option. | -| `flagReasonLocalizer` | `String Function(String reasonId)?` | Function to localize flag reason IDs to the desired language. | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -#### Template - -[CometChatMessageTemplate](/ui-kit/flutter/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/flutter/message-template). - -You can set message Templates to MessageList by using the following code snippet - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - templates: [], // Replace this placeholder with your custom widget. - ), -``` - - + + + - +## Advanced -**Example** +### Message Templates -Here is the complete example for reference: +[CometChatMessageTemplate](/ui-kit/flutter/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message bubbles. -```dart getTemplate() +```dart List getTemplate() { // Creating a text template CometChatMessageTemplate textTemplate = ChatConfigurator.getDataSource().getTextMessageTemplate(); @@ -500,517 +507,185 @@ List getTemplate() { color: alignment == BubbleAlignment.left ? Colors.deepPurple : Colors.yellow, fontSize: 14, fontWeight: FontWeight.bold, - fontFamily: "PlaywritePL" ), ), ); }; - // Creating an audio template - CometChatMessageTemplate audioTemplate = ChatConfigurator.getDataSource().getAudioMessageTemplate(); - // Creating a custom message template CometChatMessageTemplate customMessageTemplate = CometChatMessageTemplate( type: 'custom_template', category: 'custom_category', - bubbleView: (message, context, alignment) => const Text('this is a custom message template'), + bubbleView: (message, context, alignment) => const Text('Custom message'), ); - // custom list of templates - List messageTypes = [ - textTemplate, - audioTemplate, - customMessageTemplate - ]; - - return messageTypes; + return [textTemplate, customMessageTemplate]; } -``` - - - - - - -```dart +// Usage CometChatMessageList( - user: user, // A user or group object is required to launch this widget. + user: user, templates: getTemplate(), ) ``` - - ![Image](/images/50ecaf18-message_list_template_cometchat_screens-ccc43daa9e5eb7548207eeed5d647749.png) - - ![Image](/images/5036c31b-message_list_template_cometchat_screens-99b7ffddbb7ab979bca23fade52a1503.png) - - - - - -*** - -#### DateSeparatorPattern - -You can modify the date pattern of the message list date separator to your requirement using `setDateSeparatorPattern()`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - dateSeparatorPattern: (DateTime dateTime) { - return ""; //Replace this empty string with your custom date time pattern. - }, -) -``` - - -**Example** +### Date Separator Pattern -Here is the complete example for reference: +Customize the date separator pattern: ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. + user: user, dateSeparatorPattern: (DateTime dateTime) { return DateFormat("dd/MM/yyyy").format(dateTime); }, ) ``` - - ![Image](/images/49078272-message_list_date_time_separator_cometchat_screens-d90f711f80300c16d7f229543e3b7b23.png) - - ![Image](/images/b552b788-message_list_date_time_separator_cometchat_screens-dad8d61b105cdb2a5b3a9e5401c1a51c.png) - - - - - -*** - -#### SetDatePattern - -You can modify the date pattern to your requirement using .setDatePattern. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - datePattern: (message) { - return DateFormat('YOUR_PATTERN').format(message.sentAt!); - }, -) -``` - - -**Example** +### Date Pattern -Here is the complete example for reference: +Customize the date pattern for message receipts: ```dart CometChatMessageList( - user: user, // A user or group object is required to launch this widget. + user: user, datePattern: (message) { return DateFormat('EEE, M/d/y').format(message.sentAt!); }, ) ``` - - ![Image](/images/7502494d-message_list_date_time_pattern_cometchat_screens-e29fe0e35e14bba04954bb7702abbdeb.png) - - ![Image](/images/36b9b0ae-message_list_date_time_pattern_cometchat_screens-601f4e68966053f11c3682665b8d3cb2.png) - - - - - -*** - -#### loadingStateView - -Customizes the loading indicator when messages are being fetched. - -Use Cases: - -* Show a spinner or skeleton loader for smooth UX. -* Display a "Fetching messages..." text. - - - -```dart -CometChatMessageList( - loadingStateView: (context) { - // return leading view - }, -) -``` - - - - - -*** - -#### emptyStateView - -Defines a custom view to be displayed when no messages are available. - -Use Cases: - -* Show a friendly message like "No messages yet. Start the conversation!". - - - -```dart -CometChatMessageList( - emptyStateView: (context) { - // return empty view - }, -) -``` - - - - - -*** - -#### errorStateView - -Custom error state view displayed when fetching messages fails. - -Use Cases: - -* Show a retry button when an error occurs. -* Display a friendly message like "Couldn't load messages. Check your connection.". - - - -```dart -CometChatMessageList( - errorStateView: (context) { - // return error view - }, -) -``` - - - - -*** - -#### TextFormatters - -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [MentionsFormatter Guide](/ui-kit/flutter/mentions-formatter-guide) - -Here is the complete example for reference: - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - textFormatters: [ - CometChatMentionsFormatter( - style: CometChatMentionsStyle( - mentionSelfTextBackgroundColor: Color(0xFFF76808), - mentionTextBackgroundColor: Colors.white, - mentionTextColor: Colors.black, - mentionSelfTextColor: Colors.white, - ) - ) - ], -) -``` - - - - - - - - - -*** - -#### HeaderView - -Allows developers to set a custom widget as the header of the message list. It provides context and access to `user`, `group`, and `parentMessageId`, enabling tailored designs for different use cases, such as displaying user details or group information. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - headerView: (context, {group, parentMessageId, user}) => - MessageListHeader( - backgroundColor: const Color(0XFFEDEAFA), - color: const Color(0XFF6852D6), - ), -) -``` - - - - -```dart -class MessageListHeader extends StatelessWidget { - const MessageListHeader( - {Key? key, required this.backgroundColor, required this.color}) - : super(key: key); - - final Color backgroundColor; - final Color color; - - @override - Widget build(BuildContext context) { - return Container( - width: double.maxFinite, - color: backgroundColor, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 3), - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: [ - _buildHeaderItem( - icon: Icons.notes_outlined, - label: 'Notes', - color: color, - ), - _buildHeaderItem( - icon: Icons.bookmark, - label: 'Pinned Messages', - color: color, - ), - _buildHeaderItem( - icon: Icons.link, - label: 'Saved Links', - color: color, - ), - ], - ), - ), - ); - } - - Widget _buildHeaderItem( - {required IconData icon, required String label, required Color color}) { - return Container( - margin: const EdgeInsets.symmetric(horizontal: 5), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(30), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.1), - blurRadius: 8, - offset: const Offset(0, 4), - ), - ], - ), - child: Row( - children: [ - Icon( - icon, - color: color, - size: 20, - ), - const SizedBox(width: 4), - Text( - label, - style: TextStyle( - color: color, - fontSize: 12, - fontWeight: FontWeight.w400, - letterSpacing: 0), - ), - ], - ), - ); - } -} -``` - - - - - - - - - -*** - -#### FooterView - -Enables developers to add a custom widget to the footer of the message list. Like `headerView`, it supports `user`, `group`, and `parentMessageId` for context, offering flexibility to add components like timestamps, typing indicators, or action buttons. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - footerView: (context, {group, parentMessageId, user}) => - MessageListFooter( - backgroundColor: const Color(0XFFEDEAFA), - color: const Color(0XFF6852D6), - ), -) -``` - - - - -```dart -class MessageListFooter extends StatelessWidget { - const MessageListFooter( - {Key? key, required this.backgroundColor, required this.color}) - : super(key: key); - - final Color backgroundColor; - final Color color; - - @override - Widget build(BuildContext context) { - return Container( - width: double.maxFinite, - color: backgroundColor, - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 3), - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: [ - _buildFooterItem( - icon: Icons.sunny, - label: 'Ice Breakers', - color: color, - ), - _buildFooterItem( - icon: Icons.phone, - label: '+1-212-456-7890', - color: color, - ), - _buildFooterItem( - icon: Icons.photo_camera, - label: 'Instagram', - color: color, - ), - ], - ), - ), - ); - } - - Widget _buildFooterItem( - {required IconData icon, required String label, required Color color}) { - return Container( - margin: const EdgeInsets.symmetric(horizontal: 5), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(30), - boxShadow: [ - BoxShadow( - color: Colors.black.withOpacity(0.1), - blurRadius: 8, - offset: const Offset(0, 4), - ), - ], - ), - child: Row( - children: [ - Icon( - icon, - color: color, - size: 20, - ), - const SizedBox(width: 4), - Text( - label, - style: TextStyle( - color: color, - fontSize: 12, - fontWeight: FontWeight.w400, - letterSpacing: 0), - ), - ], - ), - ); - } -} -``` - - - - - - - - - -*** - -#### newMessageIndicatorView - -Customizes the unread message indicator view. - -Use Cases: - -* Set a custom view for the unread message indicator. - - - -```dart -CometChatMessageList( - user: user, // A user or group object is required to launch this widget. - newMessageIndicatorView: CustomWidget(), // your custom widget -) -``` - - - -*** +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `user` | `User?` | `null` | User object for user message list | +| `group` | `Group?` | `null` | Group object for group message list | +| `messagesRequestBuilder` | `MessagesRequestBuilder?` | `null` | Custom request builder for filtering | +| `style` | `CometChatMessageListStyle?` | - | Sets style for message list | +| `scrollController` | `ScrollController?` | - | Controller for the message list | +| `emptyStateText` | `String?` | - | Text when list is empty | +| `errorStateText` | `String?` | - | Text when error occurs | +| `loadingStateView` | `WidgetBuilder?` | - | View for loading state | +| `emptyStateView` | `WidgetBuilder?` | - | View for empty state | +| `errorStateView` | `WidgetBuilder?` | - | View for error state | +| `disableSoundForMessages` | `bool?` | `null` | Disables sound for messages | +| `customSoundForMessages` | `String?` | `null` | Custom sound URL | +| `readIcon` | `Widget?` | - | Custom read icon | +| `deliveredIcon` | `Widget?` | - | Custom delivered icon | +| `sentIcon` | `Widget?` | - | Custom sent icon | +| `waitIcon` | `Widget?` | - | Custom wait icon | +| `alignment` | `ChatAlignment` | `standard` | Chat alignment setting | +| `avatarVisibility` | `bool?` | `true` | Toggle avatar visibility | +| `datePattern` | `String Function(BaseMessage)?` | - | Custom date pattern | +| `hideTimestamp` | `bool?` | `null` | Toggle timestamp visibility | +| `templates` | `List?` | - | Message templates | +| `onThreadRepliesClick` | `ThreadRepliesClick?` | - | Thread replies callback | +| `headerView` | `Widget? Function(...)?` | - | Custom header view | +| `footerView` | `Widget? Function(...)?` | - | Custom footer view | +| `dateSeparatorPattern` | `String Function(DateTime)?` | - | Date separator pattern | +| `onError` | `OnError?` | - | Error callback | +| `receiptsVisibility` | `bool?` | `true` | Toggle read receipts | +| `dateSeparatorStyle` | `CometChatDateStyle?` | - | Date separator style | +| `disableReactions` | `bool?` | `false` | Toggle reactions | +| `addReactionIcon` | `Widget?` | - | Custom add reaction icon | +| `favoriteReactions` | `List?` | - | Frequently used reactions | +| `textFormatters` | `List?` | - | Text formatters | +| `disableMentions` | `bool?` | `null` | Disable mentions | +| `padding` | `EdgeInsetsGeometry?` | - | Padding for message list | +| `margin` | `EdgeInsetsGeometry?` | - | Margin for message list | +| `width` | `double?` | - | Width of message list | +| `height` | `double?` | - | Height of message list | +| `onLoad` | `OnLoad?` | - | Load callback | +| `onEmpty` | `OnEmpty?` | - | Empty callback | +| `onReactionClick` | `Function(String?, BaseMessage)?` | - | Reaction click callback | +| `onReactionLongPress` | `Function(String?, BaseMessage)?` | - | Reaction long press callback | +| `hideStickyDate` | `bool?` | `false` | Hide sticky date | +| `hideReplyInThreadOption` | `bool?` | `false` | Hide reply in thread option | +| `hideTranslateMessageOption` | `bool?` | `false` | Hide translate option | +| `hideEditMessageOption` | `bool?` | `false` | Hide edit option | +| `hideDeleteMessageOption` | `bool?` | `false` | Hide delete option | +| `hideReactionOption` | `bool?` | `false` | Hide reaction option | +| `hideMessagePrivatelyOption` | `bool?` | `false` | Hide message privately option | +| `hideCopyMessageOption` | `bool?` | `false` | Hide copy option | +| `hideMessageInfoOption` | `bool?` | `false` | Hide message info option | +| `hideGroupActionMessages` | `bool?` | `false` | Hide group action messages | +| `enableConversationStarters` | `bool?` | `false` | Enable conversation starters | +| `enableSmartReplies` | `bool?` | `false` | Enable smart replies | +| `hideShareMessageOption` | `bool?` | `false` | Hide share option | +| `smartRepliesDelayDuration` | `int?` | `10000` | Smart replies delay (ms) | +| `smartRepliesKeywords` | `List?` | - | Smart replies keywords | +| `addTemplate` | `List?` | - | Add custom templates | +| `dateTimeFormatterCallback` | `DateTimeFormatterCallback?` | - | Date time formatter | +| `hideModerationView` | `bool?` | `null` | Hide moderation view | +| `hideThreadView` | `bool?` | `null` | Hide thread view | +| `suggestedMessages` | `List?` | - | AI assistant suggestions | +| `hideSuggestedMessages` | `bool?` | `false` | Hide suggested messages | +| `emptyChatGreetingView` | `WidgetBuilder?` | - | Empty chat greeting view | +| `setAiAssistantTools` | `Map?` | - | AI assistant tools | +| `streamingSpeed` | `int?` | - | AI streaming speed | +| `hideDateSeparator` | `bool?` | `false` | Hide date separator | +| `mentionAllLabel` | `String?` | - | Group mention label | +| `mentionAllLabelId` | `String?` | - | Group mention label ID | +| `hideFlagOption` | `bool?` | `false` | Hide report option | +| `hideFlagRemarkField` | `bool?` | `false` | Hide flag remark field | +| `startFromUnreadMessages` | `bool?` | `false` | Start from unread messages | +| `showMarkAsUnreadOption` | `bool?` | `false` | Show mark as unread option | +| `newMessageIndicatorView` | `WidgetBuilder?` | - | New message indicator view | +| `enableConversationSummary` | `bool?` | `false` | Enable conversation summary | +| `generateConversationSummary` | `bool?` | `false` | Generate conversation summary | +| `hideReplyOption` | `bool?` | `false` | Hide reply option | +| `flagReasonLocalizer` | `String Function(String)?` | - | Flag reason localizer | + + + + Display user or group details in the header + + + Compose and send messages + + + Customize message bubble templates + + + Learn how to customize the look and feel + + diff --git a/ui-kit/flutter/search.mdx b/ui-kit/flutter/search.mdx index e4511c558..34a29c7d2 100644 --- a/ui-kit/flutter/search.mdx +++ b/ui-kit/flutter/search.mdx @@ -1,34 +1,142 @@ --- title: "Search" +description: "A powerful search interface for finding conversations and messages in real time" --- -## Overview + +```json +{ + "component": "CometChatSearch", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A powerful search interface that allows users to search across conversations and messages in real time with filters and customization options", + "primaryOutput": { + "prop": "onMessageClicked", + "type": "void Function(BaseMessage message)" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "null", + "note": "User object for user message search" + }, + "group": { + "type": "Group?", + "default": "null", + "note": "Group object for group message search" + }, + "searchFilters": { + "type": "List?", + "default": "null", + "note": "List of filters to be shown in the search screen" + }, + "searchIn": { + "type": "List?", + "default": "null", + "note": "List of scopes to be shown in the search result" + } + }, + "callbacks": { + "onBack": "VoidCallback?", + "onConversationClicked": "void Function(Conversation conversation)?", + "onMessageClicked": "void Function(BaseMessage message)?", + "onError": "OnError?", + "onConversationsLoad": "OnLoad?", + "onMessagesLoad": "OnLoad?", + "onEmpty": "OnEmpty?" + }, + "visibility": { + "usersStatusVisibility": { + "type": "bool?", + "default": "null" + }, + "receiptsVisibility": { + "type": "bool?", + "default": "null" + }, + "groupTypeVisibility": { + "type": "bool?", + "default": "null" + } + }, + "viewSlots": { + "loadingStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "initialStateView": "WidgetBuilder?", + "conversationItemView": "Widget? Function(BuildContext, Conversation)?", + "conversationTitleView": "Widget? Function(BuildContext, Conversation)?", + "conversationLeadingView": "Widget? Function(BuildContext, Conversation)?", + "conversationSubtitleView": "Widget? Function(BuildContext, Conversation)?", + "conversationTailView": "Widget? Function(BuildContext, Conversation)?", + "searchTextMessageView": "Widget? Function(BuildContext, TextMessage)?", + "searchImageMessageView": "Widget? Function(BuildContext, MediaMessage)?", + "searchVideoMessageView": "Widget? Function(BuildContext, MediaMessage)?", + "searchFileMessageView": "Widget? Function(BuildContext, MediaMessage)?", + "searchAudioMessageView": "Widget? Function(BuildContext, MediaMessage)?", + "searchMessageLinkView": "Widget? Function(BuildContext, BaseMessage)?" + }, + "formatting": { + "dateSeparatorFormatterCallback": { + "type": "DateTimeFormatterCallback?", + "default": "null" + }, + "timeSeparatorFormatterCallback": { + "type": "DateTimeFormatterCallback?", + "default": "null" + } + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CometChatSearch can be used standalone or embedded within other screens", + "components": ["CometChatConversations", "CometChatMessageList"], + "flow": "User searches → Results displayed → User clicks result → Navigate to conversation/message" + }, + "types": { + "SearchFilter": { + "label": "String", + "icon": "Widget?" + }, + "SearchScope": { + "conversations": "bool", + "messages": "bool" + } + } +} +``` + + +## Where It Fits -The `CometChatSearch` component is a powerful and customizable search interface that allows users to search across conversations and messages in real time. It supports a wide variety of filters, scopes, and customization options. `CometChatSearch` helps users find messages, conversations, media, and more through an intuitive and filterable search experience. It can be embedded in multiple contexts — as part of the conversation list, message header, or as a full-screen search experience. +CometChatSearch is a full-screen search experience that allows users to find messages, conversations, media, and more through an intuitive and filterable search interface. It can be embedded in multiple contexts — as part of the conversation list, message header, or as a standalone full-screen search experience. -## Usage - -### Integration - -You can launch `CometChatSearch` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. +## Minimal Render -##### 1. Using Navigator to Launch `CometChatSearch` +The simplest way to render CometChatSearch: ```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatSearch())); -``` +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; +// Using Navigator to launch CometChatSearch +Navigator.push( + context, + MaterialPageRoute(builder: (context) => CometChatSearch()) +); +``` - -##### 2. Embedding `CometChatSearch` as a Widget in the build Method +You can also embed it as a widget: @@ -36,330 +144,344 @@ Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatSearch( import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; -class SearchComponent extends StatefulWidget { - const SearchComponent({super.key}); - - @override - State createState() => _SearchComponentState(); -} - -class _SearchComponentState extends State { - +class SearchScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - body: SafeArea( - child: CometChatSearch(), - ) + body: SafeArea( + child: CometChatSearch(), + ), ); } } ``` - - -*** +## Filtering -### Actions +Use the request builder props to filter which items appear in the search results. -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +### ConversationsRequestBuilder -#### 1. onConversationClicked - -`onConversationClicked` is triggered when you click on a Conversation from the search result. The `onConversationClicked` action doesn’t have a predefined behavior. You can override this action using the following code snippet. +Filter conversations in the search results: ```dart - CometChatSearch( - onConversationClicked: (conversation) { - // Handle conversation click - }, - ); +CometChatSearch( + conversationsRequestBuilder: ConversationsRequestBuilder() + ..limit = 30, +) ``` - -*** +### MessagesRequestBuilder -#### 2. onMessageClicked - -`onMessageClicked` is triggered when you click on a Message from the search result. The `onMessageClicked` action doesn’t have a predefined behavior. You can override this action using the following code snippet. +Filter messages in the search results: ```dart - CometChatSearch( - onMessageClicked: (message) { - // Handle message click - }, - ); +CometChatSearch( + messagesRequestBuilder: MessagesRequestBuilder() + ..limit = 50, +) ``` - -*** - -#### 3. onBack +### Scoped Search -`OnBack` is triggered when you click on the back button of the Message Header component. You can override this action using the following code snippet. +Search within a specific user or group conversation: ```dart - CometChatSearch( - onBack: () { - // Handle back action - }, - ); -``` - - - - -*** - -#### 4. onError - -This action doesn’t change the behavior of the component but rather listens for any errors that occur in the Conversations component. +// Search within a specific user's conversation +CometChatSearch( + user: user, +) - - -```dart - CometChatSearch( - onError: (e) { - // Handle error - }, - ); +// Search within a specific group's conversation +CometChatSearch( + group: group, +) ``` - -*** +## Actions and Events -### Filters +### Callback Props -#### 1. ConversationsRequestBuilder +Component-level callbacks that fire on specific user interactions: -You can set the `ConversationsRequestBuilder` in the Search Component to filter the search result. You can modify the builder as per your specific requirements with multiple options available to know more refer to `ConversationRequestBuilder`. +| Callback | Signature | Fires When | +|----------|-----------|------------| +| `onConversationClicked` | `void Function(Conversation conversation)?` | User clicks a conversation from search results | +| `onMessageClicked` | `void Function(BaseMessage message)?` | User clicks a message from search results | +| `onBack` | `VoidCallback?` | User clicks the back button | +| `onError` | `OnError?` | An error occurs in the component | +| `onConversationsLoad` | `OnLoad?` | Conversations are loaded | +| `onMessagesLoad` | `OnLoad?` | Messages are loaded | +| `onEmpty` | `OnEmpty?` | Search results are empty | ```dart - CometChatSearch( - conversationsRequestBuilder: ConversationsRequestBuilder(), - ); +CometChatSearch( + onConversationClicked: (conversation) { + // Navigate to the conversation + print('Conversation clicked: ${conversation.conversationId}'); + }, + onMessageClicked: (message) { + // Navigate to the message + print('Message clicked: ${message.id}'); + }, + onBack: () { + Navigator.pop(context); + }, + onError: (e) { + print('Error: $e'); + }, +) ``` - -*** - -#### 2. MessagesRequestBuilder - -You can set the `MessagesRequestBuilder` in the Search Component to filter the search result. You can modify the builder as per your specific requirements with multiple options available to know more refer to `MessagesRequestBuilder`. - - - -```dart - CometChatSearch( - messagesRequestBuilder: MessagesRequestBuilder(), - ); -``` - - - +### Global UI Events -*** +The CometChatSearch component does not produce any global UI events. -## Events +## Custom View Slots -`Events` are emitted by a Component. By using event you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. +Customize the appearance of CometChatSearch by replacing default views with your own widgets. -The `CometChatSearch` component does not produce any events. +### State Views -*** +| Slot | Signature | Replaces | +|------|-----------|----------| +| `loadingStateView` | `WidgetBuilder?` | Loading spinner | +| `emptyStateView` | `WidgetBuilder?` | Empty state display | +| `errorStateView` | `WidgetBuilder?` | Error state display | +| `initialStateView` | `WidgetBuilder?` | Initial state before search | -## Customization +### Conversation View Slots -To fit your app’s design requirements, you can customize the appearance of the `CometChatSearch` component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +| Slot | Signature | Replaces | +|------|-----------|----------| +| `conversationItemView` | `Widget? Function(BuildContext, Conversation)?` | Entire conversation list item | +| `conversationLeadingView` | `Widget? Function(BuildContext, Conversation)?` | Avatar / left section | +| `conversationTitleView` | `Widget? Function(BuildContext, Conversation)?` | Name / title text | +| `conversationSubtitleView` | `Widget? Function(BuildContext, Conversation)?` | Secondary text / preview | +| `conversationTailView` | `Widget? Function(BuildContext, Conversation)?` | Right section / timestamp | -## Style +### Message View Slots -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +| Slot | Signature | Replaces | +|------|-----------|----------| +| `searchTextMessageView` | `Widget? Function(BuildContext, TextMessage)?` | Text message item | +| `searchImageMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | Image message item | +| `searchVideoMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | Video message item | +| `searchFileMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | File message item | +| `searchAudioMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | Audio message item | +| `searchMessageLinkView` | `Widget? Function(BuildContext, BaseMessage)?` | Link message item | - - - +### Example: Custom Text Message View ```dart CometChatSearch( - searchStyle: CometChatSearchStyle( - backgroundColor: const Color(0xFFEDEAFA), - searchFilterChipTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchSectionHeaderTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - - searchConversationItemBackgroundColor: const Color(0xFFEDEAFA), - searchConversationSubTitleTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchConversationTitleTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchConversationDateTextStyle: const TextStyle( - fontFamily: 'TimesNewRoman', - fontWeight: FontWeight.bold, - ), - - searchSeeMoreStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - - searchMessageItemBackgroundColor: const Color(0xFFEDEAFA), - searchMessageTitleTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchMessageSubTitleTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - searchMessageTimeStampStyle: CometChatDateStyle( - textStyle: const TextStyle(fontFamily: 'TimesNewRoman'), - ), - - searchTextStyle: const TextStyle(fontFamily: 'TimesNewRoman'), + searchTextMessageView: (context, message) { + String senderName = message.sender?.name ?? "Unknown"; + return Container( + padding: const EdgeInsets.all(16), + width: double.infinity, + color: const Color(0xFFE8E4F3), + child: Row( + children: [ + Text( + "$senderName: ", + style: const TextStyle( + color: Color(0xFF6B4FBB), + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + Expanded( + child: Text( + message.text, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + color: Color(0xFF4A4A4A), + fontSize: 16, + ), + ), + ), + ], ), ); + }, +) ``` - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets - -## CometChatMessageHeader Properties - -Following is a list of customizations along with their corresponding code snippets: - -| Property | Data Type | Description | -| --------------------- | -------------------------| ----------------------------------------------------------------- | -| `user` | `User?` | Set `User` object, one is mandatory either `user` or `group`. | -| `group` | `Group?` | Set `Group` object, one is mandatory either `user` or `group`. | -| `usersStatusVisibility` | `bool?` | Controls visibility of status indicator shown if a user is online. | -| `groupTypeVisibility` | `bool?` | Hide the group type icon which is visible on the group icon. | -| `initialStateView` | `WidgetBuilder?` | Sets view fow initial state | -| `loadingStateView` | `WidgetBuilder?` | Sets view fow loading state | -| `emptyStateView` | `WidgetBuilder?` | Sets view fow empty state | -| `errorStateView` | `WidgetBuilder?` | Sets view fow error state | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -*** - -#### conversationItemView - -With this function, you can assign a custom list item view to an conversation in the search result. For more information, refer to the [listItemView](/ui-kit/flutter/conversations#listitemview) prop of the `CometChatConversations` component. - - -#### conversationLeadingView - -With this function, you can assign a custom leading view to an conversation in the search result. For more information, refer to the [leadingView](/ui-kit/flutter/conversations#leadingview) prop of the `CometChatConversations` component. - - -#### conversationTitleView - -With this function, you can assign a custom title view of an conversation in the search result. For more information, refer to the [titleview](/ui-kit/flutter/conversations#titleview) prop of the `CometChatConversations` component. - -#### conversationSubtitleView - -With this function, you can assign a custom subtitle view to an conversation in the search result. For more information, refer to the [subtitleview](/ui-kit/flutter/conversations#subtitleview) prop of the `CometChatConversations` component. - + + + -#### conversationTailView +### Icon Customization -With this function, you can assign a custom tail view to an conversation in the search result. For more information, refer to the [trailingview](/ui-kit/flutter/conversations#trailingview) prop of the `CometChatConversations` component. +| Prop | Type | Description | +|------|------|-------------| +| `searchBackIcon` | `Widget?` | Custom back icon | +| `searchClearIcon` | `Widget?` | Custom clear icon | -#### MessageItemView +## Styling -With message item view functions, you can assign custom views to different types of messages in the search result. +Customize the appearance of CometChatSearch using `CometChatSearchStyle`. -Here’s how you can override the default message item view with a custom one for text messages: + + + ```dart CometChatSearch( - searchTextMessageView: (context, message) { - String senderName = message.sender?.name ?? "Unknown"; - String messageText = ""; - messageText = message.text; - return Container( - padding: const EdgeInsets.all(16), - width: double.infinity, - color: const Color(0xFFE8E4F3), - child: Row( - children: [ - Text( - "$senderName: ", - style: const TextStyle( - color: Color(0xFF6B4FBB), - fontSize: 16, - fontWeight: FontWeight.bold, - ), - ), - Expanded( - child: Text( - messageText, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - color: Color(0xFF4A4A4A), - fontSize: 16, - ), - ), - ), - ], - ), - ); - }, - ); + searchStyle: CometChatSearchStyle( + backgroundColor: const Color(0xFFEDEAFA), + searchBackgroundColor: Colors.white, + searchTextColor: Colors.black, + searchPlaceHolderTextColor: Colors.grey, + + // Filter chip styling + searchFilterChipBackgroundColor: Colors.grey[200], + searchFilterChipSelectedBackgroundColor: Colors.purple, + searchFilterChipTextColor: Colors.black, + searchFilterChipSelectedTextColor: Colors.white, + + // Conversation item styling + searchConversationItemBackgroundColor: const Color(0xFFEDEAFA), + searchConversationTitleTextStyle: const TextStyle(fontWeight: FontWeight.bold), + searchConversationSubTitleTextStyle: const TextStyle(color: Colors.grey), + + // Message item styling + searchMessageItemBackgroundColor: const Color(0xFFEDEAFA), + searchMessageTitleTextStyle: const TextStyle(fontWeight: FontWeight.bold), + + // See more button + searchSeeMoreColor: Colors.purple, + ), +) ``` - - - - - - -Bellow is the list of message item view functions available for customization: - -| Function | Message Type | -| ----------------------------| -------------------------| -| `searchTextMessageView` | Text Message | -| `searchImageMessageView` | Image Message | -| `searchAudioMessageView` | Audio Message | -| `searchFileMessageView` | Document Message | -| `searchMessageLinkView` | Link Message | -| `searchVideoMessageView` | Video Message | - -#### DateTime Formatters - -#### dateSeparatorFormatterCallback - -You can modify the date pattern of the chat history date separator to your requirement using `dateSeparatorFormatterCallback`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - -#### TextFormatters - -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [MentionsFormatter Guide](/ui-kit/flutter/mentions-formatter-guide) - -*** +### Style Properties + +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `Color?` | Background color of the search component | +| `searchBackgroundColor` | `Color?` | Background color of the search text field | +| `searchBorder` | `BorderSide?` | Border of the search text field | +| `searchBorderRadius` | `BorderRadius?` | Border radius of the search text field | +| `searchTextColor` | `Color?` | Color of the search text | +| `searchTextStyle` | `TextStyle?` | Style of the search text | +| `searchPlaceHolderTextColor` | `Color?` | Color of the placeholder text | +| `searchPlaceHolderTextStyle` | `TextStyle?` | Style of the placeholder text | +| `searchBackIconColor` | `Color?` | Color of the back icon | +| `searchClearIconColor` | `Color?` | Color of the clear icon | +| `searchFilterChipBackgroundColor` | `Color?` | Background color of filter chips | +| `searchFilterChipSelectedBackgroundColor` | `Color?` | Background color of selected filter chips | +| `searchFilterChipTextColor` | `Color?` | Text color of filter chips | +| `searchFilterChipSelectedTextColor` | `Color?` | Text color of selected filter chips | +| `searchFilterChipBorder` | `Border?` | Border of filter chips | +| `searchFilterChipSelectedBorder` | `Border?` | Border of selected filter chips | +| `searchFilterChipBorderRadius` | `BorderRadius?` | Border radius of filter chips | +| `searchSectionHeaderTextColor` | `Color?` | Color of section header text | +| `searchSectionHeaderTextStyle` | `TextStyle?` | Style of section header text | +| `searchConversationItemBackgroundColor` | `Color?` | Background color of conversation items | +| `searchConversationTitleTextColor` | `Color?` | Text color of conversation titles | +| `searchConversationTitleTextStyle` | `TextStyle?` | Style of conversation titles | +| `searchConversationSubTitleTextStyle` | `TextStyle?` | Style of conversation subtitles | +| `searchConversationTitleSubTextColor` | `Color?` | Text color of conversation subtitles | +| `searchConversationDateTextColor` | `Color?` | Text color of conversation dates | +| `searchConversationDateTextStyle` | `TextStyle?` | Style of conversation dates | +| `searchMessageItemBackgroundColor` | `Color?` | Background color of message items | +| `searchMessageTitleTextColor` | `Color?` | Text color of message titles | +| `searchMessageTitleTextStyle` | `TextStyle?` | Style of message titles | +| `searchMessageSubTitleTextColor` | `Color?` | Text color of message subtitles | +| `searchMessageSubTitleTextStyle` | `TextStyle?` | Style of message subtitles | +| `searchMessageTimeStampStyle` | `CometChatDateStyle?` | Style of message timestamps | +| `searchMessageDateSeparatorStyle` | `CometChatDateStyle?` | Style of date separators | +| `searchEmptyStateTextColor` | `Color?` | Text color for empty state | +| `searchEmptyStateTextStyle` | `TextStyle?` | Style for empty state text | +| `searchErrorStateTextColor` | `Color?` | Text color for error state | +| `searchErrorStateTextStyle` | `TextStyle?` | Style for error state text | +| `searchSeeMoreColor` | `Color?` | Color of "See More" button | +| `searchSeeMoreStyle` | `TextStyle?` | Style of "See More" button | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for avatars | +| `badgeStyle` | `CometChatBadgeStyle?` | Style for badges | + +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `user` | `User?` | `null` | User object for scoped search | +| `group` | `Group?` | `null` | Group object for scoped search | +| `searchFilters` | `List?` | `null` | List of filters to show | +| `searchIn` | `List?` | `null` | List of search scopes | +| `usersStatusVisibility` | `bool?` | `null` | Show/hide user status indicator | +| `receiptsVisibility` | `bool?` | `null` | Show/hide message receipts | +| `groupTypeVisibility` | `bool?` | `null` | Show/hide group type icon | +| `onBack` | `VoidCallback?` | `null` | Back button callback | +| `onConversationClicked` | `Function(Conversation)?` | `null` | Conversation click callback | +| `onMessageClicked` | `Function(BaseMessage)?` | `null` | Message click callback | +| `onError` | `OnError?` | `null` | Error callback | +| `onConversationsLoad` | `OnLoad?` | `null` | Conversations load callback | +| `onMessagesLoad` | `OnLoad?` | `null` | Messages load callback | +| `onEmpty` | `OnEmpty?` | `null` | Empty state callback | +| `loadingStateView` | `WidgetBuilder?` | `null` | Custom loading view | +| `errorStateView` | `WidgetBuilder?` | `null` | Custom error view | +| `emptyStateView` | `WidgetBuilder?` | `null` | Custom empty view | +| `initialStateView` | `WidgetBuilder?` | `null` | Custom initial view | +| `conversationItemView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation item | +| `conversationTitleView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation title | +| `conversationLeadingView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation leading view | +| `conversationSubtitleView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation subtitle | +| `conversationTailView` | `Widget? Function(BuildContext, Conversation)?` | `null` | Custom conversation tail view | +| `searchTextMessageView` | `Widget? Function(BuildContext, TextMessage)?` | `null` | Custom text message view | +| `searchImageMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | `null` | Custom image message view | +| `searchVideoMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | `null` | Custom video message view | +| `searchFileMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | `null` | Custom file message view | +| `searchAudioMessageView` | `Widget? Function(BuildContext, MediaMessage)?` | `null` | Custom audio message view | +| `searchMessageLinkView` | `Widget? Function(BuildContext, BaseMessage)?` | `null` | Custom link message view | +| `searchBackIcon` | `Widget?` | `null` | Custom back icon | +| `searchClearIcon` | `Widget?` | `null` | Custom clear icon | +| `dateSeparatorFormatterCallback` | `DateTimeFormatterCallback?` | `null` | Date separator formatter | +| `timeSeparatorFormatterCallback` | `DateTimeFormatterCallback?` | `null` | Time separator formatter | +| `conversationsProtocol` | `ConversationsBuilderProtocol?` | `null` | Conversations builder protocol | +| `conversationsRequestBuilder` | `ConversationsRequestBuilder?` | `null` | Conversations request builder | +| `messagesRequestBuilder` | `MessagesRequestBuilder?` | `null` | Messages request builder | +| `searchStyle` | `CometChatSearchStyle?` | `null` | Style configuration | + + + + Display and manage chat conversations + + + Display messages in a conversation + + + Learn how to customize the look and feel + + + Support multiple languages in your app + + diff --git a/ui-kit/flutter/threaded-messages-header.mdx b/ui-kit/flutter/threaded-messages-header.mdx index 5d92d9182..e9383fcf6 100644 --- a/ui-kit/flutter/threaded-messages-header.mdx +++ b/ui-kit/flutter/threaded-messages-header.mdx @@ -1,41 +1,120 @@ --- title: "Threaded Messages Header" +description: "A widget that displays the parent message of a thread with reply count" --- -## Overview + +```json +{ + "component": "CometChatThreadedHeader", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "A widget that displays the parent message of a thread along with a reply count, used as the header section in threaded message views", + "primaryOutput": { + "prop": "messageActionView", + "type": "Widget Function(BaseMessage message, BuildContext context)?" + }, + "props": { + "data": { + "parentMessage": { + "type": "BaseMessage", + "required": true, + "note": "Parent message for the thread" + }, + "loggedInUser": { + "type": "User", + "required": true, + "note": "Logged in user object" + }, + "template": { + "type": "CometChatMessageTemplate?", + "default": "null", + "note": "Message template used in the thread" + }, + "height": { + "type": "double?", + "default": "null", + "note": "Height of the widget" + }, + "width": { + "type": "double?", + "default": "null", + "note": "Width of the widget" + } + }, + "visibility": { + "receiptsVisibility": { + "type": "bool?", + "default": true + } + }, + "viewSlots": { + "messageActionView": "Widget Function(BaseMessage message, BuildContext context)?" + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CometChatThreadedHeader is typically used within CometChatThreadedMessages as the header component", + "components": ["CometChatThreadedMessages", "CometChatMessageList", "CometChatMessageComposer"], + "flow": "Parent message displayed at top → Reply count shown → Message list below with replies" + }, + "types": {} +} +``` + -ThreadedMessages is a [Composite Widget](/ui-kit/flutter/components-overview#composite-components) that displays all replies made to a particular message in a conversation. By default, the parent message will be displayed at the top, the message composer will be at the bottom and between them a message list will contain all replies. +## Where It Fits + +CometChatThreadedHeader is a component that displays the parent message of a thread along with a reply count. It's typically used as part of the ThreadedMessages composite component, appearing at the top of the threaded conversation view. + +ThreadedMessages is composed of the following widgets: + +| Widget | Description | +|--------|-------------| +| [MessageList](/ui-kit/flutter/message-list) | CometChatMessageList displays a list of reply messages | +| [MessageComposer](/ui-kit/flutter/message-composer) | CometChatMessageComposer helps in writing and sending replies | -ThreadedMessages is composed of the following widgets: - -| Widget | Description | -| -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| [MessageList](/ui-kit/flutter/message-list) | CometChatMessageList is a widget that displays a list of Messages | -| [MessageComposer](/ui-kit/flutter/message-composer) | CometChatMessageComposer is a widget that helps in writing and editing of messages and also sending attachments | +## Minimal Render -## Usage +The simplest way to render CometChatThreadedHeader: -### Integration + + +```dart +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -You can launch `CometChatThreadedHeader` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. +CometChatThreadedHeader( + parentMessage: parentMessage, // Required: BaseMessage object + loggedInUser: loggedInUser, // Required: User object +) +``` + + -##### 1. Using Navigator to Launch `CometChatThreadedHeader` +You can also launch it using Navigator: ```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => CometChatThreadedHeader(loggedInUser: loggedInUser, parentMessage: parentMessage))); // Logged in user object and parent message object is required to launch this widget. +Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatThreadedHeader( + loggedInUser: loggedInUser, + parentMessage: parentMessage, + ), + ), +); ``` - - -##### 2. Embedding `CometChatThreadedHeader` as a Widget in the build Method +Or embed it as a widget: @@ -51,146 +130,41 @@ class ThreadMessages extends StatefulWidget { } class _ThreadMessagesState extends State { - @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( - child: CometChatThreadedHeader(loggedInUser: loggedInUser, parentMessage: parentMessage) // Logged in user object and parent message object is need. + child: CometChatThreadedHeader( + loggedInUser: loggedInUser, + parentMessage: parentMessage, + ), ), ); } } ``` - - -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -*** - -### Style - -Using Style you can customize the look and feel of the widget in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the widget. - -### Thread Header +## Actions and Events -To modify the styling, you can apply the `ThreadedHeaderStyle` to the `CometChatThreadedHeader` Widget using the `style` property. +### Callback Props - - -```dart - CometChatThreadedHeader( - parentMessage: message, - loggedInUser: CometChatUIKit.loggedInUser!, - style: CometChatThreadedHeaderStyle( - bubbleContainerBackGroundColor: Color(0xFFFEEDE1), - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808), - borderRadius: BorderRadius.circular(12), - ) - ), - messageActionView: (message, context) { - final numberOfReplies = message.replyCount; - String replyText = numberOfReplies == 1 - ? Translations.of(context).reply - : Translations.of(context).replies; - return Container( - width: double.maxFinite, - color: Color(0xFFFEEDE1), - padding: EdgeInsets.symmetric( - vertical: 4, - ), - child: Row( - children: [ - Flexible( - child: Divider( - color: Color(0xFFF76808), - ), - ), - Padding( - padding: EdgeInsets.symmetric(horizontal: 8), - child: Text( - "$numberOfReplies $replyText", - style: TextStyle( - color: Color(0xFFF76808), - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ), - ), - Flexible( - child: Divider( - color: Color(0xFFF76808), - ), - ), - ], - ), - ); - }, - ); -``` - - - - - - - - +The CometChatThreadedHeader component does not have traditional callback props. Instead, it provides a `messageActionView` slot for customizing the action area. -The following properties are exposed by `ThreadedMessagesStyle`: +### Global UI Events -| Property | Data Type | Description | -| -------------------------------- | -------------------------------------- | ----------------------------------------------- | -| `bubbleContainerBackGroundColor` | `Color?` | Sets background color for the bubble container. | -| `bubbleContainerBorder` | `BoxBorder?` | Sets border for the bubble container. | -| `bubbleContainerBorderRadius` | `BorderRadiusGeometry?` | Sets border radius for the bubble container. | -| `countTextStyle` | `TextStyle?` | Sets text style for the reply count. | -| `countTextColor` | `Color?` | Sets color for the reply count text. | -| `countContainerBackGroundColor` | `Color?` | Sets background color for the count container. | -| `countContainerBorder` | `BoxBorder?` | Sets border for the count container. | -| `constraints` | `BoxConstraints?` | Sets constraints for the message container. | -| `incomingMessageBubbleStyle` | `CometChatIncomingMessageBubbleStyle?` | Sets style for the incoming message bubble. | -| `outgoingMessageBubbleStyle` | `CometChatOutgoingMessageBubbleStyle?` | Sets style for the outgoing message bubble. | +The CometChatThreadedHeader component does not produce any global UI events. -*** +## Custom View Slots -### Functionality +Customize the appearance of CometChatThreadedHeader by replacing default views with your own widgets. -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +| Slot | Signature | Replaces | +|------|-----------|----------| +| `messageActionView` | `Widget Function(BaseMessage message, BuildContext context)?` | Reply count section below the message bubble | -Below is a list of customizations along with corresponding code snippets - -| Property | Data Type | Description | -| ------------------- | ------------------------------------------------------ | ---------------------------------------- | -| `parentMessage` | `BaseMessage` | Parent message for the thread. | -| `messageActionView` | `Function(BaseMessage message, BuildContext context)?` | Custom action view for the message. | -| `style` | `CometChatThreadedHeaderStyle?` | Style parameter for the threaded header. | -| `loggedInUser` | `User` | Represents the logged-in user. | -| `template` | `CometChatMessageTemplate?` | Message template used in the thread. | -| `height` | `double?` | Height of the widget. | -| `width` | `double?` | Width of the widget. | - -*** - -### Advanced - -For advanced-level customization, you can set custom widgets to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your widgets, layouts, and UI elements and then incorporate those into the widget. - -#### MessageActionView - -By utilizing the `messageActionView` method, you can assign custom actions to the parent message bubble widget inside the `CometChatThreadedHeader` Widget. - -**Example** - -Here is the complete example for reference: +### Example: Custom Message Action View @@ -208,33 +182,165 @@ CometChatThreadedHeader( border: Border.all(width: 5, color: Color(0xFF6851D6)), ), child: const Center( - child: Text("Your Custom Action View", - style: TextStyle(color: Colors.white),), + child: Text( + "Your Custom Action View", + style: TextStyle(color: Colors.white), + ), ), ); }, ) ``` - - ![Image](/images/854e21f6-threaded_messages_action_view_cometchat_screens-7f88ee62a1538cddfa6da45c8eb28982.png) - - ![Image](/images/07942114-threaded_messages_action_view_cometchat_screens-0d30d7d0d3394b0a40ee33ea511157b3.png) + + +### Example: Custom Reply Count with Dividers + + + +```dart +CometChatThreadedHeader( + parentMessage: message, + loggedInUser: CometChatUIKit.loggedInUser!, + style: CometChatThreadedHeaderStyle( + bubbleContainerBackGroundColor: Color(0xFFFEEDE1), + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + borderRadius: BorderRadius.circular(12), + ), + ), + messageActionView: (message, context) { + final numberOfReplies = message.replyCount; + String replyText = numberOfReplies == 1 + ? Translations.of(context).reply + : Translations.of(context).replies; + return Container( + width: double.maxFinite, + color: Color(0xFFFEEDE1), + padding: EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Flexible(child: Divider(color: Color(0xFFF76808))), + Padding( + padding: EdgeInsets.symmetric(horizontal: 8), + child: Text( + "$numberOfReplies $replyText", + style: TextStyle( + color: Color(0xFFF76808), + fontSize: 14, + fontWeight: FontWeight.w400, + ), + ), + ), + Flexible(child: Divider(color: Color(0xFFF76808))), + ], + ), + ); + }, +) +``` + + + + + + +### Templates + +The `template` prop is used to configure and set a message template for the parent message bubble. It allows for dynamic customization of message appearance, content, or other predefined settings based on the template provided. + + +```dart +CometChatThreadedHeader( + parentMessage: parentMessage, + loggedInUser: loggedInUser, + template: CometChatMessageTemplate( + type: MessageTypeConstants.text, + category: MessageCategoryConstants.message, + // Custom template configuration + ), +) +``` + -*** +## Styling -#### Templates +Customize the appearance of CometChatThreadedHeader using `CometChatThreadedHeaderStyle`. + + + +```dart +CometChatThreadedHeader( + parentMessage: parentMessage, + loggedInUser: loggedInUser, + style: CometChatThreadedHeaderStyle( + bubbleContainerBackGroundColor: Color(0xFFFEEDE1), + countTextColor: Colors.purple, + countContainerBackGroundColor: Colors.grey[100], + incomingMessageBubbleStyle: CometChatIncomingMessageBubbleStyle( + backgroundColor: Colors.grey[200], + ), + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + borderRadius: BorderRadius.circular(12), + ), + ), +) +``` + + -The template method is used to configure and set a list of templates for message bubbles. It allows for dynamic customization of message appearance, content, or other predefined settings based on the templates provided. This method can be called to update or apply a new set of templates to the message handling system. +### Style Properties + +| Property | Type | Description | +|----------|------|-------------| +| `bubbleContainerBackGroundColor` | `Color?` | Background color for the bubble container | +| `bubbleContainerBorder` | `BoxBorder?` | Border for the bubble container | +| `bubbleContainerBorderRadius` | `BorderRadiusGeometry?` | Border radius for the bubble container | +| `countTextStyle` | `TextStyle?` | Text style for the reply count | +| `countTextColor` | `Color?` | Color for the reply count text | +| `countContainerBackGroundColor` | `Color?` | Background color for the count container | +| `countContainerBorder` | `BoxBorder?` | Border for the count container | +| `constraints` | `BoxConstraints?` | Constraints for the message container | +| `incomingMessageBubbleStyle` | `CometChatIncomingMessageBubbleStyle?` | Style for incoming message bubble | +| `outgoingMessageBubbleStyle` | `CometChatOutgoingMessageBubbleStyle?` | Style for outgoing message bubble | + +## Props Reference + +| Prop | Type | Default | Description | +|------|------|---------|-------------| +| `parentMessage` | `BaseMessage` | Required | Parent message for the thread | +| `loggedInUser` | `User` | Required | Logged in user object | +| `messageActionView` | `Function(BaseMessage, BuildContext)?` | `null` | Custom action view for the message | +| `style` | `CometChatThreadedHeaderStyle?` | `null` | Style parameter for the threaded header | +| `template` | `CometChatMessageTemplate?` | `null` | Message template used in the thread | +| `height` | `double?` | `null` | Height of the widget | +| `width` | `double?` | `null` | Width of the widget | +| `receiptsVisibility` | `bool?` | `true` | Controls visibility of receipts | + + + + Display messages in a conversation + + + Compose and send messages + + + Learn how to customize the look and feel + + + Support multiple languages in your app + + diff --git a/ui-kit/flutter/users.mdx b/ui-kit/flutter/users.mdx index c8324ee63..85c83a5f0 100644 --- a/ui-kit/flutter/users.mdx +++ b/ui-kit/flutter/users.mdx @@ -1,272 +1,446 @@ --- title: "Users" +description: "Searchable, scrollable list of all available users with avatar, name, and online/offline status." --- -## Overview - -The `CometChatUsers` is a [Widget](/ui-kit/flutter/components-overview#components), showcasing an accessible list of all available users. It provides an integral search functionality, allowing you to locate any specific user swiftly and easily. For each user listed, the widget displays the user's name by default, in conjunction with their avatar when available. Furthermore, it includes a status indicator, visually informing you whether a user is currently online or offline. - - - - + +```json +{ + "component": "CometChatUsers", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Searchable, scrollable list of all available users with avatar, name, and online/offline status.", + "primaryOutput": { + "prop": "onItemTap", + "type": "Function(BuildContext context, User user)" + }, + "props": { + "data": { + "usersRequestBuilder": { + "type": "UsersRequestBuilder?", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "usersProtocol": { + "type": "UsersBuilderProtocol?", + "default": "null", + "note": "Custom protocol for fetching users" + }, + "scrollController": { + "type": "ScrollController?", + "default": "null", + "note": "Custom scroll controller for the list" + }, + "title": { + "type": "String?", + "default": "Users", + "note": "Title text for the app bar" + }, + "controllerTag": { + "type": "String?", + "default": "null", + "note": "Tag for controller management" + }, + "searchPlaceholder": { + "type": "String?", + "default": "null", + "note": "Placeholder text for search input" + }, + "searchKeyword": { + "type": "String?", + "default": "null", + "note": "Pre-fills search and filters list" + }, + "height": { + "type": "double?", + "default": "null" + }, + "width": { + "type": "double?", + "default": "null" + } + }, + "callbacks": { + "onItemTap": "Function(BuildContext context, User user)?", + "onItemLongPress": "Function(BuildContext context, User user)?", + "onSelection": "Function(List? list, BuildContext context)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?" + }, + "visibility": { + "usersStatusVisibility": { "type": "bool?", "default": true }, + "hideAppbar": { "type": "bool?", "default": false }, + "hideSearch": { "type": "bool", "default": false }, + "showBackButton": { "type": "bool", "default": true }, + "stickyHeaderVisibility": { "type": "bool?", "default": false } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode?", + "values": ["SelectionMode.single", "SelectionMode.multiple", "SelectionMode.none"], + "default": "null" + }, + "activateSelection": { + "type": "ActivateSelection?", + "values": ["ActivateSelection.onClick", "ActivateSelection.onLongClick"], + "default": "null" + } + }, + "viewSlots": { + "listItemView": "Widget Function(User user)?", + "leadingView": "Widget? Function(BuildContext context, User user)?", + "titleView": "Widget? Function(BuildContext context, User user)?", + "subtitleView": "Widget? Function(BuildContext context, User user)?", + "trailingView": "Widget? Function(BuildContext context, User user)?", + "loadingStateView": "WidgetBuilder?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "setOptions": "List? Function(User, CometChatUsersController, BuildContext)?", + "addOptions": "List? Function(User, CometChatUsersController, BuildContext)?", + "appBarOptions": "List Function(BuildContext context)?" + }, + "icons": { + "backButton": { "type": "Widget?", "default": "built-in back arrow" }, + "searchBoxIcon": { "type": "Widget?", "default": "built-in search icon" }, + "submitIcon": { "type": "Widget?", "default": "built-in check icon" } + }, + "style": { + "usersStyle": { "type": "CometChatUsersStyle", "default": "CometChatUsersStyle()" } + } + }, + "events": [ + { + "name": "CometChatUserEvents.ccUserBlocked", + "payload": "User", + "description": "User blocked" + }, + { + "name": "CometChatUserEvents.ccUserUnblocked", + "payload": "User", + "description": "User unblocked" + } + ], + "sdkListeners": [ + "onUserOnline", + "onUserOffline", + "ccUserBlocked", + "ccUserUnblocked", + "onConnected" + ], + "compositionExample": { + "description": "User list wired to message view", + "components": [ + "CometChatUsers", + "CometChatMessages", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemTap emits User -> pass to CometChatMessages or individual message components" + }, + "types": { + "CometChatOption": { + "id": "String?", + "title": "String?", + "icon": "String?", + "iconWidget": "Widget?", + "onClick": "VoidCallback?" + }, + "SelectionMode": { + "single": "SelectionMode.single", + "multiple": "SelectionMode.multiple", + "none": "SelectionMode.none" + }, + "ActivateSelection": { + "onClick": "ActivateSelection.onClick", + "onLongClick": "ActivateSelection.onLongClick" + } + } +} +``` + -The `CometChatUsers` widget is composed of the following Base Widgets: -| Widgets | Description | -| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | -| [ListBase](/ui-kit/flutter/list-base) | a reusable container widget having title, search box, customisable background and a List View | -| [ListItem](/ui-kit/flutter/list-item) | a widget that renders data obtained from a User object on a Tile having a title, subtitle, leading and trailing view | +## Where It Fits -## Usage +`CometChatUsers` is a contact list widget. It renders all available users and emits the selected `User` via `onItemTap`. Wire it to `CometChatMessages` or individual message components (`CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer`) to build a standard two-panel chat layout. -### Integration + + +```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -As `CometChatUsers` is a custom **widget**, it can be launched directly by user actions such as button clicks or other interactions. It's also possible to integrate it into a **tab widget**. `CometChatUsers` offers several parameters and methods for UI customization. +class ChatApp extends StatefulWidget { + const ChatApp({super.key}); -You can launch `CometChatUsers` directly using `Navigator.push`, or you can define it as a widget within the `build` method of your `State` class. + @override + State createState() => _ChatAppState(); +} -##### 1. Using Navigator to Launch `CometChatUsers` +class _ChatAppState extends State { + User? selectedUser; - - -```dart -Navigator.push(context, MaterialPageRoute(builder: (context) => const CometChatUsers())); + @override + Widget build(BuildContext context) { + return Scaffold( + body: Row( + children: [ + SizedBox( + width: 400, + child: CometChatUsers( + onItemTap: (context, user) { + setState(() { + selectedUser = user; + }); + }, + ), + ), + Expanded( + child: selectedUser != null + ? CometChatMessages(user: selectedUser) + : const Center(child: Text('Select a user')), + ), + ], + ), + ); + } +} ``` - - -##### 2. Embedding `CometChatUsers` as a Widget in the build Method + + + + +--- + + +## Minimal Render ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class Users extends StatefulWidget { - const Users({super.key}); - - @override - State createState() => _UsersState(); -} - -class _UsersState extends State { +class UsersDemo extends StatelessWidget { + const UsersDemo({super.key}); @override Widget build(BuildContext context) { return const Scaffold( - body: SafeArea( - child: CometChatUsers() - ) + body: SafeArea( + child: CometChatUsers(), + ), ); } } ``` - - -*** +You can also launch it using `Navigator.push`: -### Actions - -[Actions](/ui-kit/flutter/components-overview#actions) dictate how a widget functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the widget to fit your specific needs. +```dart +Navigator.push( + context, + MaterialPageRoute(builder: (context) => const CometChatUsers()) +); +``` -##### onSelection +--- -When the `onSelection` event is triggered, it furnishes the list of selected users. This event can be invoked by any button or action within the interface. You have the flexibility to implement custom actions or behaviors based on the selected users. +## Filtering Users -This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Pass a `UsersRequestBuilder` to `usersRequestBuilder`. Pass the builder instance — not the result of `.build()`. ```dart CometChatUsers( - selectionMode: SelectionMode.multiple, - activateSelection: ActivateSelection.onClick, - onSelection: (list, context) { - //TODO: This action will trigger the end of selection. - }, + usersRequestBuilder: UsersRequestBuilder() + ..friendsOnly = true + ..limit = 15, ) ``` - - -*** +### Filter Recipes -##### onItemTap +| Recipe | Code | +| --- | --- | +| Friends only | `UsersRequestBuilder()..friendsOnly = true` | +| Online users only | `UsersRequestBuilder()..userStatus = CometChatUserStatus.online` | +| Limit to 15 per page | `UsersRequestBuilder()..limit = 15` | +| Search by keyword | `UsersRequestBuilder()..searchKeyword = "alice"` | +| Hide blocked users | `UsersRequestBuilder()..hideBlockedUsers = true` | +| Filter by roles | `UsersRequestBuilder()..roles = ["admin", "moderator"]` | +| Filter by tags | `UsersRequestBuilder()..tags = ["vip"]` | +| Specific UIDs | `UsersRequestBuilder()..uids = ["uid1", "uid2"]` | -The `onItemTap` method is used to override the onClick behavior in `CometChatUsers`. This action does not come with any predefined behavior. However, you have the flexibility to override this event and tailor it to suit your needs using the following code snippet. +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. + + +### UsersRequestBuilder Properties + +| Property | Description | Code | +| --- | --- | --- | +| `limit` | Number of users to fetch per request. Maximum 100. | `..limit = 30` | +| `searchKeyword` | Search users by name. | `..searchKeyword = "John"` | +| `friendsOnly` | Fetch only friends. Default `false`. | `..friendsOnly = true` | +| `userStatus` | Filter by status: `CometChatUserStatus.online` or `CometChatUserStatus.offline`. | `..userStatus = CometChatUserStatus.online` | +| `hideBlockedUsers` | Hide blocked users from the list. Default `false`. | `..hideBlockedUsers = true` | +| `roles` | Filter users by specific roles. | `..roles = ["admin"]` | +| `tags` | Filter users by specific tags. | `..tags = ["vip"]` | +| `withTags` | Include tags in the User object. Default `false`. | `..withTags = true` | +| `uids` | Fetch specific users by UIDs. | `..uids = ["uid1", "uid2"]` | +| `build()` | Builds and returns a `UsersRequest` object. | `.build()` | + +Refer to [UsersRequestBuilder](/sdk/flutter/retrieve-users) for the full builder API. + +--- + +## Actions and Events + +### Callback Props + +#### onItemTap + +Fires when a user row is tapped. Primary navigation hook — set the active user and render the message view. ```dart CometChatUsers( onItemTap: (context, user) { - // TODO("Not yet implemented") + print("Selected: ${user.name}"); }, ) ``` - - -*** +#### onItemLongPress -##### onBack - -This method allows users to override the onBack Pressed behavior in `CometChatUsers` by utilizing the `onBack` , providing customization options for handling the back action. - -By default, this action has a predefined behavior: it simply dismisses the current widget. However, the flexibility of CometChat UI Kit allows you to override this standard behavior according to your application's specific requirements. You can define a custom action that will be performed instead when the back button is pressed. +Fires when a user row is long-pressed. Useful for showing context menus or custom actions. ```dart CometChatUsers( - onBack: () { - // TODO("Not yet implemented") + onItemLongPress: (context, user) { + // Show custom context menu }, ) ``` - - -*** -##### onError +#### onSelection -This method `onError`, allows users to override error handling within `CometChatUsers`, providing greater control over error responses and actions. +Fires when users are selected in multi-select mode. Requires `selectionMode` to be set. ```dart CometChatUsers( - onError: (e) { - // TODO("Not yet implemented") + selectionMode: SelectionMode.multiple, + activateSelection: ActivateSelection.onClick, + onSelection: (selectedList, context) { + print("Selected ${selectedList?.length ?? 0} users"); }, ) ``` - - -*** +#### onError -##### onItemLongPress - -This method `onItemLongPress`, empowers users to customize long-click actions within `CometChatUsers`, offering enhanced functionality and interaction possibilities. +Fires on internal errors (network failure, auth issue, SDK exception). ```dart CometChatUsers( - onItemLongPress: (context, user) { - // TODO("Not yet implemented") + onError: (error) { + print("CometChatUsers error: $error"); }, ) ``` - - -*** +#### onBack -##### onLoad - -Invoked when the list is successfully fetched and loaded, helping track component readiness. +Fires when the back button is pressed. ```dart CometChatUsers( - onLoad: (list) { - // print("User List: $list"); - }, + showBackButton: true, + onBack: () { + Navigator.pop(context); + }, ) ``` - - -*** +#### onLoad -##### onEmpty - -Called when the list is empty, enabling custom handling such as showing a placeholder message. +Fires when the user list is successfully loaded. ```dart CometChatUsers( - onEmpty: () { - // print("User List is empty"); - }, + onLoad: (list) { + print("Loaded ${list.length} users"); + }, ) ``` - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a Widget. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. - -##### 1. UsersRequestBuilder +#### onEmpty -The [UsersRequestBuilder](/sdk/flutter/retrieve-users) enables you to filter and customize the user list based on available parameters in UsersRequestBuilder. This feature allows you to create more specific and targeted queries when fetching users. The following are the parameters available in [UsersRequestBuilder](/sdk/flutter/retrieve-users) +Fires when the user list is empty. ```dart CometChatUsers( - usersRequestBuilder: UsersRequestBuilder() - ..limit = 10 + onEmpty: () { + print("No users found"); + }, ) ``` - - -*** -### Events +### Global UI Events -[Events](/ui-kit/flutter/components-overview#events) are emitted by a `CometChatUsers` Widget. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +`CometChatUserEvents` emits events subscribable from anywhere in the application. Add a listener in `initState` and remove it in `dispose`. -To handle events supported by Users you have to add corresponding listeners by using `CometChatUserEvents` +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccUserBlocked` | A user is blocked | `User` | +| `ccUserUnblocked` | A user is unblocked | `User` | -| Events | Description | -| --------------- | --------------------------------------------------------------------- | -| ccUserBlocked | This will get triggered when the logged in user blocks another user | -| ccUserUnblocked | This will get triggered when the logged in user unblocks another user | +When to use: sync external UI with user state changes. For example, update a blocked users count badge when a user is blocked. ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class YourScreen extends StatefulWidget { - const YourScreen({super.key}); - - @override - State createState() => _YourScreenState(); -} class _YourScreenState extends State with CometChatUserEventListener { @@ -277,482 +451,1065 @@ class _YourScreenState extends State with CometChatUserEventListener } @override - void dispose(){ - super.dispose(); + void dispose() { CometChatUserEvents.removeUsersListener("listenerId"); + super.dispose(); } @override void ccUserBlocked(User user) { - // TODO + print("Blocked: ${user.name}"); } @override void ccUserUnblocked(User user) { - // TODO + print("Unblocked: ${user.name}"); } @override Widget build(BuildContext context) { return const Placeholder(); } - } ``` - - -*** - -## Customization +### SDK Events (Real-Time, Automatic) -To fit your app's design requirements, you can customize the appearance of the `CometChatUsers` widget. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -### Style +| SDK Listener | Internal behavior | +| --- | --- | +| `onUserOnline` | Updates the user's status indicator to online | +| `onUserOffline` | Updates the user's status indicator to offline | +| `ccUserBlocked` | Updates blocked user in list | +| `ccUserUnblocked` | Updates unblocked user in list | +| `onConnected` | Refreshes user list when connection is re-established | -You can set the `CometChatUsersStyle` to the `CometChatUsers` widget to customize the styling. +Automatic: user presence changes (online/offline), blocked/unblocked state, connection recovery. - - -```dart -CometChatUsers( - usersStyle: CometChatUsersStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleTextColor: Color(0xFFF76808), - separatorColor: Color(0xFFF76808), - ), -) -``` +--- - - +## Custom View Slots - - - +Each slot replaces a section of the default UI. Slots that accept a user parameter receive the `User` object for that row. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `listItemView` | `Widget Function(User)` | Entire list item row | +| `leadingView` | `Widget? Function(BuildContext, User)` | Avatar / left section | +| `titleView` | `Widget? Function(BuildContext, User)` | Name / title text | +| `subtitleView` | `Widget? Function(BuildContext, User)` | Subtitle text | +| `trailingView` | `Widget? Function(BuildContext, User)` | Right section | +| `loadingStateView` | `WidgetBuilder` | Loading spinner | +| `emptyStateView` | `WidgetBuilder` | Empty state | +| `errorStateView` | `WidgetBuilder` | Error state | +| `setOptions` | `List? Function(User, CometChatUsersController, BuildContext)` | Context menu actions (replaces default) | +| `addOptions` | `List? Function(User, CometChatUsersController, BuildContext)` | Context menu actions (adds to default) | +| `appBarOptions` | `List Function(BuildContext)` | App bar action widgets | -### Functionality +### listItemView -These are a set of small functional customizations that allow you to fine-tune the overall experience of the widget. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Replace the entire list item row. - + ```dart +Widget getCustomUserListItem(User user, BuildContext context) { + // Get status indicator + StatusIndicatorUtils statusIndicatorUtils = StatusIndicatorUtils.getStatusIndicatorFromParams( + context: context, + user: user, + onlineStatusIndicatorColor: Color(0xFF56E8A7), + ); + + return CometChatListItem( + id: user.uid, + avatarName: user.name, + avatarURL: user.avatar, + avatarHeight: 40, + avatarWidth: 40, + title: user.name, + key: UniqueKey(), + statusIndicatorColor: statusIndicatorUtils.statusIndicatorColor, + statusIndicatorIcon: statusIndicatorUtils.icon, + statusIndicatorStyle: CometChatStatusIndicatorStyle( + border: Border.all(width: 2, color: Color(0xFFFFFFFF)), + backgroundColor: Color(0xFF56E8A7), + ), + hideSeparator: true, + style: ListItemStyle( + background: user.status == CometChatUserStatus.online + ? const Color(0xFFE6F4ED) + : Colors.transparent, + titleStyle: TextStyle( + overflow: TextOverflow.ellipsis, + fontSize: 16, + fontWeight: FontWeight.w500, + color: Color(0xFF141414), + ), + padding: EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 8), + ), + ); +} + +// Usage: CometChatUsers( - title: "Your Title", - backButton: Icon(Icons.add_alert, color: Color(0xFF6851D6)), - searchPlaceholder: "Search Users", + listItemView: (user) => getCustomUserListItem(user, context), ) ``` - - -## List of properties exposed by `CometChatUsers` - -| Property | Data Type | Description | -| ------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------- | -| `usersProtocol` | `UsersBuilderProtocol?` | Custom users request builder protocol. | -| `usersRequestBuilder` | `UsersRequestBuilder?` | Custom request builder for fetching users. | -| `subtitleView` | `Widget? Function(BuildContext, User)` | Widget to set subtitle for each user item. | -| `listItemView` | `Widget Function(User)` | Custom view for each user item. | -| `usersStyle` | `CometChatUsersStyle` | Styling options for the users list. | -| `scrollController` | `ScrollController?` | Controller for scrolling the list. | -| `searchPlaceholder` | `String?` | Placeholder text for the search input box. | -| `backButton` | `Widget?` | Widget for the back button in the app bar. | -| `showBackButton` | `bool` | Flag to show/hide the back button. | -| `searchBoxIcon` | `Widget?` | Widget for the search box icon. | -| `hideSearch` | `bool` | Flag to show/hide the search input box. | -| `selectionMode` | `SelectionMode?` | Mode defining how users can be selected. | -| `onSelection` | `Function(List?, BuildContext)?` | Callback for handling user selection. | -| `loadingStateView` | `WidgetBuilder?` | View displayed during loading state. | -| `emptyStateView` | `WidgetBuilder?` | View displayed when the list is empty. | -| `errorStateView` | `WidgetBuilder?` | View displayed when an error occurs. | -| `appBarOptions` | `List Function(BuildContext context)?` | Options available in the app bar. | -| `usersStatusVisibility` | `bool?` | Hide status indicator on user avatars. | -| `activateSelection` | `ActivateSelection?` | Controls whether selection is allowed. | -| `onError` | `OnError?` | Callback for handling errors. | -| `onBack` | `VoidCallback?` | Callback triggered when going back. | -| `onItemTap` | `Function(BuildContext context, User)?` | Callback triggered when tapping a user. | -| `onItemLongPress` | `Function(BuildContext context, User)?` | Callback triggered on long press of a user. | -| `submitIcon` | `Widget?` | Widget for displaying the submit icon. | -| `hideAppbar` | `bool?` | Flag to show/hide the app bar. | -| `controllerTag` | `String?` | Identifier tag for controller management. | -| `height` | `double?` | Height of the widget. | -| `width` | `double?` | Width of the widget. | -| `stickyHeaderVisibility` | `bool?` | Hide alphabets used to separate users. | -| `searchKeyword` | `String?` | Keyword used to fetch initial user list. | -| `onLoad` | `OnLoad?` | Callback triggered when the list loads. | -| `onEmpty` | `OnEmpty?` | Callback triggered when the list is empty. | -| `addOptions` | `List? Function(User, CometChatUsersController, BuildContext)?` | Additional long-press actions for users. | -| `setOptions` | `List? Function(User, CometChatUsersController, BuildContext)?` | Actions available on long-press of a user. | -| `titleView` | `Widget? Function(BuildContext, User)?` | Custom title view for each user. | -| `leadingView` | `Widget? Function(User)?` | Widget for leading section of each user. | -| `trailingView` | `Widget? Function(User)?` | Widget for trailing section of each user. | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the widget. This lets you tailor each aspect of the widget to fit your exact needs and application aesthetics. You can create and define your own widget and then incorporate those into the widget. - -*** - -#### setOptions - -This method sets a predefined list of actions that users can perform when they long press a user in the list. These options typically include: - -* Muting notifications for a specific user. - -By customizing these options, developers can provide a streamlined and contextually relevant user experience + +### leadingView + +Replace the avatar / left section. ```dart CometChatUsers( - setOptions: (user, controller, context) { - // return options + leadingView: (context, user) { + return Container( + decoration: BoxDecoration( + border: Border.all( + color: user.status == CometChatUserStatus.online + ? Color(0xFF09C26F) + : Colors.transparent, + width: 2, + ), + borderRadius: BorderRadius.circular(8), + ), + child: CometChatAvatar( + image: user.avatar, + name: user.name, + style: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(6), + ), + ), + ); }, ) ``` - - -*** - -#### addOptions - -This method extends the existing set of actions available when users long press a user item. Unlike setOptionsDefines, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: +### titleView -* Adding a "Report Spam" action. -* Introducing a "Save to Notes" option. -* Integrating third-party actions such as "Share to Cloud Storage". - -This method provides flexibility in modifying user interaction capabilities. +Replace the name / title text. Role badge inline example. ```dart CometChatUsers( - addOptions: (user, controller, context) { - // return options + titleView: (context, user) { + return Row( + children: [ + Text( + user.name ?? "", + style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16), + ), + if (user.role != null) + Container( + margin: EdgeInsets.only(left: 4), + padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Color(0xFF09C26F), + borderRadius: BorderRadius.circular(7), + ), + child: Text( + user.role!, + style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600), + ), + ), + ], + ); }, ) ``` - - -*** +### subtitleView -#### loadingStateView +Replace the subtitle text for each user. -This method allows developers to set a custom loading view that is displayed when data is being fetched or loaded within the component. Instead of using a default loading spinner, a custom animation, progress bar, or branded loading screen can be displayed. - -* Showing a skeleton loader for users while data loads. -* Displaying a custom progress indicator with branding. -* Providing an animated loading experience for a more engaging UI. + + + ```dart CometChatUsers( - loadingStateView: (context) { - // return loading view + subtitleView: (context, user) { + final dateTime = user.lastActiveAt ?? DateTime.now(); + final subtitle = "Last Active at ${DateFormat('dd/MM/yyyy, HH:mm:ss').format(dateTime)}"; + + return Text( + subtitle, + style: TextStyle( + color: Color(0xFF727272), + fontSize: 14, + fontWeight: FontWeight.w400, + ), + ); }, ) ``` - - -*** - -#### emptyStateView -Configures a custom view to be displayed when there are no users. This improves the user experience by providing meaningful content instead of an empty screen. +### trailingView -* Displaying a message like "No users yet. Start a new chat!". -* Showing an illustration or animation to make the UI visually appealing. -* Providing a button to start a new user. +Replace the right section. Custom tag badge example. ```dart CometChatUsers( - emptyStateView: (context) { - // return empty view + trailingView: (context, user) { + final tag = user.tags?.isNotEmpty == true ? user.tags!.first : null; + if (tag == null) return null; + + return Container( + padding: EdgeInsets.symmetric(horizontal: 6, vertical: 4), + decoration: BoxDecoration( + color: Color(0xFF6852D6), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + tag, + style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w600), + ), + ); }, ) ``` - - -*** - -#### errorStateView +### setOptions -Defines a custom error state view that appears when an issue occurs while loading users or messages. This enhances the user experience by displaying friendly error messages instead of generic system errors. - -* Showing "Something went wrong. Please try again." with a retry button. -* Displaying a connection issue message if the user is offline. -* Providing troubleshooting steps for the error. +Replace the context menu / long-press actions on each user item. ```dart CometChatUsers( - errorStateView: (context) { - // return error view + setOptions: (user, controller, context) { + return [ + CometChatOption( + id: "block", + title: "Block User", + icon: AssetConstants.close, + onClick: () { + CometChat.blockUsers([user.uid], onSuccess: (users) { + print("User blocked"); + }, onError: (error) { + print("Error: $error"); + }); + }, + ), + CometChatOption( + id: "view_profile", + title: "View Profile", + iconWidget: Icon(Icons.person_outline), + onClick: () { + // Navigate to user profile + }, + ), + ]; }, ) ``` - - -*** - -#### leadingView +### addOptions -This method allows developers to set a custom leading view element that appears at the beginning of each user item. Typically, this space is used for profile pictures, avatars, or user badges. - -* Profile Pictures & Avatars – Display user profile images with online/offline indicators. -* Custom Icons or Badges – Show role-based badges (Admin, VIP, Verified) before the user name. -* Status Indicators – Add an active status ring or colored border based on availability. +Add to the existing context menu actions without removing defaults. ```dart CometChatUsers( - leadingView: (context, user) { - // return leading view - }, + addOptions: (user, controller, context) { + return [ + CometChatOption( + id: "add_friend", + title: "Add Friend", + iconWidget: Icon(Icons.person_add_outlined), + onClick: () { + // Add friend logic + }, + ), + CometChatOption( + id: "send_message", + title: "Send Message", + iconWidget: Icon(Icons.message_outlined), + onClick: () { + // Navigate to messages + }, + ), + ]; + }, ) ``` - - -*** -#### titleView +### appBarOptions -This method customizes the title view of each user item, which typically displays the user’s name. It allows for styling modifications, additional metadata, or inline action buttons. +Add custom widgets to the app bar. -* Styled Usernames – Customize fonts, colors, or text sizes for the name display. -* Additional Metadata – Show extra details like username handles or job roles. -* Inline Actions – Add a follow button or verification checkmark next to the name. + + + ```dart CometChatUsers( - titleView: (context, user) { - // return title view - }, + appBarOptions: (context) => [ + IconButton( + onPressed: () { + // Handle action + }, + icon: Icon(Icons.add_comment_outlined, color: Color(0xFF141414)), + ), + ], ) ``` - - -*** - -#### trailingView - -This method allows developers to customize the trailing (right-end) section of each user item, typically used for actions like buttons, icons, or extra information. - -* Quick Actions – Add a follow/unfollow button. -* Notification Indicators – Show unread message counts or alert icons. -* Custom Info Display – Display last active time or mutual connections. +For a more complete popup menu with styling: ```dart CometChatUsers( - trailingView: (context, user) { - // return trailing view - }, + appBarOptions: (context) => [ + PopupMenuButton( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + side: BorderSide(color: Color(0xFFF5F5F5), width: 1), + ), + color: Colors.white, + elevation: 4, + icon: Icon(Icons.more_vert, color: Color(0xFF141414)), + onSelected: (value) { + switch (value) { + case 'refresh': + // Refresh users list + break; + case 'settings': + // Navigate to settings + break; + } + }, + itemBuilder: (BuildContext context) => [ + PopupMenuItem( + value: 'refresh', + child: Row( + children: [ + Icon(Icons.refresh, color: Color(0xFFA1A1A1)), + SizedBox(width: 8), + Text("Refresh"), + ], + ), + ), + PopupMenuItem( + value: 'settings', + child: Row( + children: [ + Icon(Icons.settings, color: Color(0xFFA1A1A1)), + SizedBox(width: 8), + Text("Settings"), + ], + ), + ), + ], + ), + ], ) ``` - - -*** +--- + -#### ListItemView +## Styling -With this function, you can assign a custom ListItem to the `CometChatUsers` Widget. +Set `CometChatUsersStyle` to customize the appearance. ```dart CometChatUsers( - listItemView: (user) { - return Placeholder(); - }, + usersStyle: CometChatUsersStyle( + backgroundColor: Colors.white, + titleTextColor: Color(0xFFF76808), + separatorColor: Color(0xFFF76808), + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + ), ) ``` - - - + -**Example** +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of the component | +| `border` | `Border?` | Border for the widget | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius for the widget | +| `titleTextColor` | `Color?` | Color of the header title | +| `titleTextStyle` | `TextStyle?` | Style for the header title | +| `backIconColor` | `Color?` | Back button icon color | +| `searchBackgroundColor` | `Color?` | Background color of search box | +| `searchBorder` | `BorderSide?` | Border for search box | +| `searchBorderRadius` | `BorderRadius?` | Border radius for search box | +| `searchPlaceHolderTextColor` | `Color?` | Placeholder text color in search | +| `searchPlaceHolderTextStyle` | `TextStyle?` | Placeholder text style in search | +| `searchIconColor` | `Color?` | Search icon color | +| `searchInputTextColor` | `Color?` | Search input text color | +| `searchInputTextStyle` | `TextStyle?` | Search input text style | +| `separatorColor` | `Color?` | Color of list item separators | +| `separatorHeight` | `double?` | Height of list item separators | +| `stickyTitleColor` | `Color?` | Color of sticky alphabetical headers | +| `stickyTitleTextStyle` | `TextStyle?` | Style for sticky alphabetical headers | +| `itemTitleTextColor` | `Color?` | Color of user name in list items | +| `itemTitleTextStyle` | `TextStyle?` | Style for user name in list items | +| `itemBorder` | `BoxBorder?` | Border for list items | +| `listItemSelectedBackgroundColor` | `Color?` | Background color for selected items | +| `emptyStateTextColor` | `Color?` | Text color for empty state title | +| `emptyStateTextStyle` | `TextStyle?` | Text style for empty state title | +| `emptyStateSubTitleTextColor` | `Color?` | Text color for empty state subtitle | +| `emptyStateSubTitleTextStyle` | `TextStyle?` | Text style for empty state subtitle | +| `errorStateTextColor` | `Color?` | Text color for error state title | +| `errorStateTextStyle` | `TextStyle?` | Text style for error state title | +| `errorStateSubTitleTextColor` | `Color?` | Text color for error state subtitle | +| `errorStateSubTitleTextStyle` | `TextStyle?` | Text style for error state subtitle | +| `retryButtonBackgroundColor` | `Color?` | Background color for retry button | +| `retryButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius for retry button | +| `retryButtonBorder` | `BorderSide?` | Border for retry button | +| `retryButtonTextColor` | `Color?` | Text color for retry button | +| `retryButtonTextStyle` | `TextStyle?` | Text style for retry button | +| `submitIconColor` | `Color?` | Color of submit icon in selection mode | +| `checkBoxBackgroundColor` | `Color?` | Background color of unchecked checkbox | +| `checkBoxCheckedBackgroundColor` | `Color?` | Background color of checked checkbox | +| `checkboxSelectedIconColor` | `Color?` | Color of checkmark icon | +| `checkBoxBorderRadius` | `BorderRadiusGeometry?` | Border radius for checkbox | +| `checkBoxBorder` | `BorderSide?` | Border for checkbox | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for user avatars | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle?` | Style for status indicators | + +--- + -Here is the complete example for reference: +## Common Patterns + +### Custom empty state with CTA -```dart custom_list_item.dart - Widget getCustomUserListItem(User user) { - return CometChatListItem( - id: user.uid, - avatarName: user.name, - avatarURL: user.avatar, - avatarHeight: 40, - avatarWidth: 40, - title: user.name, - key: UniqueKey(), - statusIndicatorStyle: CometChatStatusIndicatorStyle( - border: Border.all( - width: 2, - color: Color(0xFFFFFFFF), - ), - backgroundColor: Color(0xFF56E8A7), - ), - hideSeparator: true, - style: ListItemStyle( - background: user.status == CometChatUserStatus.online - ? const Color(0xFFE6F4ED) - : Colors.transparent, - titleStyle: TextStyle( - overflow: TextOverflow.ellipsis, - fontSize: 16, - fontWeight: FontWeight.w500, - color: Color(0xFF141414), - ), - padding: EdgeInsets.only( - left: 16, - right: 16, - top: 8, - bottom: 8, - ), +```dart +CometChatUsers( + emptyStateView: (context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.people_outline, size: 64, color: Color(0xFF727272)), + SizedBox(height: 16), + Text("No users found", style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500)), + SizedBox(height: 8), + ElevatedButton( + onPressed: () { + // Invite users + }, + child: Text("Invite Users"), + ), + ], ), ); - } + }, +) ``` - - +### Friends-only list + -```dart main.dart +```dart CometChatUsers( - listItemView: (user) { - return getCustomUserListItem(user); - }, + usersRequestBuilder: UsersRequestBuilder() + ..friendsOnly = true + ..limit = 15, ) ``` - - -*** - -#### SubtitleView - -You can customize the subtitle view for each item to meet your specific preferences and needs. +### Multi-select with selection callback ```dart CometChatUsers( - subtitleView: (context, user) { - String subtitle = ""; - - final dateTime = user.lastActiveAt ?? DateTime.now(); - subtitle = "Last Active at ${DateFormat('dd/MM/yyyy, HH:mm:ss').format(dateTime)}"; - - return Text(subtitle, - style: TextStyle( - color: Color(0xFF727272), - fontSize: 14, - fontWeight: FontWeight.w400, - ), - ); - }, + selectionMode: SelectionMode.multiple, + activateSelection: ActivateSelection.onClick, + onSelection: (selectedUsers, context) { + if (selectedUsers != null && selectedUsers.isNotEmpty) { + print("Selected ${selectedUsers.length} users"); + // Create group with selected users, etc. + } + }, ) ``` - - - - - - -*** +### Hide all chrome — minimal list -#### AppBarOptions + + +```dart +CometChatUsers( + hideSearch: true, + hideAppbar: true, + usersStatusVisibility: false, + stickyHeaderVisibility: true, // hides alphabetical headers +) +``` + + -You can set the Custom AppBarOptions to the Conversations widget. +### Online users only ```dart CometChatUsers( - appBarOptions: (context) => [ - IconButton( - onPressed: () {}, - icon: Icon( - Icons.add_comment_outlined, - color: Color(0xFF141414), - ), - ), - ], + usersRequestBuilder: UsersRequestBuilder() + ..userStatus = CometChatUserStatus.online, ) ``` - - - - - +--- + + +## Accessibility + +The component renders a scrollable list of interactive items. Each user row supports: + +- Tap gesture for selection/navigation +- Long-press gesture for context menu actions +- Checkbox selection in multi-select mode with proper touch targets +- Status indicators with visual feedback for online/offline state + +For screen readers: +- User names are readable as list item titles +- Status indicators use color coding — consider adding `Semantics` widgets via `leadingView` if screen reader descriptions are needed for these visual indicators +- Selection state is communicated through checkbox widgets + +The component respects system accessibility settings including text scaling and high contrast modes. + +--- + +## Props + +All props are optional unless noted. + +### activateSelection + +Controls when selection mode activates. + +| | | +| --- | --- | +| Type | `ActivateSelection?` | +| Default | `null` | + +Values: `ActivateSelection.onClick`, `ActivateSelection.onLongClick` + +--- + +### addOptions + +Adds additional context menu actions to the default options. + +| | | +| --- | --- | +| Type | `List? Function(User, CometChatUsersController, BuildContext)?` | +| Default | `null` | + +--- + +### appBarOptions + +Custom widgets to display in the app bar. + +| | | +| --- | --- | +| Type | `List Function(BuildContext context)?` | +| Default | `null` | + +--- + +### backButton + +Custom back button widget. + +| | | +| --- | --- | +| Type | `Widget?` | +| Default | Built-in back arrow | + +--- + +### controllerTag + +Identifier tag for controller management. + +| | | +| --- | --- | +| Type | `String?` | +| Default | `null` | + +--- + + +### emptyStateView + +Custom view displayed when there are no users. + +| | | +| --- | --- | +| Type | `WidgetBuilder?` | +| Default | Built-in empty state | + +--- + +### errorStateView + +Custom view displayed when an error occurs. + +| | | +| --- | --- | +| Type | `WidgetBuilder?` | +| Default | Built-in error state | + +--- + +### height + +Height of the widget. + +| | | +| --- | --- | +| Type | `double?` | +| Default | `null` | + +--- + +### hideAppbar + +Hides the app bar including title and search. + +| | | +| --- | --- | +| Type | `bool?` | +| Default | `false` | + +--- + +### hideSearch + +Hides the search input box. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `false` | + +--- + +### leadingView + +Custom renderer for the avatar / left section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, User user)?` | +| Default | Built-in avatar | + +--- + +### listItemView + +Custom renderer for the entire list item row. + +| | | +| --- | --- | +| Type | `Widget Function(User user)?` | +| Default | Built-in list item | + +--- + +### loadingStateView + +Custom view displayed during loading state. + +| | | +| --- | --- | +| Type | `WidgetBuilder?` | +| Default | Built-in shimmer | + +--- + + +### onBack + +Callback triggered when the back button is pressed. + +| | | +| --- | --- | +| Type | `VoidCallback?` | +| Default | `null` | + +--- + +### onEmpty + +Callback triggered when the user list is empty. + +| | | +| --- | --- | +| Type | `OnEmpty?` | +| Default | `null` | + +--- + +### onError + +Callback triggered when an error occurs. + +| | | +| --- | --- | +| Type | `OnError?` | +| Default | `null` | + +--- + +### onItemLongPress + +Callback triggered on long press of a user item. + +| | | +| --- | --- | +| Type | `Function(BuildContext context, User user)?` | +| Default | `null` | + +--- + +### onItemTap + +Callback triggered when tapping a user item. + +| | | +| --- | --- | +| Type | `Function(BuildContext context, User user)?` | +| Default | `null` | + +--- + +### onLoad + +Callback triggered when the list is successfully loaded. + +| | | +| --- | --- | +| Type | `OnLoad?` | +| Default | `null` | + +--- + +### onSelection + +Callback triggered when users are selected. Requires `selectionMode` to be set. + +| | | +| --- | --- | +| Type | `Function(List? list, BuildContext context)?` | +| Default | `null` | + +--- + +### scrollController + +Controller for scrolling the list. + +| | | +| --- | --- | +| Type | `ScrollController?` | +| Default | `null` | + +--- + + +### searchBoxIcon + +Custom search box icon widget. + +| | | +| --- | --- | +| Type | `Widget?` | +| Default | Built-in search icon | + +--- + +### searchKeyword + +Pre-fills the search and filters the user list. + +| | | +| --- | --- | +| Type | `String?` | +| Default | `null` | + +--- + +### searchPlaceholder + +Placeholder text for the search input box. + +| | | +| --- | --- | +| Type | `String?` | +| Default | `null` | + +--- + +### selectionMode + +Enables single or multi-select mode. + +| | | +| --- | --- | +| Type | `SelectionMode?` | +| Default | `null` | + +Values: `SelectionMode.single`, `SelectionMode.multiple`, `SelectionMode.none` + +--- + +### setOptions + +Replaces the default context menu actions. + +| | | +| --- | --- | +| Type | `List? Function(User, CometChatUsersController, BuildContext)?` | +| Default | `null` | + +--- + +### showBackButton + +Shows or hides the back button. + +| | | +| --- | --- | +| Type | `bool` | +| Default | `true` | + +--- + +### stickyHeaderVisibility + +Hides alphabetical section headers when set to `true`. + +| | | +| --- | --- | +| Type | `bool?` | +| Default | `false` | + +Note: When `false`, alphabetical headers (A, B, C...) are shown to separate users. + +--- + + +### submitIcon + +Custom submit icon widget for selection mode. + +| | | +| --- | --- | +| Type | `Widget?` | +| Default | Built-in check icon | + +--- + +### subtitleView + +Custom renderer for the subtitle text. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, User user)?` | +| Default | `null` | + +--- + +### title + +Title text displayed in the app bar. + +| | | +| --- | --- | +| Type | `String?` | +| Default | `"Users"` | + +--- + +### titleView + +Custom renderer for the name / title text. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, User user)?` | +| Default | Built-in title | + +--- + +### trailingView + +Custom renderer for the right section. + +| | | +| --- | --- | +| Type | `Widget? Function(BuildContext context, User user)?` | +| Default | `null` | + +--- + +### usersProtocol + +Custom protocol for fetching users. + +| | | +| --- | --- | +| Type | `UsersBuilderProtocol?` | +| Default | `null` | + +--- + +### usersRequestBuilder + +Controls which users load and in what order. + +| | | +| --- | --- | +| Type | `UsersRequestBuilder?` | +| Default | SDK default (30 per page) | + +Pass the builder instance, not the result of `.build()`. + +--- + +### usersStatusVisibility + +Shows or hides the online/offline status indicator on user avatars. + +| | | +| --- | --- | +| Type | `bool?` | +| Default | `true` | + +--- + +### usersStyle + +Styling options for the users list. + +| | | +| --- | --- | +| Type | `CometChatUsersStyle` | +| Default | `CometChatUsersStyle()` | + +--- + +### width + +Width of the widget. + +| | | +| --- | --- | +| Type | `double?` | +| Default | `null` | + +--- + + +## Events + +`CometChatUsers` does not emit custom UI events. It subscribes to: + +| Event | Payload | Internal behavior | +| --- | --- | --- | +| `CometChatUserEvents.ccUserBlocked` | `User` | Updates blocked user in list | +| `CometChatUserEvents.ccUserUnblocked` | `User` | Updates unblocked user in list | + +--- + +## Customization Matrix + +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on user interaction | Component props | `on` callbacks | `onItemTap: (ctx, user) => setActive(user)` | +| Filter which users appear | Component props | `usersRequestBuilder` | `usersRequestBuilder: UsersRequestBuilder()..friendsOnly = true` | +| Toggle visibility of UI elements | Component props | `hide` / `show` boolean props | `hideSearch: true` | +| Replace a section of the list item | Component props | `View` render props | `listItemView: (user) => CustomWidget()` | +| Change colors, fonts, spacing | Component props | `usersStyle` | `usersStyle: CometChatUsersStyle(titleTextColor: Colors.red)` | + +--- -*** + + + Display recent one-on-one and group conversations + + + Display and manage group chats + + + Display messages in a conversation + + + Learn how to customize the look and feel + + \ No newline at end of file From b45554b829800f82611de4e04bbf25fcf4b99423 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 12:09:48 +0530 Subject: [PATCH 029/106] fixes flutter docs --- ui-kit/flutter/group-members.mdx | 2 + ui-kit/flutter/message-composer.mdx | 18 ++++++- ui-kit/flutter/message-header.mdx | 73 ++++++++++++++++++++++++++++- ui-kit/flutter/message-list.mdx | 24 ++++++++++ ui-kit/flutter/search.mdx | 8 ++++ 5 files changed, 122 insertions(+), 3 deletions(-) diff --git a/ui-kit/flutter/group-members.mdx b/ui-kit/flutter/group-members.mdx index b5beb1fb3..6e8c4b369 100644 --- a/ui-kit/flutter/group-members.mdx +++ b/ui-kit/flutter/group-members.mdx @@ -922,7 +922,9 @@ CometChatGroupMembers( | `searchIconColor` | `Color?` | Search icon color | | `loadingIconColor` | `Color?` | Loading indicator color | | `emptyStateTextStyle` | `TextStyle?` | Style for empty state title | +| `emptyStateTextColor` | `Color?` | Color for empty state title text | | `emptyStateSubtitleTextStyle` | `TextStyle?` | Style for empty state subtitle | +| `emptyStateSubtitleTextColor` | `Color?` | Color for empty state subtitle text | | `errorStateTextStyle` | `TextStyle?` | Style for error state title | | `errorStateSubtitleStyle` | `TextStyle?` | Style for error state subtitle | | `onlineStatusColor` | `Color?` | Online status indicator color | diff --git a/ui-kit/flutter/message-composer.mdx b/ui-kit/flutter/message-composer.mdx index 206701160..d9b0ff136 100644 --- a/ui-kit/flutter/message-composer.mdx +++ b/ui-kit/flutter/message-composer.mdx @@ -168,7 +168,7 @@ Component-level callbacks that fire on specific user interactions: | `onSendButtonTap` | `Function(BuildContext, BaseMessage, PreviewMessageMode?)?` | User taps the send button | | `onChange` | `Function(String)?` | Text in the input field changes | | `onError` | `OnError?` | An error occurs | -| `stateCallBack` | `Function(CometChatMessageComposerController)?` | Access controller functions | +| `stateCallBack` | `Function(CometChatMessageComposerController)?` | Controller state callback for accessing controller functions | @@ -402,8 +402,10 @@ Customize the appearance of `CometChatMessageComposer` using `CometChatMessageCo | `sendButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius of the send button | | `secondaryButtonIconColor` | `Color?` | Color of the secondary button icon | | `secondaryButtonIconBackgroundColor` | `Color?` | Background color of the secondary button | +| `secondaryButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius of the secondary button | | `auxiliaryButtonIconColor` | `Color?` | Color of the auxiliary button icon | | `auxiliaryButtonIconBackgroundColor` | `Color?` | Background color of the auxiliary button | +| `auxiliaryButtonBorderRadius` | `BorderRadiusGeometry?` | Border radius of the auxiliary button | | `textStyle` | `TextStyle?` | Style of the text | | `textColor` | `Color?` | Color of the text | | `placeHolderTextStyle` | `TextStyle?` | Style of the placeholder text | @@ -412,6 +414,10 @@ Customize the appearance of `CometChatMessageComposer` using `CometChatMessageCo | `mentionsStyle` | `CometChatMentionsStyle?` | Style for mentions | | `mediaRecorderStyle` | `CometChatMediaRecorderStyle?` | Style for media recorder | | `aiOptionStyle` | `AIOptionsStyle?` | Style for AI options | +| `aiOptionSheetStyle` | `CometChatAiOptionSheetStyle?` | Style for AI option sheet | +| `attachmentOptionSheetStyle` | `CometChatAttachmentOptionSheetStyle?` | Style for attachment option sheet | +| `suggestionListStyle` | `CometChatSuggestionListStyle?` | Style for suggestion list | +| `messagePreviewStyle` | `CometChatMessagePreviewStyle?` | Style for message preview | ### Example: Custom Styling @@ -523,13 +529,17 @@ CometChatMessageComposer( | `disableTypingEvents` | `bool` | `false` | Disables typing events | | `disableSoundForMessages` | `bool` | `false` | Disables sound for sent messages | | `customSoundForMessage` | `String?` | - | URL for custom sound | +| `customSoundForMessagePackage` | `String?` | - | Package name for custom sound asset | | `parentMessageId` | `int` | `0` | ID of the parent message | | `padding` | `EdgeInsetsGeometry?` | - | Sets padding for the message composer | | `messageInputPadding` | `EdgeInsetsGeometry?` | - | Sets padding for the message input field | | `sendButtonView` | `Widget?` | - | Custom send button widget | | `attachmentIcon` | `Widget?` | - | Custom attachment icon | +| `attachmentIconURL` | `String?` | - | Path of the icon to show in the attachments button | | `voiceRecordingIcon` | `Widget?` | - | Custom voice recording icon | | `aiIcon` | `Widget?` | - | Custom AI button icon | +| `aiIconURL` | `String?` | - | Path of the icon to show in the AI button | +| `aiIconPackageName` | `String?` | - | Package name for AI icon asset | | `auxiliaryButtonView` | `ComposerWidgetBuilder?` | - | UI component for auxiliary button | | `secondaryButtonView` | `ComposerWidgetBuilder?` | - | UI component for secondary button | | `auxiliaryButtonsAlignment` | `AuxiliaryButtonsAlignment?` | - | Controls position of auxiliary button view | @@ -549,12 +559,18 @@ CometChatMessageComposer( | `hideSendButton` | `bool?` | `null` | Hide/display the send button | | `hideStickersButton` | `bool?` | `null` | Hide/display the sticker button | | `sendButtonIcon` | `Widget?` | - | Custom send button icon | +| `recorderStartButtonIcon` | `Widget?` | - | Custom icon for media recorder start button | +| `recorderPauseButtonIcon` | `Widget?` | - | Custom icon for media recorder pause button | +| `recorderDeleteButtonIcon` | `Widget?` | - | Custom icon for media recorder delete button | +| `recorderStopButtonIcon` | `Widget?` | - | Custom icon for media recorder stop button | +| `recorderSendButtonIcon` | `Widget?` | - | Custom icon for media recorder send button | | `disableMentionAll` | `bool` | `false` | Disables @all mentions in groups | | `mentionAllLabel` | `String?` | - | Custom label for group mentions | | `mentionAllLabelId` | `String?` | - | Custom label ID for group mentions | | `headerView` | `ComposerWidgetBuilder?` | - | Custom header view | | `footerView` | `ComposerWidgetBuilder?` | - | Custom footer view | | `textFormatters` | `List?` | - | List of text formatters | +| `stateCallBack` | `Function(CometChatMessageComposerController)?` | - | Callback to access controller functions | diff --git a/ui-kit/flutter/message-header.mdx b/ui-kit/flutter/message-header.mdx index 6cddfc8ab..ab5ee45dc 100644 --- a/ui-kit/flutter/message-header.mdx +++ b/ui-kit/flutter/message-header.mdx @@ -136,6 +136,33 @@ CometChatMessageHeader( +### CometChatMessageHeaderStyle Properties + +| Property | Data Type | Description | +| ------------------------------------- | -------------------------------- | -------------------------------------------------------- | +| `backgroundColor` | `Color?` | Background color for the message header. | +| `border` | `BoxBorder?` | Border for the message header. | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius for the message header. | +| `titleTextStyle` | `TextStyle?` | Text style for the title. | +| `titleTextColor` | `Color?` | Color for the title text. | +| `subtitleTextStyle` | `TextStyle?` | Text style for the subtitle. | +| `subtitleTextColor` | `Color?` | Color for the subtitle text. | +| `typingIndicatorTextStyle` | `TextStyle?` | Text style for the typing indicator. | +| `onlineStatusColor` | `Color?` | Color for the online status indicator. | +| `backIconColor` | `Color?` | Color for the back icon. | +| `backIcon` | `Widget?` | Custom back icon widget. | +| `privateGroupBadgeIcon` | `Widget?` | Icon for private group badge. | +| `passwordProtectedGroupBadgeIcon` | `Widget?` | Icon for password protected group badge. | +| `privateGroupBadgeIconColor` | `Color?` | Color for private group badge icon. | +| `passwordProtectedGroupBadgeIconColor`| `Color?` | Color for password protected group badge icon. | +| `groupIconBackgroundColor` | `Color?` | Background color for group icon. | +| `avatarStyle` | `CometChatAvatarStyle?` | Style for the avatar. | +| `callButtonsStyle` | `CometChatCallButtonsStyle?` | Style for call buttons. | +| `statusIndicatorStyle` | `CometChatStatusIndicatorStyle?` | Style for status indicator. | +| `newChatIconColor` | `Color?` | Color for the new chat icon. | +| `chatHistoryIconColor` | `Color?` | Color for the chat history icon. | +| `menuIconColor` | `Color?` | Color for the menu icon. | + *** ### Functionality @@ -181,8 +208,12 @@ Following is a list of customizations along with their corresponding code snippe | `avatarWidth` | `double?` | Set width for avatar. | | `height` | `double?` | Set height for message header. | | `padding` | `EdgeInsetsGeometry?` | Set padding for message header. | -| `showVideoCallButton` | `bool?` | Used to hide/display video call button. | -| `showVoiceCallButton` | `bool?` | Used to hide/display voice call button. | +| `hideVideoCallButton` | `bool?` | Used to hide video call button. | +| `hideVoiceCallButton` | `bool?` | Used to hide voice call button. | +| `showBackButton` | `bool?` | Toggle visibility for back button. Defaults to `true`. | +| `usersStatusVisibility` | `bool?` | Controls visibility of status indicator. Defaults to `true`. | +| `options` | `List? Function(User? user, Group? group, BuildContext context)?` | Set menu options for the header. | +| `menuIcon` | `Widget?` | Set custom menu icon widget. | | `leadingStateView` | `Widget? Function(Group? group, User? user, BuildContext context)?` | To set leading view for the message header. | | `titleView` | `Widget? Function(Group? group, User? user, BuildContext context)?` | To set the title view for the message header. | | `auxiliaryButtonView` | `Widget? Function(Group? group, User? user, BuildContext context)?` | To set auxiliary view for the message header. | @@ -397,6 +428,44 @@ CometChatMessageHeader( *** +#### Options Menu + +You can add custom menu options to the message header using the `options` property. These options appear in a popup menu when the menu icon is tapped. + + + +```dart +CometChatMessageHeader( + user: user, + options: (User? user, Group? group, BuildContext context) { + return [ + CometChatOption( + id: "view_profile", + title: "View Profile", + icon: Icons.person, + onClick: () { + // Handle view profile action + }, + ), + CometChatOption( + id: "block_user", + title: "Block User", + icon: Icons.block, + onClick: () { + // Handle block user action + }, + ), + ]; + }, +) +``` + + + + + +*** + #### BackIcon You can customize the Back Icon according to your specific requirements by using the `.backButton` method. diff --git a/ui-kit/flutter/message-list.mdx b/ui-kit/flutter/message-list.mdx index 41a73db4c..54b943d1a 100644 --- a/ui-kit/flutter/message-list.mdx +++ b/ui-kit/flutter/message-list.mdx @@ -409,15 +409,35 @@ Customize the appearance of `CometChatMessageList` using `CometChatMessageListSt | `avatarStyle` | `CometChatAvatarStyle?` | Style for avatar in message bubble | | `emptyStateTextStyle` | `TextStyle?` | Style for empty state text | | `emptyStateTextColor` | `Color?` | Color for empty state text | +| `emptyStateSubtitleStyle` | `TextStyle?` | Style for empty state subtitle | +| `emptyStateSubtitleColor` | `Color?` | Color for empty state subtitle | | `errorStateTextStyle` | `TextStyle?` | Style for error state text | | `errorStateTextColor` | `Color?` | Color for error state text | +| `errorStateSubtitleStyle` | `TextStyle?` | Style for error state subtitle | +| `errorStateSubtitleColor` | `Color?` | Color for error state subtitle | | `incomingMessageBubbleStyle` | `CometChatIncomingMessageBubbleStyle?` | Style for incoming message bubble | | `outgoingMessageBubbleStyle` | `CometChatOutgoingMessageBubbleStyle?` | Style for outgoing message bubble | | `messageInformationStyle` | `CometChatMessageInformationStyle?` | Style for message information | | `messageOptionSheetStyle` | `CometChatMessageOptionSheetStyle?` | Style for message option sheet | | `mentionsStyle` | `CometChatMentionsStyle?` | Style for mentions | +| `actionBubbleStyle` | `CometChatActionBubbleStyle?` | Style for group action bubbles | +| `reactionListStyle` | `CometChatReactionListStyle?` | Style for reaction list | | `reactionsStyle` | `CometChatReactionsStyle?` | Style for reactions | | `aiSmartRepliesStyle` | `CometChatAISmartRepliesStyle?` | Style for smart replies | +| `aiConversationStarterStyle` | `CometChatAIConversationStarterStyle?` | Style for conversation starter | +| `aiConversationSummaryStyle` | `CometChatAIConversationSummaryStyle?` | Style for conversation summary | +| `aiAssistantSuggestedMessageTextStyle` | `TextStyle?` | Text style for AI suggested messages | +| `aiAssistantSuggestedMessageTextColor` | `Color?` | Text color for AI suggested messages | +| `aiAssistantSuggestedMessageBorder` | `Border?` | Border for AI suggested messages | +| `aiAssistantSuggestedMessageBorderRadius` | `BorderRadius?` | Border radius for AI suggested messages | +| `aiAssistantSuggestedMessageBackgroundColor` | `Color?` | Background color for AI suggested messages | +| `aiAssistantSuggestedMessageIconColor` | `Color?` | Icon color for AI suggested messages | +| `emptyChatGreetingTitleTextColor` | `Color?` | Text color for empty chat greeting title | +| `emptyChatGreetingTitleTextStyle` | `TextStyle?` | Text style for empty chat greeting title | +| `emptyChatGreetingSubtitleTextColor` | `Color?` | Text color for empty chat greeting subtitle | +| `emptyChatGreetingSubtitleTextStyle` | `TextStyle?` | Text style for empty chat greeting subtitle | +| `flagMessageStyle` | `CometchatFlagMessageStyle?` | Style for flag message dialog | +| `newMessageIndicatorStyle` | `CometChatNewMessageIndicatorStyle?` | Style for new message indicator | ### Example: Custom Styling @@ -674,6 +694,10 @@ CometChatMessageList( | `generateConversationSummary` | `bool?` | `false` | Generate conversation summary | | `hideReplyOption` | `bool?` | `false` | Hide reply option | | `flagReasonLocalizer` | `String Function(String)?` | - | Flag reason localizer | +| `reactionsRequestBuilder` | `ReactionsRequestBuilder?` | - | Request builder for reactions | +| `stateCallBack` | `Function(CometChatMessageListController)?` | - | Callback to access controller | +| `customSoundForMessagePackage` | `String?` | - | Package name for custom sound | +| `messageId` | `int?` | - | Specific message ID to scroll to | diff --git a/ui-kit/flutter/search.mdx b/ui-kit/flutter/search.mdx index 34a29c7d2..61ab7042f 100644 --- a/ui-kit/flutter/search.mdx +++ b/ui-kit/flutter/search.mdx @@ -400,7 +400,11 @@ CometChatSearch( | `searchFilterChipBackgroundColor` | `Color?` | Background color of filter chips | | `searchFilterChipSelectedBackgroundColor` | `Color?` | Background color of selected filter chips | | `searchFilterChipTextColor` | `Color?` | Text color of filter chips | +| `searchFilterChipTextStyle` | `TextStyle?` | Text style of filter chips | | `searchFilterChipSelectedTextColor` | `Color?` | Text color of selected filter chips | +| `searchFilterChipSelectedTextStyle` | `TextStyle?` | Text style of selected filter chips | +| `searchFilterIconColor` | `Color?` | Color of filter icons | +| `searchFilterSelectedIconColor` | `Color?` | Color of selected filter icons | | `searchFilterChipBorder` | `Border?` | Border of filter chips | | `searchFilterChipSelectedBorder` | `Border?` | Border of selected filter chips | | `searchFilterChipBorderRadius` | `BorderRadius?` | Border radius of filter chips | @@ -422,8 +426,12 @@ CometChatSearch( | `searchMessageDateSeparatorStyle` | `CometChatDateStyle?` | Style of date separators | | `searchEmptyStateTextColor` | `Color?` | Text color for empty state | | `searchEmptyStateTextStyle` | `TextStyle?` | Style for empty state text | +| `searchEmptyStateSubtitleColor` | `Color?` | Color for empty state subtitle | +| `searchEmptyStateSubtitleStyle` | `TextStyle?` | Style for empty state subtitle | | `searchErrorStateTextColor` | `Color?` | Text color for error state | | `searchErrorStateTextStyle` | `TextStyle?` | Style for error state text | +| `searchErrorStateSubtitleColor` | `Color?` | Color for error state subtitle | +| `searchErrorStateSubtitleStyle` | `TextStyle?` | Style for error state subtitle | | `searchSeeMoreColor` | `Color?` | Color of "See More" button | | `searchSeeMoreStyle` | `TextStyle?` | Style of "See More" button | | `avatarStyle` | `CometChatAvatarStyle?` | Style for avatars | From 57b151eec1be8797e3fb2f8ca8494d84b7ccca03 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 13:31:14 +0530 Subject: [PATCH 030/106] updates integration guides --- ui-kit/flutter/flutter-conversation.mdx | 414 ++--------- ui-kit/flutter/flutter-one-to-one-chat.mdx | 710 +++---------------- ui-kit/flutter/flutter-tab-based-chat.mdx | 758 +++------------------ ui-kit/flutter/getting-started.mdx | 579 ++++------------ ui-kit/flutter/overview.mdx | 236 ++----- 5 files changed, 394 insertions(+), 2303 deletions(-) diff --git a/ui-kit/flutter/flutter-conversation.mdx b/ui-kit/flutter/flutter-conversation.mdx index 965ae8489..af6bd97a7 100644 --- a/ui-kit/flutter/flutter-conversation.mdx +++ b/ui-kit/flutter/flutter-conversation.mdx @@ -1,196 +1,51 @@ --- title: "Conversation List + Message View" sidebarTitle: "Conversation + Message" -description: "Build a two-panel chat interface with conversation list and message view using Flutter UI Kit widgets" +description: "Build a two-panel chat interface with conversation list and message view using Flutter UI Kit widgets." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** - -```dart -// Show conversations with navigation to messages -CometChatConversations( - showBackButton: true, - onItemTap: (conversation) { - final target = conversation.conversationWith; - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => MessagesScreen( - user: target is User ? target : null, - group: target is Group ? target : null, - ), - ), - ); - }, -) - -// Messages screen with header, list, and composer -Scaffold( - appBar: CometChatMessageHeader(user: user, group: group), - body: Column( - children: [ - Expanded(child: CometChatMessageList(user: user, group: group)), - CometChatMessageComposer(user: user, group: group), - ], - ), -) -``` + -**Key Components:** -- **Conversations** → [CometChatConversations](/ui-kit/flutter/conversations) -- **Message List** → [CometChatMessageList](/ui-kit/flutter/message-list) -- **Message Composer** → [CometChatMessageComposer](/ui-kit/flutter/message-composer) -- **Message Header** → [CometChatMessageHeader](/ui-kit/flutter/message-header) - +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Framework | Flutter | +| Components | `CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Two-panel — conversation list + message view with Navigator push | +| Prerequisite | Complete [Getting Started](/ui-kit/flutter/getting-started) Steps 1–4 first | +| Pattern | WhatsApp, Telegram, Slack | -The **Conversation List + Message View** layout provides a seamless **two-panel chat interface**, commonly seen in modern messaging apps like **WhatsApp Web**, **Slack**, and **Microsoft Teams**. + -This layout allows users to switch between conversations while keeping the active chat open, delivering a **smooth, real-time messaging experience**. +This guide builds a two-panel chat layout — conversation list that navigates to a message screen. Users tap a conversation to open it. + +This assumes you've already completed [Getting Started](/ui-kit/flutter/getting-started) (project created, UI Kit installed, init + login working). -*** - -## **How It Works** - -This implementation uses Flutter's navigation system to create a mobile-friendly chat experience: - -1. **Conversation List Screen** – Displays all recent conversations using `CometChatConversations` -2. **Navigation** – Tapping a conversation pushes the message screen onto the navigation stack -3. **Message Screen** – Shows the full chat interface with header, message list, and composer -4. **Back Navigation** – Users can return to the conversation list using the back button +[View Sample App on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) -*** - -## **Implementation** - -### **Step 1: Render the Conversation Component** - -The `CometChatConversations` widget displays all conversations related to the currently logged-in user. Follow the steps below to render this component: +--- - - -```dart main.dart -@override -Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: CometChatConversations( - showBackButton: true, - onItemTap: (conversation) { - final target = conversation.conversationWith; +## What You're Building - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => MessagesScreen( - user: target is User ? target : null, - group: target is Group ? target : null, - ), - ), - ); - }, - ), - ), - ); -} -``` - - +Two screens working together: -**Key Properties:** +1. **Conversation list** — shows all active conversations (users and groups) +2. **Message screen** — header + messages + composer for the selected conversation -| Property | Type | Description | -| --- | --- | --- | -| `showBackButton` | bool | Shows/hides the back button in the app bar | -| `onItemTap` | Function | Callback when a conversation is tapped | -| `conversationWith` | User or Group | The target entity (user or group) for the conversation | +--- -*** +## Step 1 — Create the Conversations Screen -### **Full Example: main.dart** +The `CometChatConversations` widget displays all conversations. Tapping one navigates to the message screen. - - -```dart main.dart +```dart title="lib/conversations_page.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling import 'messages_screen.dart'; -import 'cometchat_config.dart'; - -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), - ); - } -} - -class Home extends StatelessWidget { - const Home({super.key}); - - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..appId = CometChatConfig.appId - ..region = CometChatConfig.region - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions - ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling - - await CometChatUIKit.init(uiKitSettings: settings.build()); - await CometChatUIKit.login( - 'cometchat-uid-1', - onSuccess: (_) => debugPrint('✅ Login Successful'), - onError: (err) => throw Exception('Login Failed: $err'), - ); - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), - ); - } - if (snap.hasError) { - return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), - ); - } - return const ConversationsPage(); - }, - ); - } -} class ConversationsPage extends StatelessWidget { const ConversationsPage({super.key}); @@ -200,10 +55,8 @@ class ConversationsPage extends StatelessWidget { return Scaffold( body: SafeArea( child: CometChatConversations( - showBackButton: true, onItemTap: (conversation) { final target = conversation.conversationWith; - Navigator.push( context, MaterialPageRoute( @@ -220,60 +73,38 @@ class ConversationsPage extends StatelessWidget { } } ``` - - - -*** -### **Step 2: Render the Messages Component** +Key points: +- `onItemTap` fires when a conversation is tapped, passing the `Conversation` object. +- `conversationWith` returns either a `User` or `Group` — pass the correct one to the message screen. -To create a complete messaging view, include the following components in `messages_screen.dart`: +--- -* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions -* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation -* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages +## Step 2 — Create the Messages Screen - - - +The message screen combines header, message list, and composer. - - -```dart messages_screen.dart +```dart title="lib/messages_screen.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class MessagesScreen extends StatefulWidget { +class MessagesScreen extends StatelessWidget { final User? user; final Group? group; - const MessagesScreen({Key? key, this.user, this.group}) : super(key: key); - - @override - State createState() => _MessagesScreenState(); -} + const MessagesScreen({super.key, this.user, this.group}); -class _MessagesScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - ), + appBar: CometChatMessageHeader(user: user, group: group), body: SafeArea( child: Column( children: [ Expanded( - child: CometChatMessageList( - user: widget.user, - group: widget.group, - ), - ), - CometChatMessageComposer( - user: widget.user, - group: widget.group, + child: CometChatMessageList(user: user, group: group), ), + CometChatMessageComposer(user: user, group: group), ], ), ), @@ -281,175 +112,38 @@ class _MessagesScreenState extends State { } } ``` - - - -**Component Breakdown:** -| Component | Purpose | Key Features | -| --- | --- | --- | -| `CometChatMessageHeader` | Shows conversation title, avatar, and actions | User/group info, back button, call buttons | -| `CometChatMessageList` | Displays messages in chronological order | Real-time updates, reactions, replies | -| `CometChatMessageComposer` | Input field for composing messages | Text, media, attachments, emojis | +| Component | Purpose | +| --- | --- | +| `CometChatMessageHeader` | Shows conversation title, avatar, and call buttons | +| `CometChatMessageList` | Displays messages with real-time updates | +| `CometChatMessageComposer` | Input field for text, media, and attachments | -*** - -### **Step 3: Run the App** +--- -Use the following command to run the app on a connected device or emulator: +## Step 3 — Run the App ```bash flutter run ``` -This will launch the app and display the **Conversation List**. Tapping a conversation will navigate to the **Message View**. - -*** - -## **Customization Options** - -### **Conversation List Customization** - - - -```dart -CometChatConversations( - title: "My Chats", - showBackButton: false, - hideSearch: false, - onItemTap: (conversation) { - // Custom navigation logic - }, - onItemLongPress: (conversation) { - // Show options menu - }, - conversationsStyle: ConversationsStyle( - background: Colors.white, - titleStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), - ), -) -``` - - - -### **Message Screen Customization** - - - -```dart -CometChatMessageList( - user: user, - group: group, - hideMessageComposer: false, - hideMessageHeader: false, - messageListStyle: MessageListStyle( - background: Colors.grey[100], - ), -) -``` - - - -For complete customization options, see: -* [Conversations Customization](/ui-kit/flutter/conversations) -* [Message List Customization](/ui-kit/flutter/message-list) -* [Message Composer Customization](/ui-kit/flutter/message-composer) -* [Theming Guide](/ui-kit/flutter/theme-introduction) - -*** - -## **Common Use Cases** - - - - - - ```dart - CometChatConversations( - conversationsRequestBuilder: ConversationsRequestBuilder() - ..conversationType = CometChatConversationType.user // or .group - ..limit = 30, - ) - ``` - - - - - - - - ```dart - CometChatConversations( - onItemLongPress: (conversation) { - showDialog( - context: context, - builder: (context) => AlertDialog( - title: Text('Options'), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - title: Text('Delete Conversation'), - onTap: () { - // Delete conversation logic - }, - ), - ], - ), - ), - ); - }, - ) - ``` - - - - - - - - ```dart - Navigator.push( - context, - PageRouteBuilder( - pageBuilder: (context, animation, secondaryAnimation) => MessagesScreen( - user: target is User ? target : null, - group: target is Group ? target : null, - ), - transitionsBuilder: (context, animation, secondaryAnimation, child) { - return SlideTransition( - position: Tween( - begin: const Offset(1.0, 0.0), - end: Offset.zero, - ).animate(animation), - child: child, - ); - }, - ), - ); - ``` - - - - +You should see the conversation list. Tapping a conversation navigates to the message screen. -*** +--- -## **Next Steps** +## Next Steps - - Learn about all conversation list customization options + + Customize the conversation list - - Explore message list, header, and composer features + + Customize the message view - - Customize colors, fonts, and styles to match your brand + + Customize colors and styles - - Handle real-time events and user interactions + + Handle real-time events - -*** diff --git a/ui-kit/flutter/flutter-one-to-one-chat.mdx b/ui-kit/flutter/flutter-one-to-one-chat.mdx index 136095916..5b6d8c0ab 100644 --- a/ui-kit/flutter/flutter-one-to-one-chat.mdx +++ b/ui-kit/flutter/flutter-one-to-one-chat.mdx @@ -1,213 +1,57 @@ --- -title: "Building A One To One/Group Chat Experience" -sidebarTitle: "One To One/Group Chat" -description: "Create a focused direct messaging interface for one-to-one or group conversations using Flutter UI Kit" +title: "One-to-One / Group Chat" +sidebarTitle: "One-to-One / Group Chat" +description: "Build a focused one-to-one or group chat experience in Flutter with CometChat UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -// Fetch a user and show messages directly -Future fetchCometChatUser(String uid) async { - final completer = Completer(); - CometChat.getUser( - uid, - onSuccess: (user) => completer.complete(user), - onError: (error) => completer.completeError(error), - ); - return completer.future; -} - -// Show messages screen directly -FutureBuilder( - future: fetchCometChatUser("cometchat-uid-2"), - builder: (context, snapshot) { - if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } - return CircularProgressIndicator(); - }, -) +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Framework | Flutter | +| Components | `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Single chat window — no conversation list | +| Prerequisite | Complete [Getting Started](/ui-kit/flutter/getting-started) Steps 1–4 first | +| Pattern | Support chat, embedded widgets, focused messaging | -// Messages screen -Scaffold( - appBar: CometChatMessageHeader(user: user, group: group), - body: Column( - children: [ - Expanded(child: CometChatMessageList(user: user, group: group)), - CometChatMessageComposer(user: user, group: group), - ], - ), -) -``` + -**Key Components:** -- **Message List** → [CometChatMessageList](/ui-kit/flutter/message-list) -- **Message Composer** → [CometChatMessageComposer](/ui-kit/flutter/message-composer) -- **Message Header** → [CometChatMessageHeader](/ui-kit/flutter/message-header) - +This guide builds a single chat window — no conversation list. Users go directly into a one-to-one or group chat. Good for support chat, deep links, or focused messaging. -The **One-to-One Chat** feature provides a streamlined **direct messaging interface**, making it ideal for **support chats, dating apps, and private messaging platforms**. This setup eliminates distractions by focusing solely on a **dedicated chat window**. +This assumes you've already completed [Getting Started](/ui-kit/flutter/getting-started) (project created, UI Kit installed, init + login working). -*** - -## **How It Works** - -This implementation bypasses the conversation list and opens directly into a chat: - -1. **Fetch User/Group** – Retrieve the target user or group using their UID/GUID -2. **Direct Navigation** – Launch directly into the message screen -3. **Focused Experience** – No conversation list, just the active chat -4. **Ideal for Context** – Perfect for support tickets, notifications, or deep links - -*** - -## **Use Cases** - -* **Customer Support** – Direct users to agent chat from help center -* **Dating Apps** – Open chat after a match -* **Notifications** – Deep link from push notification to specific chat -* **Onboarding** – Guide new users through a welcome chat -* **Contextual Messaging** – Start chat from user profile or product page +[View Sample App on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) -*** - -## **Implementation** - -### **Step 1: Render the Message View** +--- -The `CometChatMessageList` widget displays all messages for a specific user or group. Follow the steps below to render this component: +## What You're Building - - -```dart main.dart -@override -Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: FutureBuilder( - future: fetchCometChatUser("cometchat-uid-2"), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return const Center(child: CircularProgressIndicator()); - } else if (snapshot.hasError) { - return Center(child: Text("Error: ${snapshot.error}")); - } else if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } else { - return const Center(child: Text("User not found")); - } - }, - ), - ), - ); -} -``` - - +Three components stacked vertically: -**Key Concepts:** +1. **Chat header** — displays recipient name, avatar, and call buttons +2. **Message list** — real-time chat history +3. **Message composer** — text input with media and emojis -| Concept | Description | -| --- | --- | -| `fetchCometChatUser()` | Async function to retrieve user by UID | -| `FutureBuilder` | Widget that builds based on async operation state | -| `MessagesScreen` | Custom widget containing message components | +--- -*** +## Step 1 — Create the Chat Screen -### **Full Example: main.dart** +The app fetches a user on mount and renders the message components. - - -```dart main.dart +```dart title="lib/chat_screen.dart" +import 'dart:async'; import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling -import 'messages_screen.dart'; -import 'cometchat_config.dart'; - -import 'dart:async'; - -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), - ); - } -} -class Home extends StatelessWidget { - const Home({super.key}); - - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..appId = CometChatConfig.appId - ..region = CometChatConfig.region - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions - ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling - - await CometChatUIKit.init(uiKitSettings: settings.build()); - await CometChatUIKit.login( - 'cometchat-uid-1', - onSuccess: (_) => debugPrint('✅ Login Successful'), - onError: (err) => throw Exception('Login Failed: $err'), - ); - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), - ); - } - if (snap.hasError) { - return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), - ); - } - return const MessagesPage(); - }, - ); - } -} - -class MessagesPage extends StatelessWidget { - const MessagesPage({super.key}); +class ChatScreen extends StatelessWidget { + const ChatScreen({super.key}); - Future fetchCometChatUser(String uid) async { + Future fetchUser(String uid) async { final completer = Completer(); CometChat.getUser( uid, @@ -219,123 +63,49 @@ class MessagesPage extends StatelessWidget { @override Widget build(BuildContext context) { - return Scaffold( - body: SafeArea( - child: FutureBuilder( - future: fetchCometChatUser("cometchat-uid-2"), - builder: (context, snapshot) { - if (snapshot.connectionState == ConnectionState.waiting) { - return const Center(child: CircularProgressIndicator()); - } else if (snapshot.hasError) { - return Center(child: Text("Error: ${snapshot.error}")); - } else if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } else { - return const Center(child: Text("User not found")); - } - }, - ), - ), - ); - } -} -``` - - - -*** - -### **Step 2: Render the Messages Component** - -To create a complete messaging view, include the following components in `messages_screen.dart`: - -* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions -* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation -* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages - - - - - - - -```dart messages_screen.dart -import 'package:flutter/material.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -class MessagesScreen extends StatefulWidget { - final User? user; - final Group? group; - - const MessagesScreen({Key? key, this.user, this.group}) : super(key: key); - - @override - State createState() => _MessagesScreenState(); -} - -class _MessagesScreenState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - ), - body: SafeArea( - child: Column( - children: [ - Expanded( - child: CometChatMessageList( - user: widget.user, - group: widget.group, - ), - ), - CometChatMessageComposer( - user: widget.user, - group: widget.group, + return FutureBuilder( + future: fetchUser("cometchat-uid-2"), // Replace with target UID + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + if (snapshot.hasError) { + return Scaffold( + body: Center(child: Text('Error: ${snapshot.error}')), + ); + } + final user = snapshot.data!; + return Scaffold( + appBar: CometChatMessageHeader(user: user), + body: SafeArea( + child: Column( + children: [ + Expanded(child: CometChatMessageList(user: user)), + CometChatMessageComposer(user: user), + ], ), - ], - ), - ), + ), + ); + }, ); } } ``` - - - -**Component Breakdown:** - -| Component | Purpose | Key Features | -| --- | --- | --- | -| `CometChatMessageHeader` | Shows conversation title, avatar, and actions | User/group info, back button, call buttons | -| `CometChatMessageList` | Displays messages in chronological order | Real-time updates, reactions, replies | -| `CometChatMessageComposer` | Input field for composing messages | Text, media, attachments, emojis | - -*** -### **Step 3: Run the App** +Key points: +- `CometChat.getUser(uid)` fetches the user object — you need a real user object, not a manually constructed one. +- Pass either `user` or `group` to the message components, never both. -Use the following command to run the app on a connected device or emulator: - -```bash -flutter run -``` - -This will launch the app, and you should see the one-to-one chat interface with the message header, list, and composer ready for use. - -*** - -## **Variations** +--- -### **For Group Chat** +## Switching to Group Chat -To open a group chat instead of a one-to-one chat, fetch a group instead of a user: +To load a group chat instead, use `CometChat.getGroup()`: - - ```dart -Future fetchCometChatGroup(String guid) async { +Future fetchGroup(String guid) async { final completer = Completer(); CometChat.getGroup( guid, @@ -345,356 +115,52 @@ Future fetchCometChatGroup(String guid) async { return completer.future; } -// In your widget +// Then in build(): FutureBuilder( - future: fetchCometChatGroup("your-group-guid"), + future: fetchGroup("your-group-guid"), builder: (context, snapshot) { if (snapshot.hasData) { - return MessagesScreen(group: snapshot.data!); - } - return CircularProgressIndicator(); - }, -) -``` - - - -### **From Route Parameters** - -Pass user/group ID through navigation: - - - -```dart -// Navigate with parameters -Navigator.push( - context, - MaterialPageRoute( - builder: (_) => ChatScreen(userId: "cometchat-uid-2"), - ), -); - -// ChatScreen widget -class ChatScreen extends StatelessWidget { - final String userId; - - const ChatScreen({Key? key, required this.userId}) : super(key: key); - - Future fetchUser() async { - final completer = Completer(); - CometChat.getUser( - userId, - onSuccess: (user) => completer.complete(user), - onError: (error) => completer.completeError(error), - ); - return completer.future; - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: fetchUser(), - builder: (context, snapshot) { - if (snapshot.hasData) { - return MessagesScreen(user: snapshot.data!); - } - return Scaffold( - body: Center(child: CircularProgressIndicator()), - ); - }, - ); - } -} -``` - - - -### **From Deep Link** - -Handle deep links to open specific chats: - - - -```dart -// In your main app -MaterialApp( - onGenerateRoute: (settings) { - if (settings.name == '/chat') { - final args = settings.arguments as Map; - return MaterialPageRoute( - builder: (_) => ChatScreen( - userId: args['userId'], - groupId: args['groupId'], + final group = snapshot.data!; + return Scaffold( + appBar: CometChatMessageHeader(group: group), + body: Column( + children: [ + Expanded(child: CometChatMessageList(group: group)), + CometChatMessageComposer(group: group), + ], ), ); } - return null; + return const CircularProgressIndicator(); }, ) - -// Navigate from deep link -Navigator.pushNamed( - context, - '/chat', - arguments: {'userId': 'cometchat-uid-2'}, -); -``` - - - -*** - -## **Customization Options** - -### **Hide Header or Composer** - - - -```dart -MessagesScreen( - user: user, - hideMessageHeader: true, // Hide the header - hideMessageComposer: false, // Show the composer -) ``` - - - -### **Custom Message Actions** - - -```dart -CometChatMessageList( - user: user, - onMessageTap: (message) { - // Handle message tap - }, - onMessageLongPress: (message) { - // Show options menu - }, -) -``` - - +--- -### **Styling** +## Step 2 — Run the App - - -```dart -CometChatMessageList( - user: user, - messageListStyle: MessageListStyle( - background: Colors.grey[100], - loadingIconTint: Colors.blue, - ), -) +```bash +flutter run ``` - - - -For complete customization options, see: -* [Message List Customization](/ui-kit/flutter/message-list) -* [Message Header Customization](/ui-kit/flutter/message-header) -* [Message Composer Customization](/ui-kit/flutter/message-composer) -* [Theming Guide](/ui-kit/flutter/theme-introduction) -*** +You should see the chat window load with the conversation for the UID you set. -## **Common Use Cases** - - - - - - ```dart - // From support ticket screen - ElevatedButton( - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => ChatScreen( - userId: ticket.assignedAgentId, - ), - ), - ); - }, - child: Text('Chat with Support'), - ) - ``` - - - - - - - - ```dart - // From user profile screen - IconButton( - icon: Icon(Icons.message), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => ChatScreen(userId: profile.userId), - ), - ); - }, - ) - ``` - - - - - - - - ```dart - // Handle notification tap - void handleNotificationTap(Map data) { - final userId = data['senderId']; - Navigator.pushNamed( - context, - '/chat', - arguments: {'userId': userId}, - ); - } - ``` - - - - - - - - ```dart - CometChatMessageComposer( - user: user, - text: "Hello! I need help with...", // Pre-filled text - ) - ``` - - - - - -*** - -## **Best Practices** - - - - Always handle errors when fetching users or groups: - - - - ```dart - FutureBuilder( - future: fetchCometChatUser(userId), - builder: (context, snapshot) { - if (snapshot.hasError) { - return Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.error, size: 48, color: Colors.red), - SizedBox(height: 16), - Text('Failed to load chat'), - ElevatedButton( - onPressed: () => setState(() {}), // Retry - child: Text('Retry'), - ), - ], - ), - ), - ); - } - // ... rest of builder - }, - ) - ``` - - - - - - Provide clear loading indicators: - - - - ```dart - if (snapshot.connectionState == ConnectionState.waiting) { - return Scaffold( - body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - CircularProgressIndicator(), - SizedBox(height: 16), - Text('Loading chat...'), - ], - ), - ), - ); - } - ``` - - - - - - Cache fetched users to avoid repeated API calls: - - - - ```dart - class UserCache { - static final Map _cache = {}; - - static Future getUser(String uid) async { - if (_cache.containsKey(uid)) { - return _cache[uid]!; - } - - final completer = Completer(); - CometChat.getUser( - uid, - onSuccess: (user) { - _cache[uid] = user; - completer.complete(user); - }, - onError: (error) => completer.completeError(error), - ); - return completer.future; - } - } - ``` - - - - - -*** +--- -## **Next Steps** +## Next Steps - - Explore message list, header, and composer features + + Customize the message view - - Add a conversation list for multi-chat support + + Add a conversation list - - Customize colors, fonts, and styles to match your brand + + Customize colors and styles - - Handle real-time events and user interactions + + Handle real-time events - -*** diff --git a/ui-kit/flutter/flutter-tab-based-chat.mdx b/ui-kit/flutter/flutter-tab-based-chat.mdx index 5959a206b..ba02849dc 100644 --- a/ui-kit/flutter/flutter-tab-based-chat.mdx +++ b/ui-kit/flutter/flutter-tab-based-chat.mdx @@ -1,248 +1,53 @@ --- -title: "Building A Messaging UI With Tabs, Sidebar, And Message View" -sidebarTitle: "Tab Based Chat Experience" -description: "Create a multi-tab chat interface with conversations, calls, users, and groups using Flutter bottom navigation" +title: "Tab-Based Chat" +sidebarTitle: "Tab-Based Chat" +description: "Build a tab-based messaging UI with chats, calls, users, and groups in Flutter with CometChat UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** - -```dart -// Tab-based UI with bottom navigation -Scaffold( - body: PageView( - controller: _pageController, - children: [ - CometChatConversations(), - CometChatCallLogs(), - CometChatUsers(), - CometChatGroups(), - ], - ), - bottomNavigationBar: BottomNavigationBar( - currentIndex: _selectedIndex, - onTap: (index) { - setState(() => _selectedIndex = index); - _pageController.jumpToPage(index); - }, - items: [ - BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Chat"), - BottomNavigationBarItem(icon: Icon(Icons.call), label: "Calls"), - BottomNavigationBarItem(icon: Icon(Icons.person), label: "Users"), - BottomNavigationBarItem(icon: Icon(Icons.group), label: "Groups"), - ], - ), -) -``` + -**Key Components:** -- **Conversations** → [CometChatConversations](/ui-kit/flutter/conversations) -- **Call Logs** → [CometChatCallLogs](/ui-kit/flutter/call-logs) -- **Users** → [CometChatUsers](/ui-kit/flutter/users) -- **Groups** → [CometChatGroups](/ui-kit/flutter/groups) - +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Framework | Flutter | +| Components | `CometChatConversations`, `CometChatCallLogs`, `CometChatUsers`, `CometChatGroups`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Bottom navigation tabs (Chats, Calls, Users, Groups) + message view | +| Prerequisite | Complete [Getting Started](/ui-kit/flutter/getting-started) Steps 1–4 first | +| Pattern | Full-featured messaging app with multiple sections | -This guide walks you through creating a **tab-based messaging UI** using **Flutter** and **CometChat UIKit**. The UI will include different sections for **Chats, Calls, Users, and Groups**, allowing seamless navigation. + -*** +This guide builds a tabbed messaging UI — Chats, Calls, Users, and Groups tabs with bottom navigation. Good for full-featured apps that need more than just conversations. -## **User Interface Preview** +This assumes you've already completed [Getting Started](/ui-kit/flutter/getting-started) (project created, UI Kit installed, init + login working). -This layout consists of: - -1. **Bottom Navigation Bar** – Tabs for switching between Chats, Calls, Users, and Groups -2. **Page View** – Displays the selected tab's content -3. **Conversation List** – Shows recent conversations with active users and groups -4. **Message View** – Opens when a conversation is tapped - -*** - -## **How It Works** - -This implementation uses Flutter's `BottomNavigationBar` and `PageView` to create a tabbed interface: - -1. **Bottom Navigation** – Provides quick access to different sections -2. **Page View** – Swipeable pages for each tab -3. **State Management** – Syncs selected tab with page view -4. **Navigation** – Tapping a conversation opens the message screen - -*** +[View Sample App on GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) -## **Use Cases** - -* **All-in-One Chat Apps** – Complete messaging solution with multiple features -* **Business Messengers** – Professional communication with organized sections -* **Social Platforms** – Community chat with user discovery -* **Support Apps** – Help desk with call logs and user management -* **Team Collaboration** – Internal communication with group management - -*** +--- -## **Implementation** +## What You're Building -### **Step 1: Render the Tab Component** +Three sections working together: -The tab-based UI uses `BottomNavigationBar` for navigation and `PageView` for content display: +1. **Bottom navigation** — switches between Chats, Calls, Users, and Groups +2. **Page view** — renders the list for the active tab +3. **Message view** — header + messages + composer for the selected item - - -```dart main.dart -@override -Widget build(BuildContext context) { - return Scaffold( - body: PageView( - controller: _pageController, - onPageChanged: (index) { - setState(() { - _selectedIndex = index; - }); - }, - children: [ - CometChatConversations( - showBackButton: false, - onItemTap: (conversation) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => MessagesScreen( - user: conversation.conversationWith is User - ? conversation.conversationWith as User - : null, - group: conversation.conversationWith is Group - ? conversation.conversationWith as Group - : null, - ), - ), - ); - }, - ), - CometChatCallLogs(), - CometChatUsers(), - CometChatGroups(), - ], - ), - bottomNavigationBar: BottomNavigationBar( - currentIndex: _selectedIndex, - onTap: _onItemTapped, - items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.chat), - label: "Chat", - ), - BottomNavigationBarItem( - icon: Icon(Icons.call), - label: "Calls", - ), - BottomNavigationBarItem( - icon: Icon(Icons.person), - label: "Users", - ), - BottomNavigationBarItem( - icon: Icon(Icons.group), - label: "Groups", - ), - ], - ), - ); -} -``` - - - -**Key Components:** - -| Component | Purpose | Key Features | -| --- | --- | --- | -| `PageView` | Container for swipeable pages | Smooth transitions, gesture support | -| `BottomNavigationBar` | Tab navigation | Icon + label, active state | -| `PageController` | Controls page view | Jump to page, animate transitions | +--- -*** +## Step 1 — Create the Tabs Screen -### **Full Example: main.dart** +The tabs screen uses `BottomNavigationBar` and `PageView` to create a tabbed interface. - - -```dart main.dart +```dart title="lib/tabs_screen.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling +import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; import 'messages_screen.dart'; -import 'cometchat_config.dart'; - -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), - ); - } -} - -class Home extends StatelessWidget { - const Home({super.key}); - - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..appId = CometChatConfig.appId - ..region = CometChatConfig.region - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions - ..callingExtension = CometChatCallingExtension(); // Optional: Include if you're using Audio/Video Calling - - await CometChatUIKit.init(uiKitSettings: settings.build()); - await CometChatUIKit.login( - 'cometchat-uid-1', - onSuccess: (_) => debugPrint('✅ Login Successful'), - onError: (err) => throw Exception('Login Failed: $err'), - ); - } - - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), - ); - } - if (snap.hasError) { - return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), - ); - } - return const TabsScreen(); - }, - ); - } -} class TabsScreen extends StatefulWidget { const TabsScreen({super.key}); @@ -256,9 +61,7 @@ class _TabsScreenState extends State { final PageController _pageController = PageController(); void _onItemTapped(int index) { - setState(() { - _selectedIndex = index; - }); + setState(() => _selectedIndex = index); _pageController.jumpToPage(index); } @@ -273,25 +76,17 @@ class _TabsScreenState extends State { return Scaffold( body: PageView( controller: _pageController, - onPageChanged: (index) { - setState(() { - _selectedIndex = index; - }); - }, + onPageChanged: (index) => setState(() => _selectedIndex = index), children: [ CometChatConversations( - showBackButton: false, onItemTap: (conversation) { + final target = conversation.conversationWith; Navigator.push( context, MaterialPageRoute( - builder: (context) => MessagesScreen( - user: conversation.conversationWith is User - ? conversation.conversationWith as User - : null, - group: conversation.conversationWith is Group - ? conversation.conversationWith as Group - : null, + builder: (_) => MessagesScreen( + user: target is User ? target : null, + group: target is Group ? target : null, ), ), ); @@ -299,24 +94,16 @@ class _TabsScreenState extends State { ), CometChatCallLogs(), CometChatUsers( - onItemTap: (user) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => MessagesScreen(user: user), - ), - ); - }, + onItemTap: (user) => Navigator.push( + context, + MaterialPageRoute(builder: (_) => MessagesScreen(user: user)), + ), ), CometChatGroups( - onItemTap: (group) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => MessagesScreen(group: group), - ), - ); - }, + onItemTap: (group) => Navigator.push( + context, + MaterialPageRoute(builder: (_) => MessagesScreen(group: group)), + ), ), ], ), @@ -327,82 +114,47 @@ class _TabsScreenState extends State { selectedItemColor: Colors.deepPurple, unselectedItemColor: Colors.grey, items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.chat), - label: "Chat", - ), - BottomNavigationBarItem( - icon: Icon(Icons.call), - label: "Calls", - ), - BottomNavigationBarItem( - icon: Icon(Icons.person), - label: "Users", - ), - BottomNavigationBarItem( - icon: Icon(Icons.group), - label: "Groups", - ), + BottomNavigationBarItem(icon: Icon(Icons.chat), label: "Chats"), + BottomNavigationBarItem(icon: Icon(Icons.call), label: "Calls"), + BottomNavigationBarItem(icon: Icon(Icons.person), label: "Users"), + BottomNavigationBarItem(icon: Icon(Icons.group), label: "Groups"), ], ), ); } } ``` - - - -*** -### **Step 2: Render the Messages Component** +Key points: +- `PageView` enables swipeable pages for each tab. +- `BottomNavigationBar` provides quick access to different sections. +- Each list component navigates to `MessagesScreen` on item tap. -To create a complete messaging view, include the following components in `messages_screen.dart`: +--- -* [Message Header](/ui-kit/flutter/message-header) – Displays conversation title and actions -* [Message List](/ui-kit/flutter/message-list) – Shows all messages in the conversation -* [Message Composer](/ui-kit/flutter/message-composer) – Input field for sending messages +## Step 2 — Create the Messages Screen - - - +Same as the [Conversation + Message](/ui-kit/flutter/flutter-conversation) guide: - - -```dart messages_screen.dart +```dart title="lib/messages_screen.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -class MessagesScreen extends StatefulWidget { +class MessagesScreen extends StatelessWidget { final User? user; final Group? group; - const MessagesScreen({Key? key, this.user, this.group}) : super(key: key); + const MessagesScreen({super.key, this.user, this.group}); - @override - State createState() => _MessagesScreenState(); -} - -class _MessagesScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - ), + appBar: CometChatMessageHeader(user: user, group: group), body: SafeArea( child: Column( children: [ - Expanded( - child: CometChatMessageList( - user: widget.user, - group: widget.group, - ), - ), - CometChatMessageComposer( - user: widget.user, - group: widget.group, - ), + Expanded(child: CometChatMessageList(user: user, group: group)), + CometChatMessageComposer(user: user, group: group), ], ), ), @@ -410,401 +162,43 @@ class _MessagesScreenState extends State { } } ``` - - - -*** -### **Step 3: Run the App** +--- -Use the following command to run the app on a connected device or emulator: +## Step 3 — Run the App ```bash flutter run ``` -This will launch the app, and you should see the tab-based chat experience with the sidebar and message view. You can navigate between different tabs (Chats, Calls, Users, and Groups) and interact with the messaging features seamlessly. - -*** - -## **Tab Descriptions** - -### **1. Chat Tab** - -Displays recent conversations with users and groups: - -* **CometChatConversations** – Shows conversation list -* **Real-time updates** – New messages appear instantly -* **Unread counts** – Badge showing unread message count -* **Last message preview** – Shows snippet of last message -* **Tap to open** – Navigate to full message view +You should see the tab bar at the bottom. Switch between Chats, Calls, Users, and Groups — tapping any item opens the message view. -### **2. Calls Tab** - -Shows call history and logs: - -* **CometChatCallLogs** – Displays all call records -* **Call types** – Audio and video calls -* **Call status** – Missed, incoming, outgoing -* **Tap to call back** – Initiate new call from history -* **Call duration** – Shows length of completed calls - -### **3. Users Tab** - -Browse and search all users: - -* **CometChatUsers** – Lists all available users -* **Search functionality** – Find users by name -* **User status** – Online/offline indicators -* **Tap to chat** – Start conversation with any user -* **User avatars** – Profile pictures - -### **4. Groups Tab** - -Manage and join groups: - -* **CometChatGroups** – Shows all groups -* **Group types** – Public, private, password-protected -* **Member count** – Number of participants -* **Join groups** – Request to join or join directly -* **Tap to chat** – Open group conversation +--- -*** +## Tab Descriptions -## **Customization Options** +| Tab | Component | Purpose | +| --- | --- | --- | +| Chats | `CometChatConversations` | Recent conversations with unread counts | +| Calls | `CometChatCallLogs` | Call history (audio/video) | +| Users | `CometChatUsers` | Browse and search all users | +| Groups | `CometChatGroups` | Browse and join groups | -### **Custom Tab Icons** +--- - - -```dart -BottomNavigationBar( - items: const [ - BottomNavigationBarItem( - icon: Icon(Icons.forum), - activeIcon: Icon(Icons.forum, size: 28), - label: "Chats", - ), - BottomNavigationBarItem( - icon: Icon(Icons.phone), - activeIcon: Icon(Icons.phone, size: 28), - label: "Calls", - ), - // ... more tabs - ], -) -``` - - - -### **Custom Tab Colors** - - - -```dart -BottomNavigationBar( - selectedItemColor: Colors.blue, - unselectedItemColor: Colors.grey, - backgroundColor: Colors.white, - elevation: 8, - // ... items -) -``` - - - -### **Disable Swipe Between Tabs** - - - -```dart -PageView( - controller: _pageController, - physics: NeverScrollableScrollPhysics(), // Disable swipe - children: [ - // ... pages - ], -) -``` - - - -### **Add More Tabs** - - - -```dart -// Add a Settings tab -children: [ - CometChatConversations(), - CometChatCallLogs(), - CometChatUsers(), - CometChatGroups(), - SettingsScreen(), // New tab -], - -items: [ - // ... existing items - BottomNavigationBarItem( - icon: Icon(Icons.settings), - label: "Settings", - ), -], -``` - - - -### **Custom Tab Styling** - - - -```dart -CometChatConversations( - title: "My Chats", - conversationsStyle: ConversationsStyle( - background: Colors.white, - titleStyle: TextStyle( - fontSize: 20, - fontWeight: FontWeight.bold, - ), - ), -) -``` - - - -For complete customization options, see: -* [Conversations Customization](/ui-kit/flutter/conversations) -* [Call Logs Customization](/ui-kit/flutter/call-logs) -* [Users Customization](/ui-kit/flutter/users) -* [Groups Customization](/ui-kit/flutter/groups) -* [Theming Guide](/ui-kit/flutter/theme-introduction) - -*** - -## **Common Use Cases** - - - - - - ```dart - BottomNavigationBarItem( - icon: Stack( - children: [ - Icon(Icons.chat), - if (unreadCount > 0) - Positioned( - right: 0, - top: 0, - child: Container( - padding: EdgeInsets.all(2), - decoration: BoxDecoration( - color: Colors.red, - borderRadius: BorderRadius.circular(10), - ), - constraints: BoxConstraints( - minWidth: 16, - minHeight: 16, - ), - child: Text( - '$unreadCount', - style: TextStyle( - color: Colors.white, - fontSize: 10, - ), - textAlign: TextAlign.center, - ), - ), - ), - ], - ), - label: "Chat", - ) - ``` - - - - - - - - ```dart - // Save selected tab to shared preferences - void _onItemTapped(int index) async { - setState(() => _selectedIndex = index); - _pageController.jumpToPage(index); - - final prefs = await SharedPreferences.getInstance(); - await prefs.setInt('selected_tab', index); - } - - // Load selected tab on init - @override - void initState() { - super.initState(); - _loadSelectedTab(); - } - - Future _loadSelectedTab() async { - final prefs = await SharedPreferences.getInstance(); - final savedIndex = prefs.getInt('selected_tab') ?? 0; - setState(() => _selectedIndex = savedIndex); - _pageController.jumpToPage(savedIndex); - } - ``` - - - - - - - - ```dart - void _onItemTapped(int index) { - setState(() => _selectedIndex = index); - _pageController.animateToPage( - index, - duration: Duration(milliseconds: 300), - curve: Curves.easeInOut, - ); - } - ``` - - - - - - - - ```dart - @override - Widget build(BuildContext context) { - return WillPopScope( - onWillPop: () async { - if (_selectedIndex != 0) { - // Go back to first tab instead of exiting - _onItemTapped(0); - return false; - } - return true; // Allow exit - }, - child: Scaffold( - // ... rest of widget - ), - ); - } - ``` - - - - - -*** - -## **Best Practices** - - - - Always dispose of controllers to prevent memory leaks: - - - - ```dart - @override - void dispose() { - _pageController.dispose(); - super.dispose(); - } - ``` - - - - - - For 4+ tabs, use fixed type to prevent shifting: - - - - ```dart - BottomNavigationBar( - type: BottomNavigationBarType.fixed, // Prevents label shifting - // ... rest of properties - ) - ``` - - - - - - Load tab content only when needed: - - - - ```dart - PageView( - controller: _pageController, - children: [ - _selectedIndex == 0 ? CometChatConversations() : SizedBox(), - _selectedIndex == 1 ? CometChatCallLogs() : SizedBox(), - _selectedIndex == 2 ? CometChatUsers() : SizedBox(), - _selectedIndex == 3 ? CometChatGroups() : SizedBox(), - ], - ) - ``` - - - - - - Refresh tab content when switching: - - - - ```dart - void _onItemTapped(int index) { - setState(() => _selectedIndex = index); - _pageController.jumpToPage(index); - - // Refresh current tab - _refreshTab(index); - } - - void _refreshTab(int index) { - // Implement refresh logic for each tab - switch (index) { - case 0: - // Refresh conversations - break; - case 1: - // Refresh call logs - break; - // ... etc - } - } - ``` - - - - - -*** - -## **Next Steps** +## Next Steps - Customize the conversation list appearance and behavior + Customize the conversation list - Configure call history and calling features + Configure call history - Manage user lists and group memberships + Manage user and group lists - - Customize colors, fonts, and styles to match your brand + + Customize colors and styles - -*** diff --git a/ui-kit/flutter/getting-started.mdx b/ui-kit/flutter/getting-started.mdx index ac00ff131..df8966cce 100644 --- a/ui-kit/flutter/getting-started.mdx +++ b/ui-kit/flutter/getting-started.mdx @@ -1,275 +1,119 @@ --- -title: "Getting Started With CometChat Flutter UI Kit" +title: "Getting Started" sidebarTitle: "Getting Started" -description: "Install and configure CometChat Flutter UI Kit with step-by-step setup, initialization, and authentication guide" +description: "Add CometChat to a Flutter app in 5 steps: create project, install, init, login, render." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Setup Reference** + -```bash -# Install -flutter pub add cometchat_chat_uikit -flutter pub add cometchat_calls_uikit # Optional: for calling - -# Initialize (run once at app start) -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "YOUR_APP_ID" - ..region = "YOUR_REGION" - ..authKey = "YOUR_AUTH_KEY" - ..subscriptionType = CometChatSubscriptionType.allUsers - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() - ..callingExtension = CometChatCallingExtension() -).build(); -await CometChatUIKit.init(uiKitSettings: uiKitSettings); - -# Login (after init) -await CometChatUIKit.login("cometchat-uid-1"); -``` - -**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 +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Init | `CometChatUIKit.init(uiKitSettings)` — must resolve before `login()` | +| Login | `CometChatUIKit.login("UID")` — must resolve before rendering widgets | +| Order | `init()` → `login()` → render. Breaking this order = blank screen | +| Auth Key | Dev/testing only. Use Auth Token in production | +| Calling | Optional. Install `cometchat_calls_uikit` to enable | +| Platforms | iOS 13.0+, Android API 24+ (with calling) | -**Integration Paths:** -- **Conversation List + Message** → [flutter-conversation](/ui-kit/flutter/flutter-conversation) -- **One-to-One Chat** → [flutter-one-to-one-chat](/ui-kit/flutter/flutter-one-to-one-chat) -- **Tab-Based Chat** → [flutter-tab-based-chat](/ui-kit/flutter/flutter-tab-based-chat) - + -The **CometChat UI Kit for Flutter** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI widgets**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. - -With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat Flutter UI Kit. +This guide walks you through adding CometChat to a Flutter app. By the end you'll have a working chat UI. - + -*** - -## **Prerequisites** - -Before installing the **CometChat UI Kit for Flutter**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: - -* **User Management** -* **Group Chat & Messaging** -* **Voice & Video Calling** -* **Real-time Notifications** - - - -To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: - -1. **App ID** -2. **Auth Key** -3. **Region** - -Ensure you have these details ready before proceeding with the installation and configuration. - - - -*** - -## **Register & Set Up CometChat** - -Follow these steps to **register on CometChat** and **set up your development environment**. - -### **Step 1: Register on CometChat** - -To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. - -🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** - -### **Step 2: Get Your Application Keys** - -After registering, create a **new app** and retrieve your **authentication details**: - -1. Navigate to the **QuickStart** or **API & Auth Keys** section. - -2. Note down the following keys: - - * **App ID** - * **Auth Key** - * **Region** - - - -Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **iOS, Android, and web**. - - - -### **Step 3: Set Up Your Development Environment** +--- -Ensure your system meets the following **prerequisites** before proceeding with integration. +## Prerequisites -**System Requirements:** +You need three things from the [CometChat Dashboard](https://app.cometchat.com/): -* **Flutter** installed on your system (Flutter 3.0 or higher recommended) -* **Android Studio** or **VS Code** with configured Flutter/Dart plugins -* **Xcode & CocoaPods** for iOS development -* An **iOS device or simulator** with iOS 13.0 or above -* An **Android device or emulator** with Android version 5.0 (API level 21) or above +| 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 Flutter 3.0+ installed with Android Studio or VS Code. -## **Getting Started** + +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 Flutter Application Project** +--- -To get started, create a new Flutter application project: +## Step 1 — Create a Flutter Project ```bash flutter create my_chat_app cd my_chat_app ``` -*** - -### **Step 2: Add Dependency** - -**1. Update Pubspec** - -To use this UI Kit in your Flutter project, you'll need to add the following dependency to the dependencies section of your `pubspec.yaml` file: +--- -```yaml pubspec.yaml -dependencies: - flutter: - sdk: flutter - - cometchat_chat_uikit: ^5.2.10 - cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling -``` +## Step 2 — Install the UI Kit -**Final `pubspec.yaml` Example:** +Add to your `pubspec.yaml`: ```yaml pubspec.yaml -name: my_chat_app -description: "A Flutter chat application using CometChat UI Kit" - -publish_to: 'none' - -version: 1.0.0+1 - -environment: - sdk: '>=3.8.0 <4.0.0' - dependencies: flutter: sdk: flutter - cometchat_chat_uikit: ^5.2.10 - cometchat_calls_uikit: ^5.0.12 # Optional: Include if you're using Audio/Video Calling - cupertino_icons: ^1.0.8 - -dev_dependencies: - flutter_test: - sdk: flutter - - flutter_lints: ^4.0.0 - -flutter: - uses-material-design: true + cometchat_calls_uikit: ^5.0.12 # Optional: for voice/video calling ``` -After updating `pubspec.yaml`, run: +Then run: ```bash flutter pub get ``` -*** - -**2. Android App Setup** - -To ensure compatibility with the CometChat Calling UI Kit and its dependencies, your Flutter project must target a minimum SDK version of **24 or higher**. - -Update the `minSdkVersion` in your Android project configuration, located at `android/app/build.gradle`: +**Android Setup** — Update `android/app/build.gradle`: ```gradle build.gradle android { defaultConfig { - minSdk = 24 - // Other configurations... + minSdk = 24 // Required for calling } } ``` -*** - -**3. Update iOS Podfile** - -In your Podfile (located at `ios/Podfile`), update the minimum iOS version your project supports to 12.0: +**iOS Setup** — Update `ios/Podfile`: ```ruby Podfile platform :ios, '13.0' ``` -After updating, run: +Then run: ```bash -cd ios -pod install -cd .. -``` - -*** - -**4. Import CometChat UIKit** - -In your Dart code, import the CometChat UIKit package to access its features. Add the following import statement to your `main.dart` file: - - - -```dart main.dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional: Include if you're using Audio/Video Calling +cd ios && pod install && cd .. ``` - - - -*** - -### **Step 3: Initialize UI Kit** - -Before using any features from the CometChat UI Kit, initialize it with your app credentials. - - - -You must call `CometChatUIKit.init()` before rendering any UI Kit widgets or calling any SDK methods. Initialization must complete before login. - - -**1. Import & Configure UIKit Settings** +--- -You can store your app credentials (App ID, Auth Key, Region) in a dedicated configuration file and load them dynamically in your app. +## Step 3 — Initialize CometChat -**Example Configuration File:** +Create a constants file and initialize the UI Kit before anything else. - - -```dart cometchat_config.dart +```dart title="lib/cometchat_config.dart" class CometChatConfig { static const String appId = "APP_ID"; // Replace with your App ID - static const String region = "REGION"; // Replace with your App Region - static const String authKey = "AUTH_KEY"; // Replace with your Auth Key + static const String region = "REGION"; // Replace with your Region + static const String authKey = "AUTH_KEY"; // Replace with your Auth Key (dev only) } ``` - - -**Initialization Code:** - - - -```dart main.dart +```dart title="lib/main.dart" import 'package:flutter/material.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; // Optional import 'cometchat_config.dart'; -void main() { - runApp(const MyApp()); -} +void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @@ -277,334 +121,169 @@ class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), + title: 'CometChat Demo', + home: const InitializerScreen(), ); } } -class Home extends StatelessWidget { - const Home({super.key}); +class InitializerScreen extends StatelessWidget { + const InitializerScreen({super.key}); - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true + Future _initCometChat() async { + final settings = (UIKitSettingsBuilder() ..appId = CometChatConfig.appId ..region = CometChatConfig.region ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() // Replace with empty array to disable extensions - ..callingExtension = CometChatCallingExtension(); // Optional: Include if using Audio/Video Calling + ..subscriptionType = CometChatSubscriptionType.allUsers + ..autoEstablishSocketConnection = true + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension() // Optional + ).build(); - await CometChatUIKit.init( - uiKitSettings: settings.build(), - onSuccess: (successMessage) { - debugPrint('✅ CometChat Initialized'); - }, - onError: (error) { - debugPrint('❌ CometChat Initialization error: $error'); - }, - ); + await CometChatUIKit.init(uiKitSettings: settings); } @override Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { + return FutureBuilder( + future: _initCometChat(), + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), + body: Center(child: CircularProgressIndicator()), ); } - if (snap.hasError) { + if (snapshot.hasError) { return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), + body: Center(child: Text('Init failed: ${snapshot.error}')), ); } - return const LoginScreen(); // Navigate to your login screen + return const LoginScreen(); }, ); } } ``` - - - - - -Store your CometChat credentials in a config file to simplify environment management and avoid hardcoding sensitive information. - - - -**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. - +`init()` must resolve before you call `login()`. If you call `login()` before init completes, it will fail silently. -*** +--- + +## Step 4 — Login -### **Step 4: Login to UI Kit** +After init resolves, log the user in. For development, use one of the pre-created test UIDs: -Once the UI Kit is initialized, authenticate your user using the `login()` method. You'll receive a `User` object upon success. +`cometchat-uid-1` · `cometchat-uid-2` · `cometchat-uid-3` · `cometchat-uid-4` · `cometchat-uid-5` - - -```dart main.dart +```dart CometChatUIKit.login( - "cometchat-uid-1", // Replace with a valid UID + "cometchat-uid-1", onSuccess: (user) { - debugPrint('✅ CometChat LoggedIn success: ${user.name}'); - // Navigate to your chat screen + debugPrint('Login successful: ${user.name}'); + // Navigate to chat screen }, onError: (error) { - debugPrint('❌ CometChat LoggedIn error: $error'); + debugPrint('Login failed: $error'); }, ); ``` - - - -**Test Users:** - -You can test using any of the following pre-generated users: - -* `cometchat-uid-1` -* `cometchat-uid-2` -* `cometchat-uid-3` -* `cometchat-uid-4` -* `cometchat-uid-5` - - - -For more information, refer to the documentation on [Init](/ui-kit/flutter/methods#init) and [Login](/ui-kit/flutter/methods#login-using-auth-key). - - - -**Example: Initialization and Login Combined** - - - -```dart main.dart -import 'package:flutter/material.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; -import 'cometchat_config.dart'; - -void main() => runApp(const MyApp()); - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'CometChat UI Kit', - theme: ThemeData( - colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), - useMaterial3: true, - ), - home: const Home(), - ); - } -} - -class Home extends StatelessWidget { - const Home({super.key}); - - Future _initializeAndLogin() async { - final settings = UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..appId = CometChatConfig.appId - ..region = CometChatConfig.region - ..authKey = CometChatConfig.authKey - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() - ..callingExtension = CometChatCallingExtension(); - - await CometChatUIKit.init(uiKitSettings: settings.build()); - await CometChatUIKit.login( - 'cometchat-uid-1', - onSuccess: (_) => debugPrint('✅ Login Successful'), - onError: (err) => throw Exception('Login Failed: $err'), - ); - } - @override - Widget build(BuildContext context) { - return FutureBuilder( - future: _initializeAndLogin(), - builder: (ctx, snap) { - if (snap.connectionState != ConnectionState.done) { - return const Scaffold( - body: SafeArea( - child: Center(child: CircularProgressIndicator()), - ), - ); - } - if (snap.hasError) { - return Scaffold( - body: SafeArea( - child: Center( - child: Text( - 'Error starting app:\n${snap.error}', - textAlign: TextAlign.center, - ), - ), - ), - ); - } - return const ConversationsPage(); // Your main chat screen - }, - ); - } -} -``` - - +Key points: +- `getLoggedInUser()` checks for an existing session so you don't re-login unnecessarily. +- Widgets must not render until login resolves — use a state flag to gate rendering. - -Extract credentials into a separate file (`cometchat_config.dart`) for better maintainability. - +For production, use `loginWithAuthToken()` instead of Auth Key. Generate tokens server-side via the REST API. -*** - -### **Step 5: Choose a Chat Experience** - -Integrate a conversation view that suits your application's **UX requirements**. Below are the available options: +--- -*** +## Step 5 — Choose a Chat Experience -### **1️⃣ Conversation List + Message View** +Integrate a conversation view that suits your app's UX. Each option below includes a step-by-step guide. -**Best for:** Flutter apps that need a **smooth, stack-based navigation** between conversations and messages. +### Conversation List + Message View -**Highlights:** +Two-panel layout — conversation list with navigation to messages. Think WhatsApp or Telegram. -* **Compact Layout** – Uses `Navigator.push()` for mobile-first navigation -* **One-to-One & Group Chats** – Built-in support for private and group conversations -* **Real-Time Messaging** – Message list and view auto-refresh with CometChat events -* **State Persistence** – Session-aware updates across screens and app restarts -* **Mobile-First UI** – Optimized widgets that adapt to different screen sizes -* **Extremely Customizable** – Modify styles, themes, and components easily +- Stack-based navigation with `Navigator.push()` +- Switch between one-to-one and group conversations +- Real-time updates and message sync across sessions -**Use When:** - -* You want a **clean navigation experience** for multiple chat sessions -* Your Flutter app supports **both direct and group messaging** -* You prefer a **stack-based routing approach** using `Navigator` + + Step-by-step guide to build this layout + -[Integrate Conversation List + Message View](./flutter-conversation) - -*** - -### **2️⃣ One-to-One / Group Chat** +--- -**Best for:** When a user lands **directly into a chat screen**, bypassing the conversation list. +### One-to-One / Group Chat -**Highlights:** +Single chat window — no conversation list. Good for support chat, embedded widgets, or focused messaging. -* **Single Screen Chat** – Use `CometChatMessageList` widget with preselected user/group -* **No Conversation List** – Start with just the message screen -* **Ideal for support & contextual chat** – Ticket-based or user-to-agent communication -* **Simplified Routing** – Pass user/group as route argument -* **Real-Time Communication** – Auto-updates messages and statuses +- Dedicated chat window for one-on-one or group messaging +- No conversation list — users go directly into the chat +- Ideal for support chat or contextual messaging -**Use When:** - -* Your chat starts **from a specific user or group ID** -* You want a **clean, focused chat interface** -* Use case involves **support, onboarding, or one-time messages** - -[Integrate One-to-One / Group Chat](./flutter-one-to-one-chat) + + Step-by-step guide to build this layout + -*** - -### **3️⃣ Tab-Based Messaging UI (All-in-One)** +--- -**Best for:** Flutter apps needing a **multi-tab experience** to access Chat, Users, Calls, and Settings. +### Tab-Based Chat -**Highlights:** +Tabbed navigation — Chat, Call Logs, Users, Groups in separate tabs. Good for full-featured apps. -* **Tab Navigation** – Use `BottomNavigationBar` to switch between core features -* **Independent Screens** – Chats, Calls, Users, and Settings in dedicated widgets -* **No Sidebar** – True mobile layout using bottom tabs, ideal for smaller devices -* **Scalable** – Add new tabs like Profile, Notifications, or Help later -* **Seamless UX** – Syncs chat state across tabs with minimal boilerplate +- `BottomNavigationBar` with independent screens +- Unified experience for conversations, call history, and contacts +- Scales well for adding future features -**Use When:** - -* You need a **full-featured chat solution** in one UI -* Your users require **structured navigation** between modules -* Use cases like **support apps, business messengers, or social platforms** - -[Integrate Tab-Based Chat](./flutter-tab-based-chat) - -*** + + Step-by-step guide to build this layout + -## **Build Your Own Chat Experience** - -**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app's design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. - -**Recommended for:** +--- -* Apps that require **a fully customized chat experience** -* Developers who want to **extend functionalities and modify UI components** -* Businesses integrating chat seamlessly into **existing platforms** +## Build Your Own Chat Experience -**Key Areas to Explore:** +Need full control over the UI? Use individual widgets, customize themes, and wire up your own layouts. -* **[Flutter Sample App](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app)** – Fully functional sample applications to accelerate your development -* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities -* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design -* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding -* **[Build Your Own UI](/sdk/flutter/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience +- [Sample App](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) — Working reference app to compare against +- [Components](/ui-kit/flutter/components-overview) — All prebuilt UI widgets with props and customization options +- [Core Features](/ui-kit/flutter/core-features) — Messaging, real-time updates, and other capabilities +- [Theming](/ui-kit/flutter/theme-introduction) — Colors, fonts, dark mode, and custom styling +- [Build Your Own UI](/sdk/flutter/overview) — Skip the UI Kit entirely and build on the raw SDK -*** +--- -## **Next Steps** +## Next Steps - - Two-panel layout with conversation list and message view + + Browse all prebuilt UI widgets - - Direct messaging interface for focused conversations + + Customize colors, fonts, and styles - - Multi-tab experience with chats, calls, users, and groups + + Chat features included out of the box - - Adjust colors, fonts, and styles to match your brand + + Init, login, and other SDK methods - -*** diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index 84839787b..e1391ba86 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -1,219 +1,77 @@ --- -title: "CometChat UI Kit For Flutter" +title: "Flutter UI Kit" sidebarTitle: "Overview" -description: "Prebuilt Flutter widgets for chat, calling, and messaging with modular, customizable components for iOS and Android" +description: "Prebuilt Flutter widgets for chat, voice, and video calling. Works on iOS and Android." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -// Install -flutter pub add cometchat_chat_uikit +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` v5.2.x | +| Calling | Optional — `cometchat_calls_uikit` | +| Platforms | iOS 13.0+, Android API 21+ | +| Flutter | 3.0+ recommended | +| Localization | Built-in support | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) | -// Initialize (run once at app start) -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "YOUR_APP_ID" - ..region = "YOUR_REGION" - ..subscriptionType = CometChatSubscriptionType.allUsers -).build(); -CometChatUIKit.init(uiKitSettings: uiKitSettings); + -// Login -CometChatUIKit.login("UID"); - -// Show conversations -CometChatConversations() - -// Show messages -CometChatMessageList(user: user) // or group: group -``` - -**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 - - -The **CometChat UI Kit** for Flutter is a powerful solution designed to seamlessly integrate chat functionality into applications. It provides a robust set of **prebuilt UI widgets** that are **modular, customizable, and highly scalable**, allowing developers to accelerate their development process with minimal effort. - -*** - -## **Why Choose CometChat UI Kit?** - -* **Rapid Integration** – Prebuilt UI widgets for faster deployment. -* **Customizable & Flexible** – Modify the UI to align with your brand's identity. -* **Cross-Platform Compatibility** – Works seamlessly across iOS and Android platforms. -* **Scalable & Reliable** – Built on CometChat's **robust chat infrastructure** for enterprise-grade performance. - -*** - -## **User Interface Preview** +The CometChat Flutter UI Kit provides prebuilt, customizable widgets for adding chat, voice, and video calling to any Flutter app. Each widget handles its own data fetching, real-time listeners, and state — you just drop them into your layout. -*** - -## **Integration** - -### **UI Components (Assemble It Yourself)** +--- -A collection of individual widgets—like conversation lists, message lists, message composer, etc.—each with built-in chat logic so you can customize every element. +## Get Started - + -**How It Works** - -* Import the widgets you need from our UI Kits. -* Arrange them in your desired layout, applying styling or customization as needed. -* You don't need to rewrite the SDK calls yourself—each widget already integrates with CometChat logic. - -**Why It's Great** - -* **Flexible Design** – You control the final UI arrangement. -* **No Extra Overhead** – Implement only the features you need. -* **Modular** – Use exactly what you want, when you want. - -[**Go to Flutter UI Docs**](/ui-kit/flutter/getting-started) - -*** - -## **Before Getting Started** - -Before you begin, it's essential to grasp the fundamental concepts and features offered by CometChat's APIs, SDK, and UI Kit. You can find detailed information in the [Key Concepts](/fundamentals/key-concepts) documentation. - -You can start building a modern messaging experience in your app by installing the new UI Kit. This developer kit is an add-on feature to CometChat Flutter SDK so installing it will also install the core Chat SDK. - -To begin, please follow the [Getting Started](/ui-kit/flutter/getting-started) guide. - -*** - -## **Key Features** - -### **Comprehensive Widget Library** - -The UI Kit includes a complete set of widgets for building chat experiences: - -* **CometChatConversations** – Display recent conversations with users and groups -* **CometChatMessageList** – Full-featured messaging interface with real-time updates -* **CometChatMessageComposer** – Input field for sending text, media, and attachments -* **CometChatMessageHeader** – Conversation header with user/group info and actions -* **CometChatUsers** – Browse and search users -* **CometChatGroups** – Manage and join groups -* **CometChatGroupMembers** – View and manage group participants -* **Calling Components** – Voice and video calling widgets - -### **Built-in Chat Logic** - -Each widget comes with integrated CometChat SDK functionality: - -* Real-time message delivery and updates -* Typing indicators and read receipts -* User presence and status -* Message reactions and threading -* File and media sharing -* Push notifications support - -### **Extensive Customization** - -Tailor the UI to match your brand: - -* **Theming** – Customize colors, fonts, and spacing -* **Styling** – Override default styles for any component -* **Templates** – Create custom message bubble layouts -* **Formatters** – Add mentions, shortcuts, and URL previews -* **Configurations** – Control feature availability and behavior - -*** - -## **Architecture** - -The CometChat UI Kit for Flutter is built on top of the [CometChat Flutter SDK](/sdk/flutter/overview) and follows a modular architecture: - -``` -Your Flutter App - ↓ -CometChat UI Kit (Widgets) - ↓ -CometChat Flutter SDK (Core Chat Logic) - ↓ -CometChat Platform -``` - -This layered approach means: - -* **Widgets handle UI** – Rendering, user interactions, animations -* **SDK handles logic** – Message delivery, real-time events, data management -* **Platform handles infrastructure** – Scalability, reliability, security - -*** - -## **Supported Platforms** - -The Flutter UI Kit works seamlessly across: - -* **iOS** – iPhone and iPad (iOS 13.0+) -* **Android** – Phones and tablets (API level 21+) + + Install, initialize, and build your first chat screen + -*** +--- -## **Next Steps** +## Explore - - Install the UI Kit and build your first chat screen + + Browse all prebuilt UI widgets - - Understand CometChat's core concepts and terminology + + Chat, calling, AI, and extensions - - Explore all available widgets and their capabilities + + Colors, fonts, dark mode, and custom styling - - Customize colors, fonts, and styles to match your brand + + Understand CometChat's core concepts -*** - -## **Helpful Resources** - -Explore these essential resources to gain a deeper understanding of **CometChat UI Kits** and streamline your integration process. - - - - -Fully functional sample applications to accelerate your development. - -View on GitHub - - - - - -Access the complete UI Kit source code on GitHub. - -View on GitHub - - - - - -UI design resources for customization and prototyping. +--- -View on Figma +## Resources - + + + Working reference app + + + Full UI Kit source on GitHub + + + Design resources and prototyping + + + Open a support ticket + + + Developer community forum + - -*** - -## **Need Help?** - -If you need assistance, check out: - -* 💬 [Developer Community](http://community.cometchat.com/) -* ❓ [Support Portal](https://help.cometchat.com/hc/en-us/requests/new) From edebad31e0aaf37d003ab008ce43ab745d67d39a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 13:39:08 +0530 Subject: [PATCH 031/106] Update color-resources.mdx --- ui-kit/flutter/color-resources.mdx | 267 ++++++++++++++++++----------- 1 file changed, 169 insertions(+), 98 deletions(-) diff --git a/ui-kit/flutter/color-resources.mdx b/ui-kit/flutter/color-resources.mdx index 9d9a8550d..5ac72fe51 100644 --- a/ui-kit/flutter/color-resources.mdx +++ b/ui-kit/flutter/color-resources.mdx @@ -1,140 +1,211 @@ --- title: "Color Resources" +sidebarTitle: "Color Resources" +description: "Complete reference for CometChatColorPalette tokens in Flutter UI Kit." --- -## Introducing CometChatColorPalette: + -### Your Theme Customization Toolbox! +| Field | Value | +| --- | --- | +| Class | `CometChatColorPalette` | +| Usage | `ThemeData(extensions: [CometChatColorPalette(...)])` | +| Categories | Primary, Neutral, Alert, Text, Icon, Border, Background, Button, Shimmer | +| Light mode | Use light color values | +| Dark mode | Use dark color values | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/theme/colors) | -Ever wanted to personalize your app's entire look and feel with just a few lines of code? Introducing the `CometChatColorPalette` class! This powerful tool, designed for the V5 CometChat Flutter UI Kit, allows you to effortlessly change the colors used throughout your app. + -Think of it like a giant paintbrush for your app's theme. You can set the primary color, neutral tones, and even specific colors for alerts, backgrounds, text, borders, and icons. +`CometChatColorPalette` controls all colors in the UI Kit. Apply it via `ThemeData.extensions`. -Here's a breakdown of what you can customize: - -* **Primary Colors:** Define the main color scheme of your app. -* **Neutral Colors:** Create a balanced base for your app's visuals. -* **Alert Colors:** Set unique colors for informative, warning, success, and error messages. -* **Background Colors:** Choose the background shades for different areas of your app. -* **Text Colors:** Control the color of text elements for optimal readability and aesthetics. -* **Border Colors:** Set the color of borders for elements like buttons and cards. -* **Icon Colors:** Customize the colors of app icons for a cohesive look. -* **Button Colors:** Choose the background and text color of buttons for clear action prompts. -* **Shimmer Colors:** Define the colors used in loading animations for user feedback. +--- -By simply creating a `CometChatColorPalette` object and assigning it to the `extensions` property of your `ThemeData`, you can instantly transform your app's appearance. +## Complete Token Reference + +### Primary Colors + +| Token | Description | +| --- | --- | +| `primary` | Main accent color | +| `extendedPrimary50` | 96% lighter (light) / 80% darker (dark) | +| `extendedPrimary100` | 88% lighter (light) / 72% darker (dark) | +| `extendedPrimary200` | 77% lighter (light) / 64% darker (dark) | +| `extendedPrimary300` | 66% lighter (light) / 56% darker (dark) | +| `extendedPrimary400` | 55% lighter (light) / 48% darker (dark) | +| `extendedPrimary500` | 44% lighter (light) / 40% darker (dark) | +| `extendedPrimary600` | 33% lighter (light) / 32% darker (dark) | +| `extendedPrimary700` | 22% lighter (light) / 24% darker (dark) | +| `extendedPrimary800` | 11% lighter (light) / 16% darker (dark) | +| `extendedPrimary900` | 11% lighter (light) / 8% darker (dark) | + +### Neutral Colors + +| Token | Description | +| --- | --- | +| `neutral50` - `neutral900` | Surface and background shades (50, 100, 200, 300, 400, 500, 600, 700, 800, 900) | + +### Alert Colors + +| Token | Description | +| --- | --- | +| `info` | Information indicator | +| `warning` | Warning indicator | +| `error` | Error indicator | +| `success` | Success indicator | +| `error100` | Light/dark mode error shade | + +### Text Colors + +| Token | Description | +| --- | --- | +| `textPrimary` | Primary text | +| `textSecondary` | Secondary text | +| `textTertiary` | Tertiary text | +| `textDisabled` | Disabled text | +| `textWhite` | White text | +| `textHighlight` | Highlighted text | + +### Icon Colors + +| Token | Description | +| --- | --- | +| `iconPrimary` | Primary icon | +| `iconSecondary` | Secondary icon | +| `iconTertiary` | Tertiary icon | +| `iconWhite` | White icon | +| `iconHighlight` | Highlighted icon | + +### Border Colors + +| Token | Description | +| --- | --- | +| `borderLight` | Light border | +| `borderDefault` | Default border | +| `borderDark` | Dark border | +| `borderHighlight` | Highlighted border | + +### Background Colors + +| Token | Description | +| --- | --- | +| `background1` | Primary background | +| `background2` | Secondary background | +| `background3` | Tertiary background | +| `background4` | Quaternary background | + +### Button Colors + +| Token | Description | +| --- | --- | +| `buttonBackground` | Primary button background | +| `secondaryButtonBackground` | Secondary button background | +| `buttonIconColor` | Primary button icon | +| `buttonText` | Primary button text | +| `secondaryButtonIcon` | Secondary button icon | +| `secondaryButtonText` | Secondary button text | + +### Other + +| Token | Description | +| --- | --- | +| `shimmerBackground` | Shimmer effect background | +| `shimmerGradient` | Shimmer effect gradient | +| `messageSeen` | Read receipt indicator | +| `white` | White color | +| `black` | Black color | +| `transparent` | Transparent color | -### Light mode +--- -Achieve a vibrant and clean aesthetic with colors optimized for light backgrounds. The CometChatColorPalette offers shades and tints designed to ensure readability and contrast in bright environments. +## Light Mode - - ```dart ThemeData( - extensions: [ - CometChatColorPalette( - textSecondary: Color(0xFF727272), - background1: Color(0xFFFFFFFF), - textPrimary: Color(0xFF141414), - borderLight: Color(0xFFF5F5F5), - borderDark: Color(0xFFDCDCDC), - iconSecondary: Color(0xFFA1A1A1), - success: Color(0xFF09C26F), - iconHighlight: Color(0xFF6852D6), - extendedPrimary500: Color(0xFFAA9EE8), - warning: Color(0xFFFAAB00), - messageSeen: Color(0xFF56E8A7), - neutral900: Color(0xFF141414), - neutral600: Color(0xFF727272), - neutral300: Color(0xFFE8E8E8), - primary: Color(0xFF6852D6) - ) - ] + extensions: [ + CometChatColorPalette( + primary: Color(0xFF6852D6), + textPrimary: Color(0xFF141414), + textSecondary: Color(0xFF727272), + background1: Color(0xFFFFFFFF), + borderLight: Color(0xFFF5F5F5), + borderDark: Color(0xFFDCDCDC), + iconSecondary: Color(0xFFA1A1A1), + iconHighlight: Color(0xFF6852D6), + success: Color(0xFF09C26F), + warning: Color(0xFFFAAB00), + extendedPrimary500: Color(0xFFAA9EE8), + messageSeen: Color(0xFF56E8A7), + neutral300: Color(0xFFE8E8E8), + neutral600: Color(0xFF727272), + neutral900: Color(0xFF141414), + ), + ], ) ``` - - - - -### Dark mode +--- -Provide a modern and eye-friendly experience with a palette tailored for darker themes, enhancing visual comfort and reducing glare during nighttime use. +## Dark Mode - - ```dart ThemeData( - extensions: [ - CometChatColorPalette( - textSecondary: Color(0xFF989898), - background1: Color(0xFF1A1A1A), - textPrimary: Color(0xFFFFFFFF), - borderLight: Color(0xFF272727), - iconSecondary: Color(0xFF858585), - success: Color(0xFF0B9F5D), - iconHighlight: Color(0xFF6852D6), - extendedPrimary500: Color(0xFF3E3180), - warning: Color(0xFFD08D04), - messageSeen: Color(0xFF56E8A7), - neutral900: Color(0xFFFFFFFF), - neutral600: Color(0xFF989898), - neutral300: Color(0xFF383838), - primary: Color(0xFF6852D6) - ) - ] + extensions: [ + CometChatColorPalette( + primary: Color(0xFF6852D6), + textPrimary: Color(0xFFFFFFFF), + textSecondary: Color(0xFF989898), + background1: Color(0xFF1A1A1A), + borderLight: Color(0xFF272727), + iconSecondary: Color(0xFF858585), + iconHighlight: Color(0xFF6852D6), + success: Color(0xFF0B9F5D), + warning: Color(0xFFD08D04), + extendedPrimary500: Color(0xFF3E3180), + messageSeen: Color(0xFF56E8A7), + neutral300: Color(0xFF383838), + neutral600: Color(0xFF989898), + neutral900: Color(0xFFFFFFFF), + ), + ], ) ``` - - - - -### Custom Colors +--- -Personalize your application's appearance by defining unique color schemes using CometChatColorPalette, aligning the chat interface with specific branding or creative preferences. +## Custom Brand Colors - - ```dart ThemeData( - extensions: [ - CometChatColorPalette( - textSecondary: Color(0xFF727272), - background1: Color(0xFFFFFFFF), - textPrimary: Color(0xFF141414), - borderLight: Color(0xFFF5F5F5), - borderDark: Color(0xFFDCDCDC), - iconSecondary: Color(0xFFA1A1A1), - success: Color(0xFF09C26F), - iconHighlight: Color(0xFFF76808), - extendedPrimary500: Color(0xFFFBAA75), - warning: Color(0xFFFAAB00), - messageSeen: Color(0xFF56E8A7), - neutral900: Color(0xFF141414), - neutral600: Color(0xFF727272), - neutral300: Color(0xFFE8E8E8), - primary: Color(0xFFF76808) - ) - ] + extensions: [ + CometChatColorPalette( + primary: Color(0xFFF76808), + iconHighlight: Color(0xFFF76808), + extendedPrimary500: Color(0xFFFBAA75), + textPrimary: Color(0xFF141414), + textSecondary: Color(0xFF727272), + background1: Color(0xFFFFFFFF), + borderLight: Color(0xFFF5F5F5), + borderDark: Color(0xFFDCDCDC), + success: Color(0xFF09C26F), + warning: Color(0xFFFAAB00), + messageSeen: Color(0xFF56E8A7), + neutral300: Color(0xFFE8E8E8), + neutral600: Color(0xFF727272), + neutral900: Color(0xFF141414), + ), + ], ) ``` - - - - - -Ready to unleash your inner designer? Explore the `CometChatColorPalette` and create a stunning and personalized user experience! From d015f89ec016d83e862adfe0bc1120e2d1446253 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 14:01:38 +0530 Subject: [PATCH 032/106] Updates docs for { "group": "Theming", "pages": [ "ui-kit/flutter/theme-introduction", "ui-kit/flutter/color-resources", "ui-kit/flutter/component-styling", "ui-kit/flutter/message-bubble-styling", "ui-kit/flutter/localize", "ui-kit/flutter/sound-manager" ] }, --- ui-kit/flutter/component-styling.mdx | 626 +++------------- ui-kit/flutter/localize.mdx | 430 +++-------- ui-kit/flutter/message-bubble-styling.mdx | 827 +++++----------------- ui-kit/flutter/sound-manager.mdx | 126 ++-- ui-kit/flutter/theme-introduction.mdx | 208 +++--- 5 files changed, 586 insertions(+), 1631 deletions(-) diff --git a/ui-kit/flutter/component-styling.mdx b/ui-kit/flutter/component-styling.mdx index 312a7ce36..29eb4bf94 100644 --- a/ui-kit/flutter/component-styling.mdx +++ b/ui-kit/flutter/component-styling.mdx @@ -1,670 +1,248 @@ --- -title: "Elevate Your Chat Experience: Mastering Component Styling In CometChat" +title: "Component Styling" sidebarTitle: "Component Styling" +description: "Style individual CometChat Flutter UI Kit components using ThemeExtensions." --- -## Unlock the Power of Customization + -Tired of generic chat interfaces? With CometChat's powerful component styling capabilities, you can now create truly unique and visually stunning chat experiences. +| Field | Value | +| --- | --- | +| Method | Add component style classes to `ThemeData.extensions` | +| Components | Conversations, MessageList, MessageComposer, MessageHeader, Users, Groups, GroupMembers | +| Base components | Avatar, Badge, StatusIndicator, Receipts, Reactions, MediaRecorder | +| Pattern | `CometChatStyle` classes | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) | -## Transform Your Chat with Component Styling + -Component Styling empowers you to fine-tune every aspect of your chat UI, from the subtle nuances of message bubbles to the bold impact of global theme changes. Customize the following key components to match your brand's identity and user preferences: +Style individual components by adding their style classes to `ThemeData.extensions`. -## Components +--- -### Conversation +## Main Components -Control the overall layout and behavior of conversations. +### Conversations - - ```dart ThemeData( - fontFamily: 'Times New Roman', - extensions: [ - CometChatConversationsStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75) - ), - badgeStyle: CometChatBadgeStyle( - backgroundColor: Color(0xFFF76808) - ) - ) - ] + extensions: [ + CometChatConversationsStyle( + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + badgeStyle: CometChatBadgeStyle( + backgroundColor: Color(0xFFF76808), + ), + ), + ], ) ``` - - - - ### Message List -Customize the appearance of message lists, including bubble styles, timestamps, and reactions. - - - ```dart ThemeData( - extensions: [ - CometChatMessageListStyle( - backgroundColor: Color(0xFFFEEDE1), - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) - ) - ) - ] + extensions: [ + CometChatMessageListStyle( + backgroundColor: Color(0xFFFEEDE1), + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), + ), + ], ) ``` - - - - ### Message Composer -Tailor the input field and send button to suit your design. - - - ```dart ThemeData( - extensions: [ - CometChatMessageComposerStyle( - sendButtonIconBackgroundColor: Color(0xFFF76808), - secondaryButtonIconColor: Color(0xFFF76808), - auxiliaryButtonIconColor: Color(0xFFF76808) - ) - ] + extensions: [ + CometChatMessageComposerStyle( + sendButtonIconBackgroundColor: Color(0xFFF76808), + secondaryButtonIconColor: Color(0xFFF76808), + auxiliaryButtonIconColor: Color(0xFFF76808), + ), + ], ) ``` - - - - ### Message Header -Customize the header displayed at the top of each conversation. - - - ```dart ThemeData( - extensions: [ - CometChatMessageHeaderStyle( - avatarStyle: CometChatAvatarStyle( - backgroundColor: Color(0xFFFBAA75), - borderRadius: BorderRadius.circular(6.67), - ), - callButtonsStyle: CometChatCallButtonsStyle( - voiceCallIconColor: Color(0xFFF76808), - videoCallIconColor: Color(0xFFF76808), - ), - ) - ] + extensions: [ + CometChatMessageHeaderStyle( + avatarStyle: CometChatAvatarStyle( + backgroundColor: Color(0xFFFBAA75), + borderRadius: BorderRadius.circular(6.67), + ), + callButtonsStyle: CometChatCallButtonsStyle( + voiceCallIconColor: Color(0xFFF76808), + videoCallIconColor: Color(0xFFF76808), + ), + ), + ], ) ``` - - - - ### Users -Style user profiles and lists. - - - ```dart ThemeData( - extensions: [ - CometChatUsersStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleTextColor: Color(0xFFF76808), - separatorColor: Color(0xFFF76808), - backgroundColor: Color(0xFFFFF9F5) - ) - ] + extensions: [ + CometChatUsersStyle( + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + titleTextColor: Color(0xFFF76808), + separatorColor: Color(0xFFF76808), + backgroundColor: Color(0xFFFFF9F5), + ), + ], ) ``` - - - - ### Groups -Customize the appearance of group chats and group information. - - - -```dart -ThemeData( - extensions: [ - CometChatGroupsStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleTextColor: Color(0xFFF76808), - separatorColor: Color(0xFFF76808), - backgroundColor: Color(0xFFFFF9F5) - ) - ] -) -``` - - - - - -### Group Members - -Elevate your group chat experience with customizable member list styles. - - - - - - - ```dart ThemeData( - extensions: [ - CometChatGroupMembersStyle( - avatarStyle: CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ), - titleStyle: TextStyle(color: Color(0xFFF76808)), - separatorColor: Color(0xFFF76808), - ownerMemberScopeBackgroundColor: Color(0xFFF76808), - adminMemberScopeBackgroundColor: Color(0xFFFEEDE1), - adminMemberScopeBorder: Border.all(color: Color(0xFFF76808)), - adminMemberScopeTextColor: Color(0xFFF76808), - moderatorMemberScopeBackgroundColor: Color(0xFFFEEDE1), - moderatorMemberScopeTextColor: Color(0xFFF76808), - backIconColor: Color(0xFFF76808), - ) - ] -) -``` - - - - - -### AI Assistant Chat History - -The `CometChatAIAssistantChatHistory` component displays the history of interactions with an AI assistant. It provides a seamless way to view past conversations, ensuring users can easily reference previous AI responses. - - - - - - - -```dart -final ccColor = CometChatThemeHelper.getColorPalette(context); -CometChatAIAssistantChatHistory( - user: user, // A user or group object is required to launch this widget. - style: CometChatAIAssistantChatHistoryStyle( - backgroundColor: const Color(0xFFFFFAF6), - headerBackgroundColor: const Color(0xFFFFFAF6), - headerTitleTextColor: ccColor.textPrimary, - headerTitleTextStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts - ), - newChatIconColor: ccColor.iconSecondary, - newChatTextColor: ccColor.textPrimary, - newChaTitleStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts - ), - dateSeparatorStyle: CometChatDateStyle( - textStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts + extensions: [ + CometChatGroupsStyle( + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), ), - textColor: ccColor.textTertiary, - backgroundColor: const Color(0xFFFFFAF6), - ), - itemTextStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts + titleTextColor: Color(0xFFF76808), + separatorColor: Color(0xFFF76808), + backgroundColor: Color(0xFFFFF9F5), ), - itemTextColor: ccColor.textPrimary, - ), -), + ], +) ``` - - - +--- ## Base Components ### Avatar -Personalize user avatars with different shapes, sizes, and borders. - - - -```dart -ThemeData( - extensions: [ - CometChatAvatarStyle( - borderRadius: BorderRadius.circular(8), - backgroundColor: Color(0xFFFBAA75), - ) - ] -) -``` - - - - - -### Status Indicator - -Control the appearance of online/offline indicators. - - - - - - - ```dart -ThemeData( - extensions: [ - CometChatStatusIndicatorStyle( - backgroundColor: Color(0xFFFFAB00), - borderRadius: BorderRadius.circular(2), - ) - ] +CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), ) ``` - - - - ### Badge -Customize badges for unread messages and notifications. - - - ```dart -ThemeData( - extensions: [ - CometChatBadgeStyle( - borderRadius: BorderRadius.circular(4), - backgroundColor: Color(0xFFF44649), - ), - ] +CometChatBadgeStyle( + borderRadius: BorderRadius.circular(4), + backgroundColor: Color(0xFFF44649), ) ``` - - - - -### Date - -Format and style timestamps. - -### Receipts - -Customize the appearance of message receipts (e.g., "Seen," "Delivered"). +### Status Indicator - + - - ```dart -ThemeData( - extensions: [ - CometChatMessageReceiptStyle( - readIconColor: Color(0xFFFFAB00), - ) - ] +CometChatStatusIndicatorStyle( + backgroundColor: Color(0xFFFFAB00), + borderRadius: BorderRadius.circular(2), ) ``` - - - - -### Media Recorder - -Style the audio and video recording interfaces. +### Receipts - + - - ```dart -ThemeData( - extensions: [ - CometChatMediaRecorderStyle( - recordIndicatorBackgroundColor: Color(0xFFF44649), - recordIndicatorBorderRadius: BorderRadius.circular(20), - pauseButtonBorderRadius: BorderRadius.circular(8), - deleteButtonBorderRadius: BorderRadius.circular(8), - stopButtonBorderRadius: BorderRadius.circular(8), - ) - ] +CometChatMessageReceiptStyle( + readIconColor: Color(0xFFFFAB00), ) ``` - - - - -### Sticker Keyboard - -Customize the appearance of sticker keyboards. - ### Reactions -Style the appearance of reactions to messages. - - - -```dart -ThemeData( - extensions: [ - CometChatReactionsStyle( - borderRadius: BorderRadius.circular(8), - ) - ] -) -``` - - - - - -### Reaction List - -Control the style of reactions displayed on messages. - - - - - - - ```dart -ThemeData( - extensions: [ - CometChatReactionListStyle( - activeTabTextColor: Color(0xFFF76808), - activeTabIndicatorColor: Color(0xFFF76808), - ) - ] +CometChatReactionsStyle( + borderRadius: BorderRadius.circular(8), ) ``` - +--- - +## AI Components ### Conversation Starter -Tailor the initial message or prompt. - - - -```dart -ThemeData( - extensions: [ - CometChatAIConversationStarterStyle( - backgroundColor: Color(0xFFFEEDE1), - border: Border.all(color: Color(0xFFFBBB90)), - ) - ] -) -``` - - - - - -### Conversation Summary - -Customize the summary view of a conversation. - - - - - - - ```dart -ThemeData( - extensions: [ - CometChatAIConversationSummaryStyle( - backgroundColor: Color(0xFFFEEDE1), - titleStyle: TextStyle( - color: Color(0xFFF76808), - ), - ) - ] +CometChatAIConversationStarterStyle( + backgroundColor: Color(0xFFFEEDE1), + border: Border.all(color: Color(0xFFFBBB90)), ) ``` - - - - ### Smart Replies -Style the appearance of suggested replies. - - - ```dart -ThemeData( - extensions: [ - CometChatAISmartRepliesStyle( - backgroundColor: Color(0xFFFEEDE1), - titleStyle: TextStyle( - color: Color(0xFFF76808), - ), - itemBackgroundColor: Color(0xFFFFF9F5), - itemBorder: Border.all(color: Color(0xFFFBBB90)), - ) - ] +CometChatAISmartRepliesStyle( + backgroundColor: Color(0xFFFEEDE1), + titleStyle: TextStyle(color: Color(0xFFF76808)), + itemBackgroundColor: Color(0xFFFFF9F5), + itemBorder: Border.all(color: Color(0xFFFBBB90)), ) ``` - - - - - -### Message Information - -Customize the information displayed when tapping on a message. - - - - - - - -```dart -ThemeData( - fontFamily: "Times New Roman", - extensions: [ - CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) - ), - CometChatMessageInformationStyle( - backgroundHighLightColor: Color(0xFFFEEDE1), - messageReceiptStyle: CometChatMessageReceiptStyle( - readIconColor: Color(0xFFF76808) - ) - ), - ] - ) -``` - - - - - -### Message Option Sheet - -Style the options menu for individual messages. - - - - - - - -```dart -ThemeData( - extensions: [ - CometChatMessageOptionSheetStyle( - backgroundColor: Color(0xFFFEEDE1), - iconColor: Color(0xFFF76808), - ) - ] -) -``` - - - - - -### Attachment Option Sheet - -Customize the attachment options menu. - - - - - - - -```dart -ThemeData( - extensions: [ - CometChatAttachmentOptionSheetStyle( - backgroundColor: Color(0xFFFEEDE1), - iconColor: Color(0xFFF76808), - ) - ] -) -``` - - - - - -### AI Option Sheet - -Style the all-in-one options menu. - - - - - - - -```dart -ThemeData( - extensions: [ - CometChatAiOptionSheetStyle( - backgroundColor: Color(0xFFFFF9F5), - iconColor: Color(0xFFF76808) - ) - ] -) -``` - - - - - -### Mentions - -Customize the appearance of user and group mentions. - - - - - - - -```dart -ThemeData( - extensions: [ - CometChatMentionsStyle( - mentionSelfTextBackgroundColor: Color(0xFFF76808), - mentionTextBackgroundColor: Colors.white, - mentionTextColor: Colors.black, - mentionSelfTextColor: Colors.white, - ) - ] -) -``` - - - - diff --git a/ui-kit/flutter/localize.mdx b/ui-kit/flutter/localize.mdx index 3b8399004..5ae38bc1a 100644 --- a/ui-kit/flutter/localize.mdx +++ b/ui-kit/flutter/localize.mdx @@ -1,402 +1,184 @@ --- -title: "Localize" +title: "Localization" +sidebarTitle: "Localize" +description: "Configure multi-language localization and custom translations in CometChat Flutter UI Kit." --- -## Overview + -CometChat UI Kit provides language localization to adapt to the language of a specific country or region. The CometChatLocalize class allows you to detect the language of your users based on their browser or device settings, and set the language accordingly. +| Field | Value | +| --- | --- | +| Package | `cometchat_uikit_shared` | +| Import | `import 'package:cometchat_uikit_shared/l10n/translations.dart';` | +| Set language | Add `Locale('fr')` to `supportedLocales` | +| Delegates | `Translations.delegate`, `GlobalMaterialLocalizations.delegate`, etc. | +| Supported | 18 languages: ar, de, en, en-GB, es, fr, hi, hu, ja, ko, lt, ms, nl, pt, ru, sv, tr, zh | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/l10n) | -CometChatLocalize is a class that includes methods related to locale. Developers can use these methods to change the language of the UI Kit library. + -Presently, the UI Kit supports 19 languages for localization, which are: +`Translations` manages multi-language localization for the UI Kit. -* Arabic (ar) -* German (de) -* English (en, en-GB) -* Spanish (es) -* French (fr) -* Hindi(hi) -* Hungarian (hu) -* Japanese (ja) -* Korean\* (ko) -* Lithuanian(lt) -* Malay (ms) -* Dutch (nl) -* Portuguese (pt) -* Russian (ru) -* Swedish (sv) -* Turkish (tr) -* Chinese (zh, zh-TW) +--- -## Usage +## Supported Languages + +| Language | Code | +| --- | --- | +| Arabic | `ar` | +| German | `de` | +| English | `en` | +| English (UK) | `en-GB` | +| Spanish | `es` | +| French | `fr` | +| Hindi | `hi` | +| Hungarian | `hu` | +| Japanese | `ja` | +| Korean | `ko` | +| Lithuanian | `lt` | +| Malay | `ms` | +| Dutch | `nl` | +| Portuguese | `pt` | +| Russian | `ru` | +| Swedish | `sv` | +| Turkish | `tr` | +| Chinese | `zh` | -### Integration +--- -Add the following dependency in `pubspec.yaml` +## Setup - - -```dart +Add the dependency in `pubspec.yaml`: + +```yaml flutter_localizations: - sdk: flutter + sdk: flutter ``` - - - - -*** +Configure `MaterialApp`: -Update MaterialApp Localizations Delegates - - - ```dart -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; -import 'package:cometchat_uikit_shared/l10n/translations.dart' as cc; -import 'package:flutter/material.dart'; +import 'package:cometchat_uikit_shared/l10n/translations.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; -import 'guard_screen.dart'; - - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - // This widget is the root of your application. - @override - Widget build(BuildContext context) { - return MaterialApp( - supportedLocales: const [ - Locale('en'), - Locale('en', 'GB'), - Locale('ar'), - Locale('de'), - Locale('es'), - Locale('fr'), - Locale('hi'), - Locale('hu'), - Locale('ja'), - Locale('ko'), - Locale('lt'), - Locale('ms'), - Locale('nl'), - Locale('pt'), - Locale('ru'), - Locale('sv'), - Locale('tr'), - Locale('zh'), - Locale('zh', 'TW'), - ], - localizationsDelegates: const [ - cc.Translations.delegate, - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - theme: ThemeData( - appBarTheme: AppBarTheme( - scrolledUnderElevation: 0.0, - ), - ), - title: 'CometChat Flutter Sample App', - navigatorKey: CallNavigationContext.navigatorKey, - home: GuardScreen(), - debugShowCheckedModeBanner: false, - ); - } -} +MaterialApp( + supportedLocales: const [ + Locale('en'), + Locale('fr'), + Locale('es'), + Locale('de'), + // Add more as needed + ], + localizationsDelegates: Translations.localizationsDelegates, + home: MyApp(), +) ``` - - - - -*** +--- -You can also translate specific strings. For example: +## Get Translated Strings - - ```dart String translatedString = Translations.of(context).users; - -//Use it in a widget Text(translatedString); ``` - - - - -### Customizing UI Kit Translations for a Specific Language +--- -*** +## Custom Translations -To override a specific language's default translations in the CometChat UI Kit, you can create a custom localization class and delegate. The example below demonstrates how to override the English (en) language by customizing labels such as "chats" and "calls". This allows you to tailor the UI text to better fit your application's tone or branding requirements. +Override default translations by extending the language class: - - ```dart -// Import necessary Flutter and package dependencies -import 'dart:async'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart' as cc; +import 'package:cometchat_uikit_shared/l10n/translations.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:get/get.dart'; -import 'package:master_app/guard_screen.dart'; -import 'package:master_app/utils/page_manager.dart'; -import 'prefs/shared_preferences.dart'; - -// Main function - entry point of the Flutter application -Future main() async { - WidgetsFlutterBinding.ensureInitialized(); // Ensures bindings are initialized before runApp - SharedPreferencesClass.init(); // Initialize shared preferences - Get.put(PageManager()); // Register PageManager with GetX dependency injection - - runApp(const MyApp()); // Launch the app -} - -// Root widget of the application -class MyApp extends StatefulWidget { - const MyApp({super.key}); - - @override - State createState() => _MyAppState(); -} - -class _MyAppState extends State { - // Builds the MaterialApp with localization, theme, and navigation setup - @override - Widget build(BuildContext context) { - return MaterialApp( - // List of all supported locales - supportedLocales: const [ - Locale('en'), - Locale('en', 'GB'), - Locale('ar'), - Locale('de'), - Locale('es'), - Locale('fr'), - Locale('hi'), - Locale('hu'), - Locale('ja'), - Locale('ko'), - Locale('lt'), - Locale('ms'), - Locale('nl'), - Locale('pt'), - Locale('ru'), - Locale('sv'), - Locale('tr'), - Locale('zh'), - Locale('zh', 'TW'), - ], - - // Localization delegates required to load localized resources - localizationsDelegates: const [ - CustomEN.delegate, // Custom override for English localization - cc.Translations.delegate, // CometChat UI Kit translations - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - - // Application theme configuration - theme: ThemeData( - appBarTheme: AppBarTheme( - scrolledUnderElevation: 0.0, // No shadow when scrolling under the AppBar - ), - ), - - title: 'CometChat Flutter Sample App', // App title - navigatorKey: CallNavigationContext - .navigatorKey, // Navigator key for CometChat call handling - home: GuardScreen(), // Initial screen shown to the user - debugShowCheckedModeBanner: false, // Hides the debug banner - ); - } -} -// Custom English translation class overriding default CometChat translations class CustomEN extends TranslationsEn { - static const delegate = _CustomCometChatLocalizationsDelegate(); + static const delegate = _CustomLocalizationsDelegate(); @override - String get chats => "Overridden Chat"; // Custom string for "chats" + String get chats => "My Chats"; @override - String get calls => "Overridden Call"; // Custom string for "calls" + String get calls => "My Calls"; } -// Localization delegate to provide the CustomEN class for English -class _CustomCometChatLocalizationsDelegate - extends LocalizationsDelegate { - const _CustomCometChatLocalizationsDelegate(); +class _CustomLocalizationsDelegate extends LocalizationsDelegate { + const _CustomLocalizationsDelegate(); - // Only support English for this custom delegate @override bool isSupported(Locale locale) => locale.languageCode == 'en'; - // Load the custom English translations synchronously @override - Future load(Locale locale) => - SynchronousFuture(CustomEN()); + Future load(Locale locale) => SynchronousFuture(CustomEN()); - // No need to reload delegate on changes @override - bool shouldReload(_CustomCometChatLocalizationsDelegate old) => false; + bool shouldReload(_CustomLocalizationsDelegate old) => false; } ``` - +Then add to `MaterialApp`: - +```dart +localizationsDelegates: const [ + CustomEN.delegate, // Custom override first + ...Translations.localizationsDelegates, +], +``` -### Adding New Language Support in CometChat UI Kit +--- -*** +## Add New Language -This implementation demonstrates how to extend the CometChat Flutter UI Kit with custom localization support for the Telugu (te) language. By creating a custom translation class and registering it through a LocalizationsDelegate, developers can override or define translation strings such as "Chats" and "Calls" in Telugu. This approach enables personalized and region-specific user experiences beyond the default set of supported languages in the UI Kit. +Create a custom translation class for unsupported languages: - - ```dart -// Import Dart and Flutter dependencies -import 'dart:async'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart' as cc; +import 'package:cometchat_uikit_shared/l10n/translations.dart'; import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_localizations/flutter_localizations.dart'; -import 'package:get/get.dart'; -import 'package:master_app/guard_screen.dart'; -import 'package:master_app/utils/page_manager.dart'; -import 'prefs/shared_preferences.dart'; - -// Entry point of the Flutter application -Future main() async { - WidgetsFlutterBinding.ensureInitialized(); // Ensures Flutter engine is initialized - SharedPreferencesClass.init(); // Initialize shared preferences for app storage - Get.put(PageManager()); // Register PageManager using GetX dependency injection - - runApp(const MyApp()); // Launch the main app widget -} -// Main application widget -class MyApp extends StatefulWidget { - const MyApp({super.key}); +class TeluguTranslations extends Translations { + TeluguTranslations([super.locale = "te"]); + static const delegate = _TeluguDelegate(); @override - State createState() => _MyAppState(); -} + String get chats => "సందేశాలు"; -class _MyAppState extends State { - // Root of the application @override - Widget build(BuildContext context) { - return MaterialApp( - // Set the default locale to Telugu - locale: Locale('te'), - - // List of all supported locales including the new Telugu support - supportedLocales: const [ - Locale('en'), - Locale('en', 'GB'), - Locale('ar'), - Locale('de'), - Locale('es'), - Locale('fr'), - Locale('hi'), - Locale('hu'), - Locale('ja'), - Locale('ko'), - Locale('lt'), - Locale('ms'), - Locale('nl'), - Locale('pt'), - Locale('ru'), - Locale('sv'), - Locale('tr'), - Locale('zh'), - Locale('zh', 'TW'), - Locale('te'), // Newly added Telugu locale - ], - - // Localization delegates used to load translations - localizationsDelegates: const [ - MmCCLocalization.delegate, // Custom Telugu localization delegate - cc.Translations.delegate, // CometChat UI Kit default translations - GlobalMaterialLocalizations.delegate, // Flutter built-in material localization - GlobalWidgetsLocalizations.delegate, // Flutter built-in widget localization - GlobalCupertinoLocalizations.delegate, // Flutter built-in Cupertino localization - ], - - // Define app theme (e.g., AppBar style) - theme: ThemeData( - appBarTheme: AppBarTheme( - scrolledUnderElevation: 0.0, // Remove shadow when scrolling under AppBar - ), - ), - - title: 'CometChat Flutter Sample App', // App title - navigatorKey: CallNavigationContext.navigatorKey, // Navigator key for CometChat call handling - home: GuardScreen(), // Entry screen of the app - debugShowCheckedModeBanner: false, // Disable debug banner in release mode - ); - } + String get calls => "ఫోన్ కాల్స్"; + + // Override all required getters from Translations... } -// Custom localization delegate for Telugu language -class _NnCometChatLocalizationsDelegate - extends LocalizationsDelegate { - const _NnCometChatLocalizationsDelegate(); +class _TeluguDelegate extends LocalizationsDelegate { + const _TeluguDelegate(); - // Checks if the provided locale is supported (only 'te' in this case) @override bool isSupported(Locale locale) => locale.languageCode == 'te'; - // Load the custom Telugu translation class @override - Future load(Locale locale) => - SynchronousFuture(MmCCLocalization()); + Future load(Locale locale) => SynchronousFuture(TeluguTranslations()); - // Determines whether to reload the delegate (not needed here) @override - bool shouldReload(_NnCometChatLocalizationsDelegate old) => false; + bool shouldReload(_TeluguDelegate old) => false; } +``` -// NOTE: -// Only "chats" and "calls" have been overridden in this example. -// To fully localize the UI for the Telugu language, you should override -// all relevant strings provided by the CometChat UI Kit's Translations class. -// This ensures a consistent and complete user experience across the app. - -// Custom Telugu translation class for CometChat UI Kit -class MmCCLocalization extends cc.Translations { - MmCCLocalization([super.locale = "te"]); - - // Register the delegate for use in MaterialApp - static const delegate = _NnCometChatLocalizationsDelegate(); - - // Override specific UI Kit strings in Telugu - @override - String get chats => "సందేశాలు"; // Telugu for "Chats" +Then add to `MaterialApp`: - @override - String get calls => "ఫోన్ కాల్స్"; // Telugu for "Calls" - - // Note: Add more overrides here to fully localize the UI -} +```dart +localizationsDelegates: const [ + TeluguTranslations.delegate, // Custom language first + ...Translations.localizationsDelegates, +], +supportedLocales: const [ + Locale('te'), // Telugu + Locale('en'), + // Other locales... +], ``` - - - +--- -### DateTimeFormatter -By providing a custom implementation of the DateTimeFormatterCallback, you can globally configure how time and date values are displayed across all UI components in the CometChat UI Kit. This ensures consistent formatting for labels such as "Today", "Yesterday", "X minutes ago", and more, throughout the entire application. +## Date/Time Formatting -For more detailed information and the full reference for the DateTimeFormatterCallback methods, refer to the DateTimeFormatterCallback methods section in the [CometChatUIKit class](/ui-kit/flutter/methods#dateformatter) \ No newline at end of file +Customize date/time display globally via `DateTimeFormatterCallback`. See [CometChatUIKit Methods](/ui-kit/flutter/methods#dateformatter) for details. diff --git a/ui-kit/flutter/message-bubble-styling.mdx b/ui-kit/flutter/message-bubble-styling.mdx index c3e519d0e..4c928a04f 100644 --- a/ui-kit/flutter/message-bubble-styling.mdx +++ b/ui-kit/flutter/message-bubble-styling.mdx @@ -1,774 +1,297 @@ --- -title: "Customizing Message Bubbles" -sidebarTitle: "Message Bubble Styling" +title: "Message Bubble Styling" +sidebarTitle: "Message Bubbles" +description: "Customize incoming and outgoing message bubbles in CometChat Flutter UI Kit." --- -When building chat applications, customizing the look and feel of message bubbles is often a significant challenge. Developers frequently encounter difficulties when they need to modify specific design elements, such as background colors or styles for particular message types. This complexity is amplified by the wide range of message bubbles available in the **CometChat Flutter UI Kit**. + -To simplify this process, the CometChat UI Kit provides two specialized classes: **CometChatOutgoingMessageBubbleStyle** and **CometChatIncomingMessageBubbleStyle**. These classes are designed to give developers fine-grained control over the appearance of message bubbles for **sent** and **received** messages, respectively. Both classes extend the `ThemeExtension` class, allowing customizations to be seamlessly applied through global theming or by explicitly passing style objects. +| Field | Value | +| --- | --- | +| Outgoing | `CometChatOutgoingMessageBubbleStyle` | +| Incoming | `CometChatIncomingMessageBubbleStyle` | +| Usage | Add to `ThemeData.extensions` or pass to `CometChatMessageListStyle` | +| Bubble types | Text, Image, Video, Audio, File, Poll, Sticker, Voice Call, Video Call, Link Preview, Collaborative Document, Collaborative Whiteboard, Message Translation, Deleted, AI Assistant (incoming only) | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/models/extension_bubble_styles) | + + + +Customize message bubbles using `CometChatOutgoingMessageBubbleStyle` and `CometChatIncomingMessageBubbleStyle`. -## How These Classes Help - -### 1. Targeted Customization - -Developers can customize specific attributes of message bubbles, such as: - -* Background color - -* Border radius - -* Text style - -* Bubble-specific elements like reactions or avatars - -* Specialized bubbles for various message types, such as: - - * Audio bubbles - * File bubbles - * Collaborative bubbles - * Poll bubbles - * Deleted message bubbles - * Link preview bubbles - * Message translation bubbles - * Sticker bubbles - -This targeted approach eliminates the need to modify every bubble type when changes are required for just one. - -### 2. Unified Global Theming - -By leveraging the power of Flutter's global theming system: +--- -* You can define consistent styles across your application. -* Alternatively, you can apply custom styles dynamically by passing `CometChatOutgoingMessageBubbleStyle` and `CometChatIncomingMessageBubbleStyle` objects to the `outgoingMessageBubbleStyle` and `incomingMessageBubbleStyle` properties of the **CometChatMessageListStyle** class. +## Global Theming - - - +Apply bubble styles globally via `ThemeData.extensions`: - - ```dart MaterialApp( - title: 'Your app', - theme: ThemeData( - extensions: [ - CometChatIncomingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) - ), - CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) - ), - ] + theme: ThemeData( + extensions: [ + CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), ), - home: ... - ); -``` - - - - - -### 3. Ease of Integration - -To apply these styles: - -1. Create a `CometChatMessageListStyle` object. -2. Assign your custom outgoing and incoming bubble styles. -3. Pass this object to the `style` property of the **CometChatMessageList** widget. - -This modular approach ensures that customization is both easy to manage and highly adaptable. - - - -```dart -CometChatMessageList( - user: user, - group: group, - style: CometChatMessageListStyle( - incomingMessageBubbleStyle: CometChatIncomingMessageBubbleStyle(), - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle(), - ), + CometChatIncomingMessageBubbleStyle( + backgroundColor: Color(0xFFFEEDE1), + ), + ], + ), ) ``` - - - - -## Key Features of Each Class - -### CometChatOutgoingMessageBubbleStyle - -Focused on customizing bubbles for **messages sent by the user**, with properties for: - -* **Text bubbles**: Style text content sent by users. -* **Image and video bubbles**: Customize visual media messages. -* **Audio bubbles**: Adjust styles for audio messages. -* **File bubbles**: Tailor the look of file-sharing bubbles. -* **Collaborative bubbles**: Style messages related to collaboration features. -* **Poll bubbles**: Adjust the appearance of poll-related messages. -* **Deleted message bubbles**: Customize how deleted messages are displayed. -* **Link preview bubbles**: Style links with previews for shared URLs. -* **Message translation bubbles**: Adjust translations for sent messages. -* **Sticker bubbles**: Customize stickers sent in chats. -* **Call bubbles**: Style voice and video call bubbles. -* Additional customizations like reactions, timestamps, avatars, and borders. - - + - - -```dart -CometChatOutgoingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) -) -``` - - - - - -### CometChatIncomingMessageBubbleStyle +--- -Designed to style bubbles for **messages received from others**, with properties for: - -* **Text bubbles**: Customize text content from other users. -* **Image and video bubbles**: Adjust styles for media from others. -* **Audio bubbles**: Customize received audio messages. -* **File bubbles**: Tailor the look of received files. -* **Collaborative bubbles**: Style incoming collaboration-related messages. -* **Poll bubbles**: Adjust the appearance of polls sent by others. -* **Deleted message bubbles**: Customize how deleted messages appear. -* **Link preview bubbles**: Style links with previews in received messages. -* **Message translation bubbles**: Adjust translations for received messages. -* **Sticker bubbles**: Customize stickers sent by others. -* **Call bubbles**: Style voice and video call bubbles. -* **Sender name**: Customize the display style for sender names. -* **AI Assistant bubbles**: Customize how ai assistant messages appear. -* Additional customizations like reactions, timestamps, avatars, and borders. +## Component-Level Styling - - - +Pass styles directly to `CometChatMessageList`: - - ```dart -CometChatIncomingMessageBubbleStyle( - backgroundColor: Color(0xFFF76808) +CometChatMessageList( + user: user, + style: CometChatMessageListStyle( + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), + incomingMessageBubbleStyle: CometChatIncomingMessageBubbleStyle( + backgroundColor: Color(0xFFFEEDE1), + ), + ), ) ``` - - - - -## Benefits - -By using these classes, developers can: - -* Save time by focusing on specific customizations. -* Reduce complexity while maintaining a consistent design. -* Create visually appealing and user-friendly chat interfaces. - -Whether you're tweaking a single bubble type or applying a cohesive design across your application, these tools provide the flexibility and precision needed to bring your vision to life. - - - -## Customizable Message Bubbles +--- -The CometChat Flutter Chat UI Kit offers a versatile range of customizable message bubbles tailored to enhance any chat experience. From Text, Image, Video, and Audio Bubbles for seamless multimedia sharing, to File, Poll, and Collaborative Whiteboard/Document Bubbles for productivity, the UI Kit ensures every interaction is visually engaging. Link Previews, Stickers, and Call Bubbles add rich context, while Action and Deleted Message Bubbles enhance clarity. These bubbles are fully customizable, empowering developers to create unique, brand-specific chat interfaces. +## Bubble Types ### Text Bubble - + -Modify text color, font, and background to match your branding while maintaining readability. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor:Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ) - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + textBubbleStyle: CometChatTextBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), +) ``` -![Image](/images/1c8970f5-text_bubble_customized-7e864e9942e622a04619f92451de0d4e.png) - - - - - ### Image Bubble - + -Customize borders and background to enhance media presentation. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - imageBubbleStyle: CometChatImageBubbleStyle( - backgroundColor:Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - imageBubbleStyle: CometChatImageBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ) - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + imageBubbleStyle: CometChatImageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), +) ``` - - - - - - - - ### Video Bubble -Style play button color, background color and borders for a seamless viewing experience. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - videoBubbleStyle: CometChatVideoBubbleStyle( - backgroundColor:Color(0xFFF76808), - playIconColor: Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - videoBubbleStyle: CometChatVideoBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - playIconColor: Color(0xFFF76808), - ) - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + videoBubbleStyle: CometChatVideoBubbleStyle( + backgroundColor: Color(0xFFF76808), + playIconColor: Color(0xFFF76808), + ), +) ``` - - - - - - - - ### Audio Bubble - - - - -Adjust progress bar colors, play and download button styles, and backgrounds to suit your theme. - - - -```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - audioBubbleStyle: CometChatAudioBubbleStyle( - backgroundColor:Color(0xFFF76808), - playIconColor: Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - audioBubbleStyle: CometChatAudioBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - downloadIconColor: Color(0xFFF76808), - audioBarColor: Color(0xFFF76808), - playIconColor: Color(0xFFF76808), - ) - ), - ] - ) -``` - - - - - -### File Bubble - - - - - -Personalize file bubble's background and download icon colors. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - fileBubbleStyle: CometChatFileBubbleStyle( - backgroundColor:Color(0xFFF76808), - ) - ), - CometChatIncomingMessageBubbleStyle( - fileBubbleStyle: CometChatFileBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - downloadIconTint: Color(0xFFF76808), - ) - ), - ] - ) +CometChatIncomingMessageBubbleStyle( + audioBubbleStyle: CometChatAudioBubbleStyle( + backgroundColor: Color(0xFFFEEDE1), + downloadIconColor: Color(0xFFF76808), + audioBarColor: Color(0xFFF76808), + playIconColor: Color(0xFFF76808), + ), +) ``` - - - +### File Bubble -### Sticker Bubble - - - - - -Personalize sticker display with unique padding, borders, and background styles to match the app's personality. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - stickerBubbleStyle: CometChatStickerBubbleStyle( - backgroundColor: Color(0xFFF76808), - ), - ), - CometChatIncomingMessageBubbleStyle( - stickerBubbleStyle: CometChatStickerBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ), - ), - ] - ) +CometChatIncomingMessageBubbleStyle( + fileBubbleStyle: CometChatFileBubbleStyle( + backgroundColor: Color(0xFFFEEDE1), + downloadIconTint: Color(0xFFF76808), + ), +) ``` - - - - - - - - -### Call Bubble +### Poll Bubble - + -Customize icons, text, and background elements for incoming and outgoing call notifications to fit seamlessly into your UI design. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - videoCallBubbleStyle: CometChatCallBubbleStyle( - backgroundColor: Color(0xFFF76808), - iconColor: Color(0xFFF76808), - buttonTextStyle: TextStyle( - color: Colors.white, - ), - dividerColor: Color(0xFFFBAA75) - ), - ), - CometChatIncomingMessageBubbleStyle( - videoCallBubbleStyle: CometChatCallBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - iconColor: Color(0xFFF76808), - buttonTextStyle: TextStyle( - color: Color(0xFFF76808), - ), - ), - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + pollsBubbleStyle: CometChatPollsBubbleStyle( + backgroundColor: Color(0xFFF76808), + progressBackgroundColor: Color(0xFFFBAA75), + iconColor: Color(0xFFF76808), + ), +) ``` - - - +### Call Bubble -### Collaborative Whiteboard Bubble - - - - - -Style the background and interaction controls to support creative collaboration. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - collaborativeWhiteboardBubbleStyle: CometChatCollaborativeBubbleStyle( - backgroundColor:Color(0xFFF76808), - iconTint: Color(0xFFFFFFFF), - titleStyle: TextStyle( - fontWeight: FontWeight.bold, - color: Color(0xFFFFFFFF), - ), - buttonTextStyle: TextStyle( - color: Color(0xFFFFFFFF), - ), - dividerColor: Color(0xFFFBAA75), - ) - ), - CometChatIncomingMessageBubbleStyle( - collaborativeWhiteboardBubbleStyle: CometChatCollaborativeBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - iconTint: Color(0xFFF76808), - titleStyle: TextStyle( - fontWeight: FontWeight.bold, - ), - buttonTextStyle: TextStyle( - color: Color(0xFFF76808), - ), - ) - ), - ] - ) -``` - - - - - - - - - -### Collaborative Document Bubble - - - - - -Customize fonts and interface elements for shared document interaction. - - - -```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - collaborativeDocumentBubbleStyle: CometChatCollaborativeBubbleStyle( - backgroundColor:Color(0xFFF76808), - iconTint: Color(0xFFFFFFFF), - titleStyle: TextStyle( - fontWeight: FontWeight.bold, - color: Color(0xFFFFFFFF), - ), - buttonTextStyle: TextStyle( - color: Color(0xFFFFFFFF), - ), - dividerColor: Color(0xFFFBAA75), - ) - ), - CometChatIncomingMessageBubbleStyle( - collaborativeDocumentBubbleStyle: CometChatCollaborativeBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - iconTint: Color(0xFFF76808), - titleStyle: TextStyle( - fontWeight: FontWeight.bold, - ), - buttonTextStyle: TextStyle( - color: Color(0xFFF76808), - ), - ) - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + videoCallBubbleStyle: CometChatCallBubbleStyle( + backgroundColor: Color(0xFFF76808), + iconColor: Color(0xFFF76808), + buttonTextStyle: TextStyle(color: Colors.white), + dividerColor: Color(0xFFFBAA75), + ), +) ``` - - - - - - - - -### Poll Bubble +### Link Preview Bubble - + -Tailor vote bar colors, text, and layouts to align with your UI design. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - pollsBubbleStyle: CometChatPollsBubbleStyle( - backgroundColor: Color(0xFFF76808), - progressBackgroundColor: Color(0xFFFBAA75), - iconColor: Color(0xFFF76808), - voterAvatarStyle: CometChatAvatarStyle( - border: Border.all(color: Color(0xFFF76808)), - ) - ), - ), - CometChatIncomingMessageBubbleStyle( - pollsBubbleStyle: CometChatPollsBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - progressBackgroundColor: Color(0xFFDCDCDC), - progressColor: Color(0xFFF76808), - iconColor: Colors.white, - selectedOptionColor: Color(0xFFF76808), - voterAvatarStyle: CometChatAvatarStyle( - border: Border.all(color: Color(0xFFFEEDE1)), - ) - ), - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + linkPreviewBubbleStyle: CometChatLinkPreviewBubbleStyle( + backgroundColor: Color(0xFFFBAA75), + ), + textBubbleStyle: CometChatTextBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), +) ``` - - - - - - - - -### Link Preview Bubble +### Deleted Message Bubble - + -Adjust title fonts, descriptions, and thumbnail frames for cohesive link displays. - - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - linkPreviewBubbleStyle: CometChatLinkPreviewBubbleStyle( - backgroundColor:Color(0xFFFBAA75), - ), - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor: Color(0xFFF76808), - ), - ), - CometChatIncomingMessageBubbleStyle( - linkPreviewBubbleStyle: CometChatLinkPreviewBubbleStyle( - backgroundColor: Color(0xFFFBAA75), - ), - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ), - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + deletedBubbleStyle: CometChatDeletedBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), +) ``` - - - +### Collaborative Bubbles - - - -### Action Message Bubble - - - + -Style background colors and icons for activity-driven notifications. - - - ```dart -ThemeData( - extensions: [ - CometChatActionBubbleStyle( - textStyle: TextStyle( - color: Color(0xFFF76808), - ), - border: Border.all( - color: Color(0xFFF76808), - ), - backgroundColor: Color(0xFFFEEDE1) - ) - ] - ) +CometChatOutgoingMessageBubbleStyle( + collaborativeWhiteboardBubbleStyle: CometChatCollaborativeBubbleStyle( + backgroundColor: Color(0xFFF76808), + iconTint: Color(0xFFFFFFFF), + titleStyle: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFFFFFFFF)), + buttonTextStyle: TextStyle(color: Color(0xFFFFFFFF)), + dividerColor: Color(0xFFFBAA75), + ), +) ``` - - - - - - - - -### Deleted Message Bubble - - - - - -Add unique styles for placeholders that indicate message deletion. +### Sticker Bubble - - ```dart -ThemeData( - extensions: [ - CometChatOutgoingMessageBubbleStyle( - deletedBubbleStyle: CometChatDeletedBubbleStyle( - backgroundColor: Color(0xFFF76808), - ), - ), - CometChatIncomingMessageBubbleStyle( - deletedBubbleStyle: CometChatDeletedBubbleStyle( - backgroundColor: Color(0xFFFEEDE1), - ), - ), - ] - ) +CometChatOutgoingMessageBubbleStyle( + stickerBubbleStyle: CometChatStickerBubbleStyle( + backgroundColor: Color(0xFFF76808), + borderRadius: BorderRadius.circular(12), + ), +) ``` - - - +### Voice Call Bubble - - - - -### Call Action Bubble - - - - - -Customize call action bubbles with unique background colors and icons. - - - ```dart -ThemeData(extensions: [ - CometChatColorPalette(textSecondary: Color(0xFFF76808)), - CometChatActionBubbleStyle( - textStyle: TextStyle( - color: Color(0xFFF76808), - ), - border: Border.all( - color: Color(0xFFF76808), - ), - backgroundColor: Color(0xFFFEEDE1)) - ]); +CometChatOutgoingMessageBubbleStyle( + voiceCallBubbleStyle: CometChatCallBubbleStyle( + backgroundColor: Color(0xFFF76808), + iconColor: Color(0xFFFFFFFF), + buttonTextStyle: TextStyle(color: Colors.white), + ), +) ``` - - - - - - - - -### AI Assistant Bubble - -AI Assistant bubbles display messages and interactions from an AI assistant within the chat interface. - -**Default** - - - - +--- -**Customization** +## Style Properties Reference - - - +### CometChatOutgoingMessageBubbleStyle -**Customizing Bubble** +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of the message bubble | +| `border` | `BoxBorder?` | Border of the message bubble | +| `borderRadius` | `BorderRadiusGeometry?` | Border radius of the message bubble | +| `messageBubbleBackgroundImage` | `DecorationImage?` | Background image for the bubble | +| `threadedMessageIndicatorTextStyle` | `TextStyle?` | Text style for threaded message indicator | +| `threadedMessageIndicatorIconColor` | `Color?` | Icon color for threaded message indicator | +| `messageBubbleAvatarStyle` | `CometChatAvatarStyle?` | Style for sender avatar | +| `messageReceiptStyle` | `CometChatMessageReceiptStyle?` | Style for message receipts | +| `messageBubbleReactionStyle` | `CometChatReactionsStyle?` | Style for message reactions | +| `messageBubbleDateStyle` | `CometChatDateStyle?` | Style for message date | +| `textBubbleStyle` | `CometChatTextBubbleStyle?` | Style for text messages | +| `imageBubbleStyle` | `CometChatImageBubbleStyle?` | Style for image messages | +| `videoBubbleStyle` | `CometChatVideoBubbleStyle?` | Style for video messages | +| `audioBubbleStyle` | `CometChatAudioBubbleStyle?` | Style for audio messages | +| `fileBubbleStyle` | `CometChatFileBubbleStyle?` | Style for file messages | +| `pollsBubbleStyle` | `CometChatPollsBubbleStyle?` | Style for poll messages | +| `stickerBubbleStyle` | `CometChatStickerBubbleStyle?` | Style for sticker messages | +| `voiceCallBubbleStyle` | `CometChatCallBubbleStyle?` | Style for voice call bubbles | +| `videoCallBubbleStyle` | `CometChatCallBubbleStyle?` | Style for video call bubbles | +| `linkPreviewBubbleStyle` | `CometChatLinkPreviewBubbleStyle?` | Style for link preview bubbles | +| `collaborativeDocumentBubbleStyle` | `CometChatCollaborativeBubbleStyle?` | Style for collaborative document bubbles | +| `collaborativeWhiteboardBubbleStyle` | `CometChatCollaborativeBubbleStyle?` | Style for collaborative whiteboard bubbles | +| `messageTranslationBubbleStyle` | `CometChatMessageTranslationBubbleStyle?` | Style for translated messages | +| `deletedBubbleStyle` | `CometChatDeletedBubbleStyle?` | Style for deleted messages | +| `moderationStyle` | `CometChatModerationStyle?` | Style for moderated messages | +| `messagePreviewStyle` | `CometChatMessagePreviewStyle?` | Style for message previews | +| `exceptionStyle` | `CometChatExceptionStyle?` | Style for exception views | - - -```dart -ThemeData( - extensions: [ - CometChatAiAssistantBubbleStyle( - backgroundColor: Colors.transparent, - textColor: const Color(0xFF141414), - textStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts - ), - ), - ], -); -``` +### CometChatIncomingMessageBubbleStyle - +Includes all properties from `CometChatOutgoingMessageBubbleStyle` except `messageReceiptStyle`, `moderationStyle`, and `exceptionStyle`, plus: - \ No newline at end of file +| Property | Type | Description | +| --- | --- | --- | +| `senderNameTextStyle` | `TextStyle?` | Text style for sender name | +| `aiAssistantBubbleStyle` | `CometChatAIAssistantBubbleStyle?` | Style for AI assistant bubbles | diff --git a/ui-kit/flutter/sound-manager.mdx b/ui-kit/flutter/sound-manager.mdx index fd3317552..c70ad5b88 100644 --- a/ui-kit/flutter/sound-manager.mdx +++ b/ui-kit/flutter/sound-manager.mdx @@ -1,72 +1,116 @@ --- title: "Sound Manager" +sidebarTitle: "Sound Manager" +description: "Manage and customize audio cues for incoming/outgoing calls and messages in CometChat Flutter UI Kit." --- -## Overview + -The SoundManager is a helper class responsible for managing and playing various types of audio in the CometChat UI Kit. This includes sound events for incoming and outgoing messages and calls. +| Field | Value | +| --- | --- | +| Package | `cometchat_uikit_shared` | +| Import | `import 'package:cometchat_uikit_shared/cometchat_uikit_shared.dart';` | +| Class | `SoundManager` (singleton) | +| Play sound | `SoundManager().play(sound: Sound.incomingMessage)` | +| Stop sound | `SoundManager().stop()` | +| Sound events | `incomingMessage`, `outgoingMessage`, `incomingMessageFromOther`, `incomingCall`, `outgoingCall` | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/resources) | -## Methods + -### Play Sound +`SoundManager` is a singleton helper class for managing and playing audio cues — incoming/outgoing calls and messages. -The SoundManager plays pre-defined or custom sounds based on user interactions with the chat interface. If no custom sound file is provided, the default sound is played. +--- -* `play()`: This method plays different types of sounds for incoming and outgoing calls and messages. +## Methods - - -```dart -// Play sound with default sound: -SoundManager().play(sound: Sound.incomingMessage); //To play default incoming message sound -SoundManager().play(sound: Sound.outgoingMessage);//To play default outgoing message sound -``` +### play - +Plays the default or custom audio for a sound event. - +```dart +void play({ + required Sound sound, + String? customSound, + String? packageName, + bool? isLooping, +}) +``` -CometChat sound will behave differently with different type of OS in case of background playing +| Parameter | Type | Description | +| --- | --- | --- | +| `sound` | `Sound` | Required. The sound event type to play | +| `customSound` | `String?` | Optional. Asset path for custom sound file | +| `packageName` | `String?` | Optional. Package name when using sounds from another plugin | +| `isLooping` | `bool?` | Optional. Whether to loop the sound (default: `false`) | -### Stop Sound +```dart +// Play default sounds +SoundManager().play(sound: Sound.incomingMessage); +SoundManager().play(sound: Sound.outgoingMessage); + +// Play custom sound +SoundManager().play( + sound: Sound.outgoingMessage, + customSound: "assets/custom_sound.wav", +); + +// Play looping sound (e.g., for incoming call) +SoundManager().play( + sound: Sound.incomingCall, + isLooping: true, +); +``` -The SoundManager can Stop different types of sounds for incoming and outgoing calls and messages using the following method: +### stop -* `stop()`: This method Stops any sound currently being played. +Stops any currently playing sound. - - ```dart SoundManager().stop(); ``` - +--- - +## Sound Enum -## Usage +| Value | Default Asset | When it plays | +| --- | --- | --- | +| `incomingMessage` | `assets/sound/incoming_message.wav` | New message received | +| `outgoingMessage` | `assets/sound/outgoing_message.wav` | Message sent | +| `incomingMessageFromOther` | `assets/sound/incoming_message.wav` | Message from another conversation | +| `incomingCall` | `assets/sound/incoming_call.wav` | Incoming call detected | +| `outgoingCall` | `assets/sound/outgoing_call.wav` | Outgoing call initiated | -Here is how to use SoundManager: +--- + +## Usage - - ```dart -//Play sound with custom sound -SoundManager().play(sound: Sound.outgoingMessage, customSound: "assetPath"); //To custom message sound -``` +import 'package:cometchat_uikit_shared/cometchat_uikit_shared.dart'; + +// Play incoming message sound +SoundManager().play(sound: Sound.incomingMessage); - +// Play outgoing call sound +SoundManager().play(sound: Sound.outgoingCall); - +// Play custom notification sound +SoundManager().play( + sound: Sound.incomingMessage, + customSound: "assets/sounds/notification.mp3", +); -By using the SoundManager, you can enhance the user experience in your chat application by integrating audible cues for chat interactions. +// Play looping ringtone for incoming call +SoundManager().play( + sound: Sound.incomingCall, + isLooping: true, +); -The table below lists down various Sound enum cases and the corresponding assets played for them: +// Stop any playing sound +SoundManager().stop(); +``` -| Sound | Asset | -| ------------------------ | ---------------------------------- | -| incomingMessage | assets/sound/incoming\_message.wav | -| outgoingMessage | assets/sound/outgoing\_message.wav | -| incomingMessageFromOther | assets/sound/incoming\_message.wav | -| outgoingCall | assets/sound/outgoing\_call.wav | -| incomingCall | assets/sound/incoming\_call.wav | + +Sound behavior varies by OS when the app is in the background. + diff --git a/ui-kit/flutter/theme-introduction.mdx b/ui-kit/flutter/theme-introduction.mdx index a4f874967..984444790 100644 --- a/ui-kit/flutter/theme-introduction.mdx +++ b/ui-kit/flutter/theme-introduction.mdx @@ -1,129 +1,157 @@ --- -title: "Theming In CometChat Flutter UI Kit" -sidebarTitle: "Introduction" +title: "Theming" +sidebarTitle: "Overview" +description: "Customize the CometChat Flutter UI Kit appearance using ThemeExtensions for colors, fonts, spacing, and dark mode." --- -CometChat's theming framework is a robust system that empowers developers to define the **look and feel** of their applications with precision and consistency. It follows three essential design system principles: **Color**, **Typography**, and **Shape**. These principles guide the customization of various UI components. + - - - - -*** +| Field | Value | +| --- | --- | +| Goal | Customize UI Kit appearance (colors, fonts, spacing) via Flutter ThemeExtensions | +| Where | `ThemeData.extensions` in `MaterialApp` | +| Color | `CometChatColorPalette` — primary, neutral, alert, text, icon, background colors | +| Typography | `CometChatTypography` — font sizes, weights, text styles | +| Spacing | `CometChatSpacing` — padding, margin, border radius | +| Dark mode | Use separate `CometChatColorPalette` for dark theme | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/theme) | -## Theming Overview + -Theming in our UI Kit consists of three core components: +Theming controls the look and feel of the chat UI — colors, fonts, and spacing — through Flutter's `ThemeExtension` system. -* **Color**: Managed through `CometChatColorPalette`, it controls the application's color scheme, including primary, neutral, alert, and text colors. -* **Typography**: Defined via `CometChatTypography`, it standardizes text styles, such as font size and weight. -* **Shape**: Configured using `CometChatSpacing`, it defines the structure of margins, paddings, and border radii, shaping the visual layout. + + + -### Key Benefits +--- -* Achieve **consistent UI** design across your application. -* Support for **light and dark themes**. -* Easy **scalability and customization** for app-specific requirements. +## Core Components -*** +| Component | Class | Purpose | +| --- | --- | --- | +| Color | `CometChatColorPalette` | Primary, neutral, alert, text, icon, background colors | +| Typography | `CometChatTypography` | Font sizes, weights, text styles | +| Spacing | `CometChatSpacing` | Padding, margin, border radius | -### Light and Dark Themes +### Typography Tokens -Our Chat UI Kit supports both light and dark themes, to enhance usability and accessibility across diverse environments ensuring that your application is adaptable to user preferences and device settings. +| Token | Purpose | +| --- | --- | +| `heading1` - `heading4` | Heading text styles | +| `body` | Body text | +| `caption1`, `caption2` | Caption text | +| `button` | Button text | +| `link` | Link text | +| `title` | Title text | - - - +### Spacing Tokens -The light theme provides a clean and bright interface ideal for well-lit settings, while the dark theme reduces eye strain and conserves battery life in low-light environments. +| Token | Default Value | +| --- | --- | +| `spacing` - `spacing20` | 2px - 80px (increments of 4) | +| `padding` - `padding10` | Derived from spacing | +| `margin` - `margin20` | Derived from spacing | +| `radius` - `radius6`, `radiusMax` | Border radius values | - - - +--- -By offering adaptive theming, the UI Kit ensures a seamless and visually appealing experience that caters to user preferences and situational needs. This flexibility helps deliver a modern and inclusive chat experience. +## Basic Usage -### Custom Theme +Override theme properties in your `MaterialApp`: -The Chat UI Kit offers robust support for creating **customized themes**, allowing developers to define unique visual styles using `CometChatColorPalette`, `CometChatTypography`, and `CometChatSpacing`. By integrating these custom objects with `ThemeData` `extensions`, developers can establish global theming tailored to their application's specific design requirements. This approach promotes consistency, adaptability, and personalization, enabling seamless alignment with branding guidelines while enhancing user experience. The customization capabilities empower developers to build visually distinct and cohesive chat interfaces that resonate with their target audience. +```dart title="main.dart" +MaterialApp( + theme: ThemeData( + fontFamily: 'Roboto', + extensions: [ + CometChatColorPalette( + primary: Color(0xFFF76808), + textPrimary: Color(0xFF141414), + background1: Color(0xFFFFFFFF), + ), + ], + ), + home: MyApp(), +) +``` -Flutter's [**ThemeExtension**](https://api.flutter.dev/flutter/material/ThemeExtension-class.html) allows you to extend the default theming system to include **custom properties**, enabling **global styling** for app-specific widgets. It provides a structured way to define custom colors, typography, or spacing beyond Flutter’s default themes. +--- -By creating custom **ThemeExtension** classes, you can apply consistent styles across widgets using `ThemeData`. Developers can access these styles through `Theme.of(context).extension()`, ensuring a clean and maintainable approach to styling. This is particularly useful for apps requiring **customizable and reusable themes**. +## Light and Dark Themes - + - - -```dart +```dart title="Light Theme" ThemeData( - fontFamily: 'Times New Roman', - extensions: [ - CometChatColorPalette( - primary: Color(0xFFF76808) - ) - ] + extensions: [ + CometChatColorPalette( + primary: Color(0xFF6852D6), + textPrimary: Color(0xFF141414), + textSecondary: Color(0xFF727272), + background1: Color(0xFFFFFFFF), + borderLight: Color(0xFFF5F5F5), + ), + ], ) ``` - - - - -*** - -## Core Components - -### **Color** - -The `CometChatColorPalette` class offers a comprehensive way to manage colors in your app. It includes colors for primary themes, alerts, text, icons, borders, and backgrounds. - -#### Features - -* **Primary Colors**: Base colors and extended shades. -* **Neutral Colors**: Shades for surfaces and backgrounds. -* **Alert Colors**: Colors for states like success, error, warning, and info. -* **Text Colors**: Differentiated for primary, secondary, and disabled states. - - + -### **Typography** - -Typography plays a critical role in ensuring that content is both legible and engaging. The UI Kit supports custom font styles and weights, allowing developers to create a hierarchy of text elements. +```dart title="Dark Theme" +ThemeData( + extensions: [ + CometChatColorPalette( + primary: Color(0xFF6852D6), + textPrimary: Color(0xFFFFFFFF), + textSecondary: Color(0xFF989898), + background1: Color(0xFF1A1A1A), + borderLight: Color(0xFF272727), + ), + ], +) +``` -#### Features +--- -* **Headings**: Text styles for various heading levels, allowing for clear text hierarchy. -* **Body**: Defines the styling for regular text, such as paragraphs or content. -* **Captions**: Smaller text style, typically used for labels or supplementary information. -* **Buttons**: Customizes the text style for button text. -* **Links**: Styles the text for clickable links. -* **Titles**: Defines the style for main titles or component headers. +## Custom Brand Colors - + -### **Spacing** - -Spacing plays a key role in modern UI design by improving clarity, readability, and usability. Proper spacing allows elements to stand out, guides the user’s focus, and enhances the visual hierarchy. It ensures that interfaces feel organized and easy to navigate, contributing significantly to a seamless and intuitive user experience.`CometChatSpacing` provides various spacing properties such as padding, margin, and radius, essential for maintaining consistent layouts across the UI. - -#### Features - -* **Padding**: Controls the internal spacing within elements, ensuring content doesn't touch the edges. -* **Margin**: Defines the space between elements, providing separation for better visual structure. -* **Radius**: Adjusts the corner rounding of UI elements for a smoother, more modern appearance. - - - - +```dart +ThemeData( + fontFamily: 'Times New Roman', + extensions: [ + CometChatColorPalette( + primary: Color(0xFFF76808), + iconHighlight: Color(0xFFF76808), + extendedPrimary500: Color(0xFFFBAA75), + ), + ], +) +``` -### Best Practices +--- -* **Ensure** Contrast: Follow accessibility guidelines to maintain a minimum contrast ratio. -* **Consistency**: Use a consistent color palette across all components. -* **Adaptability**: Test your theme in various scenarios, such as low-light and high-contrast environments. +## Next Steps + + + + Full list of color tokens + + + Style individual components + + + Customize message bubbles + + + Multi-language support + + From 1e5ca024588cbcfeac78f61b22179b351fe68161 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 14:13:57 +0530 Subject: [PATCH 033/106] Update component-styling.mdx --- ui-kit/flutter/component-styling.mdx | 152 ++++++++++++++++++++++++++- 1 file changed, 151 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/component-styling.mdx b/ui-kit/flutter/component-styling.mdx index 29eb4bf94..5ca6af35a 100644 --- a/ui-kit/flutter/component-styling.mdx +++ b/ui-kit/flutter/component-styling.mdx @@ -10,7 +10,9 @@ description: "Style individual CometChat Flutter UI Kit components using ThemeEx | --- | --- | | Method | Add component style classes to `ThemeData.extensions` | | Components | Conversations, MessageList, MessageComposer, MessageHeader, Users, Groups, GroupMembers | -| Base components | Avatar, Badge, StatusIndicator, Receipts, Reactions, MediaRecorder | +| Base components | Avatar, Badge, StatusIndicator, Receipts, Reactions, ReactionList, MediaRecorder | +| AI components | ConversationStarter, ConversationSummary, SmartReplies, AIOptionSheet, AIAssistantChatHistory | +| Option sheets | MessageOptionSheet, AttachmentOptionSheet, AIOptionSheet | | Pattern | `CometChatStyle` classes | | Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/chat_uikit) | @@ -148,6 +150,30 @@ ThemeData( ) ``` +### Group Members + +```dart +ThemeData( + extensions: [ + CometChatGroupMembersStyle( + avatarStyle: CometChatAvatarStyle( + borderRadius: BorderRadius.circular(8), + backgroundColor: Color(0xFFFBAA75), + ), + titleStyle: TextStyle(color: Color(0xFFF76808)), + separatorColor: Color(0xFFF76808), + ownerMemberScopeBackgroundColor: Color(0xFFF76808), + adminMemberScopeBackgroundColor: Color(0xFFFEEDE1), + adminMemberScopeBorder: Border.all(color: Color(0xFFF76808)), + adminMemberScopeTextColor: Color(0xFFF76808), + moderatorMemberScopeBackgroundColor: Color(0xFFFEEDE1), + moderatorMemberScopeTextColor: Color(0xFFF76808), + backIconColor: Color(0xFFF76808), + ), + ], +) +``` + --- ## Base Components @@ -215,6 +241,90 @@ CometChatReactionsStyle( ) ``` +### Reaction List + +```dart +CometChatReactionListStyle( + activeTabTextColor: Color(0xFFF76808), + activeTabIndicatorColor: Color(0xFFF76808), +) +``` + +### Media Recorder + +```dart +CometChatMediaRecorderStyle( + recordIndicatorBackgroundColor: Color(0xFFF44649), + recordIndicatorBorderRadius: BorderRadius.circular(20), + pauseButtonBorderRadius: BorderRadius.circular(8), + deleteButtonBorderRadius: BorderRadius.circular(8), + stopButtonBorderRadius: BorderRadius.circular(8), +) +``` + +--- + +## Option Sheets + +### Message Option Sheet + +```dart +ThemeData( + extensions: [ + CometChatMessageOptionSheetStyle( + backgroundColor: Color(0xFFFEEDE1), + iconColor: Color(0xFFF76808), + ), + ], +) +``` + +### Attachment Option Sheet + +```dart +ThemeData( + extensions: [ + CometChatAttachmentOptionSheetStyle( + backgroundColor: Color(0xFFFEEDE1), + iconColor: Color(0xFFF76808), + ), + ], +) +``` + +### Message Information + +```dart +ThemeData( + extensions: [ + CometChatOutgoingMessageBubbleStyle( + backgroundColor: Color(0xFFF76808), + ), + CometChatMessageInformationStyle( + backgroundHighLightColor: Color(0xFFFEEDE1), + messageReceiptStyle: CometChatMessageReceiptStyle( + readIconColor: Color(0xFFF76808), + ), + ), + ], +) +``` + +### Mentions + +```dart +ThemeData( + extensions: [ + CometChatMentionsStyle( + mentionSelfTextBackgroundColor: Color(0xFFF76808), + mentionTextBackgroundColor: Colors.white, + mentionTextColor: Colors.black, + mentionSelfTextColor: Colors.white, + ), + ], +) +``` + --- ## AI Components @@ -246,3 +356,43 @@ CometChatAISmartRepliesStyle( itemBorder: Border.all(color: Color(0xFFFBBB90)), ) ``` + +### Conversation Summary + +```dart +CometChatAIConversationSummaryStyle( + backgroundColor: Color(0xFFFEEDE1), + titleStyle: TextStyle(color: Color(0xFFF76808)), +) +``` + +### AI Option Sheet + +```dart +CometChatAiOptionSheetStyle( + backgroundColor: Color(0xFFFFF9F5), + iconColor: Color(0xFFF76808), +) +``` + +### AI Assistant Chat History + +```dart +final ccColor = CometChatThemeHelper.getColorPalette(context); + +CometChatAIAssistantChatHistory( + user: user, + style: CometChatAIAssistantChatHistoryStyle( + backgroundColor: Color(0xFFFFFAF6), + headerBackgroundColor: Color(0xFFFFFAF6), + headerTitleTextColor: ccColor.textPrimary, + newChatIconColor: ccColor.iconSecondary, + newChatTextColor: ccColor.textPrimary, + dateSeparatorStyle: CometChatDateStyle( + textColor: ccColor.textTertiary, + backgroundColor: Color(0xFFFFFAF6), + ), + itemTextColor: ccColor.textPrimary, + ), +) +``` From 56b276861839e356bcff4ebc95eb7e5468958caa Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 14:14:05 +0530 Subject: [PATCH 034/106] Update message-bubble-styling.mdx --- ui-kit/flutter/message-bubble-styling.mdx | 62 ++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/message-bubble-styling.mdx b/ui-kit/flutter/message-bubble-styling.mdx index 4c928a04f..3b5fd03ca 100644 --- a/ui-kit/flutter/message-bubble-styling.mdx +++ b/ui-kit/flutter/message-bubble-styling.mdx @@ -10,8 +10,10 @@ description: "Customize incoming and outgoing message bubbles in CometChat Flutt | --- | --- | | Outgoing | `CometChatOutgoingMessageBubbleStyle` | | Incoming | `CometChatIncomingMessageBubbleStyle` | +| Action | `CometChatActionBubbleStyle` | +| AI Assistant | `CometChatAiAssistantBubbleStyle` | | Usage | Add to `ThemeData.extensions` or pass to `CometChatMessageListStyle` | -| Bubble types | Text, Image, Video, Audio, File, Poll, Sticker, Voice Call, Video Call, Link Preview, Collaborative Document, Collaborative Whiteboard, Message Translation, Deleted, AI Assistant (incoming only) | +| Bubble types | Text, Image, Video, Audio, File, Poll, Sticker, Voice Call, Video Call, Link Preview, Collaborative Document, Collaborative Whiteboard, Message Translation, Deleted, Action, AI Assistant | | Source | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/shared_uikit/lib/src/models/extension_bubble_styles) | @@ -217,6 +219,7 @@ CometChatOutgoingMessageBubbleStyle( ```dart +// Collaborative Whiteboard CometChatOutgoingMessageBubbleStyle( collaborativeWhiteboardBubbleStyle: CometChatCollaborativeBubbleStyle( backgroundColor: Color(0xFFF76808), @@ -226,6 +229,17 @@ CometChatOutgoingMessageBubbleStyle( dividerColor: Color(0xFFFBAA75), ), ) + +// Collaborative Document +CometChatOutgoingMessageBubbleStyle( + collaborativeDocumentBubbleStyle: CometChatCollaborativeBubbleStyle( + backgroundColor: Color(0xFFF76808), + iconTint: Color(0xFFFFFFFF), + titleStyle: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFFFFFFFF)), + buttonTextStyle: TextStyle(color: Color(0xFFFFFFFF)), + dividerColor: Color(0xFFFBAA75), + ), +) ``` ### Sticker Bubble @@ -251,6 +265,36 @@ CometChatOutgoingMessageBubbleStyle( ) ``` +### Action Message Bubble + +Style activity-driven notifications like "User joined" or "User left": + +```dart +ThemeData( + extensions: [ + CometChatActionBubbleStyle( + textStyle: TextStyle(color: Color(0xFFF76808)), + border: Border.all(color: Color(0xFFF76808)), + backgroundColor: Color(0xFFFEEDE1), + ), + ], +) +``` + +### AI Assistant Bubble + +```dart +ThemeData( + extensions: [ + CometChatAiAssistantBubbleStyle( + backgroundColor: Colors.transparent, + textColor: Color(0xFF141414), + textStyle: TextStyle(fontFamily: 'Roboto'), + ), + ], +) +``` + --- ## Style Properties Reference @@ -295,3 +339,19 @@ Includes all properties from `CometChatOutgoingMessageBubbleStyle` except `messa | --- | --- | --- | | `senderNameTextStyle` | `TextStyle?` | Text style for sender name | | `aiAssistantBubbleStyle` | `CometChatAIAssistantBubbleStyle?` | Style for AI assistant bubbles | + +### CometChatActionBubbleStyle + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of action bubble | +| `border` | `BoxBorder?` | Border of action bubble | +| `textStyle` | `TextStyle?` | Text style for action message | + +### CometChatAiAssistantBubbleStyle + +| Property | Type | Description | +| --- | --- | --- | +| `backgroundColor` | `Color?` | Background color of AI assistant bubble | +| `textColor` | `Color?` | Text color | +| `textStyle` | `TextStyle?` | Text style for AI messages | From 4ecabe30110376e33d34209441d210e7e0d3ec74 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 14:26:44 +0530 Subject: [PATCH 035/106] updates { "group": "Reference", "pages": [ "ui-kit/flutter/methods", "ui-kit/flutter/events" ] }, --- ui-kit/flutter/events.mdx | 14 +++++++++++++- ui-kit/flutter/methods.mdx | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 4b0a0a06e..4d99da659 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -357,6 +357,16 @@ class _MessageEventsExampleState extends State with CometC // TODO("Not yet implemented") } + @override + void ccMessageForwarded(BaseMessage message, List? usersSent, List? groupsSent, MessageStatus status) { + // TODO("Not yet implemented") + } + + @override + void ccReplyToMessage(BaseMessage message, MessageStatus status) { + // TODO("Not yet implemented") + } + @override void onTextMessageReceived(TextMessage textMessage) { // TODO("Not yet implemented") @@ -570,7 +580,9 @@ class _CallEventsExampleState extends State with CometChatCal 1. `showPanel`: Triggered to show an additional UI panel with custom elements. 2. `hidePanel`: Triggered to hide a previously shown UI panel. 3. `ccActiveChatChanged`: Triggered when the active chat changes, providing information about the current message, user, and group. -4. `ccOpenChat`: Triggered to open a chat with a specific user or group. +4. `openChat`: Triggered to open a chat with a specific user or group. +5. `ccComposeMessage`: Triggered when composing a message with a specific text and status. +6. `onAiFeatureTapped`: Triggered when an AI feature is tapped for a specific user or group. diff --git a/ui-kit/flutter/methods.mdx b/ui-kit/flutter/methods.mdx index d0ab76a2a..bed14c418 100644 --- a/ui-kit/flutter/methods.mdx +++ b/ui-kit/flutter/methods.mdx @@ -38,7 +38,7 @@ Here's the table format for the properties available in `UIKitSettings`: | **subscriptionType** | `String` | Sets subscription type for tracking the presence of all users | | **roles** | `String` | Sets subscription type for tracking the presence of users with specified roles | | **autoEstablishSocketConnection** | `Boolean` | Configures if web socket connections will established automatically on app initialization or be done manually, set to true by default | -| **aiFeature** | `List` | Sets the AI Features that need to be added in UI Kit | +| **aiFeature** | `List` | Sets the AI Features that need to be added in UI Kit | | **extensions** | `List` | Sets the list of extension that need to be added in UI Kit | | **callingExtension** | `ExtensionsDataSource` | Sets the calling extension configuration | | **adminHost** | `String` | Sets a custom admin host URL | From 8f126d2a94681f476760fd5e69e4e4c6d9167907 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:09:36 +0530 Subject: [PATCH 036/106] UI Kit Guides --- ui-kit/flutter/guide-block-unblock-user.mdx | 266 ++++----- ui-kit/flutter/guide-call-log-details.mdx | 198 +++---- ui-kit/flutter/guide-group-chat.mdx | 268 ++++----- ui-kit/flutter/guide-message-agentic-flow.mdx | 512 +++++------------- ui-kit/flutter/guide-message-privately.mdx | 222 ++++---- ui-kit/flutter/guide-new-chat.mdx | 217 +++----- ui-kit/flutter/guide-overview.mdx | 33 +- ui-kit/flutter/guide-threaded-messages.mdx | 272 +++++----- ui-kit/flutter/mentions-formatter-guide.mdx | 14 + ui-kit/flutter/shortcut-formatter-guide.mdx | 14 + 10 files changed, 771 insertions(+), 1245 deletions(-) diff --git a/ui-kit/flutter/guide-block-unblock-user.mdx b/ui-kit/flutter/guide-block-unblock-user.mdx index 5a7eed5c4..8f9cecacb 100644 --- a/ui-kit/flutter/guide-block-unblock-user.mdx +++ b/ui-kit/flutter/guide-block-unblock-user.mdx @@ -1,183 +1,189 @@ --- -title: "Implementing Block/Unblock User in Flutter with CometChat UIKit" +title: "Block/Unblock Users" sidebarTitle: "Block/Unblock User" -description: "Enable users to block and unblock other users for privacy and spam control" +description: "Implement block and unblock user functionality in CometChat Flutter UI Kit with composer state management." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Block a user -await CometChatUIKit.blockUsers([user.uid]); - -// Unblock a user -await CometChatUIKit.unblockUsers([user.uid]); - -// Navigate to user info screen -Navigator.push( - context, - MaterialPageRoute( - builder: (_) => CometChatUserInfo(user: tappedUser), - ), -); - -// Check block status -if (user.blockedByMe) { - // Show unblock button -} else { - // Show block button -} -``` - -**Key Components & Methods:** -- `CometChatUIKit.blockUsers()` → SDK method to block users -- `CometChatUIKit.unblockUsers()` → SDK method to unblock users -- `CometChatUserInfo` → User profile screen -- `User.blockedByMe` → Block status property (SDK) +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometchatUserInfo` — uses `CometChatUIKit.blockUsers()` / `CometChatUIKit.unblockUsers()` SDK methods | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Events | Block/unblock state managed via `user.blockedByMe` property | +| UI helpers | `CometChatUserInfoController`, confirmation dialogs | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -**Sample Implementation:** [user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) - + +Block/Unblock lets users prevent specific users from sending them messages. When blocked, the message composer is hidden and replaced with an unblock prompt. -Enable users to block and unblock other users in your Flutter chat app by integrating CometChat’s `blockUsers` and `unblockUsers` methods with a simple UI. +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -## Overview +--- -The Block User feature lets one user prevent another from sending messages or interacting with them. Essential for user privacy, spam control, and moderation in public or group chats. Users tap “Block” or “Unblock,” and the CometChat SDK enforces the block state. +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometchatUserInfo` | User profile screen with block/unblock controls | +| `CometChatUserInfoController` | Controller managing block/unblock state and actions | +| `CometChatUIKit.blockUsers()` | SDK method to block specific users | +| `CometChatUIKit.unblockUsers()` | SDK method to unblock previously blocked users | +| `user.blockedByMe` | Property indicating if current user blocked this user | -- A Flutter project with **CometChat UIKit Flutter v5** installed -- Initialized CometChat credentials (`appID`, `region`, `authKey`) -- Navigation set up between your chat list and user-info screen (`lib/messages.dart`) +--- -## Components +## Integration Steps -| Component | Role | -|:------------------------------------|:--------------------------------------------------------| -| `CometChatUserInfo` | Displays user profile with block/unblock controls | -| `CometChatUIKit.blockUsers([...])` | SDK method to block specified user(s) | -| `CometChatUIKit.unblockUsers([...])` | SDK method to unblock specified user(s) | -| `ElevatedButton` | Flutter widget for block/unblock actions | +### 1. Navigate to User Info -## Integration Steps +Open the user info screen from the messages view when tapping the user profile or info icon. -### Navigate to User Info Screen +_File: [messages.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart)_ -Open the user-info screen when tapping the info icon in chat. ```dart -IconButton( - icon: Icon(Icons.info_outline), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => CometChatUserInfo(user: tappedUser), - ), - ); - }, +Navigator.push( + context, + MaterialPageRoute( + builder: (_) => CometchatUserInfo(user: tappedUser), + ), ); ``` -**File reference:** -[`sample_app/lib/messages/messages.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) +--- + +### 2. Block User + +Call the block user dialog which uses `CometChatUIKit.blockUsers()` with the target UID. On success, update the UI to show the blocked state. -### Add “Block User” Button +_File: [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart)_ -Let users block another user via the SDK. ```dart -ElevatedButton( - onPressed: () async { - try { - await CometChatUIKit.blockUsers([user.uid]); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('\${user.name} has been blocked')), +listTileOptions( + controller.user?.blockedByMe != true + ? Translations.of(context).block + : Translations.of(context).unBlock, + Icon(Icons.block, color: colorPalette.error), + () { + if (controller.user?.blockedByMe != true) { + controller.blockUserDialog( + context: context, + colorPalette: colorPalette, + typography: typography, ); - } catch (e) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Error blocking user: \$e')), + } else { + controller.unblockUserDialog( + context: context, + colorPalette: colorPalette, + typography: typography, ); } }, - child: Text('Block User'), -); +) ``` -**File reference:** -[`sample_app/lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) +--- -### Add “Unblock User” Button +### 3. Unblock User + +Call `CometChatUIKit.unblockUsers()` with the target UID. On success, restore the UI to allow messaging. + +_File: [cometchat_user_info_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info_controller.dart)_ -Allow users to undo the block. ```dart -ElevatedButton( - onPressed: () async { - try { - await CometChatUIKit.unblockUsers([user.uid]); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('\${user.name} has been unblocked')), - ); - } catch (e) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar(content: Text('Error unblocking user: \$e')), - ); - } - }, - child: Text('Unblock User'), -); +void unblockUserDialog({ + required BuildContext context, + required CometChatColorPalette colorPalette, + required CometChatTypography typography, +}) { + // Show confirmation dialog + // On confirm: CometChatUIKit.unblockUsers([user.uid]) +} ``` -**File reference:** -[`sample_app/lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) +--- -## Customization Options +### 4. Blocked State Banner -- **Button Styling:** Use `ElevatedButton.styleFrom(...)` to customize colors, padding, and shape. -- **Conditional Rendering:** Display “Block” or “Unblock” based on `user.blockedByMe` state. -- **Modal Confirmation:** Wrap actions in `showDialog` for “Are you sure?” prompts. +Display a warning banner when viewing a blocked user's profile. -## Filtering / Edge Cases +_File: [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart)_ -- **Self-Block Prevention:** Disable the button if `user.uid == loggedInUser.uid`. -- **Offline Users:** Optionally disable or queue actions when network is unavailable. +```dart +if (value.getBlockedByMe()) + Container( + padding: EdgeInsets.symmetric( + horizontal: spacing.padding3 ?? 0, + vertical: spacing.padding2 ?? 0, + ), + color: colorPalette.warning?.withValues(alpha: 0.2), + child: Row( + children: [ + Icon(Icons.info, color: colorPalette.warning), + SizedBox(width: spacing.padding2), + Text("${Translations.of(context).youHaveBlocked} ${widget.user.name}."), + ], + ), + ), +``` + +--- + +### 5. Composer Blocked State -## Error Handling & Blocked-User Handling +When a user is blocked, the composer in thread/message views is replaced with an unblock prompt. -- **SnackBars:** Show success or error messages via `ScaffoldMessenger`. -- **Retry Logic:** Offer a “Retry” action in the SnackBar on failure. -- **UI State:** Disable the button while the SDK call is in progress to prevent duplicates. +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -## Optional Context-Specific Notes +```dart +if (controller.user?.blockedByMe == true) { + return Container( + padding: EdgeInsets.symmetric(vertical: 8, horizontal: 20), + color: colorPalette.background4, + child: Column( + children: [ + Text(Translations.of(context).cantSendMessageBlockedUser), + ElevatedButton( + onPressed: () => controller.unBlockUser(), + child: Text(Translations.of(context).unBlock), + ), + ], + ), + ); +} +``` -**Group vs. User Blocking:** -This guide covers only user-to-user blocking. For group moderation (ban or remove members), see [`sample_app/lib/group_info/cometchat_group_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) methods like `removeMembers` and `banMembers`. +--- + +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| User info screen | `CometchatUserInfo` | [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | +| Block user | `blockUserDialog()` | [cometchat_user_info_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info_controller.dart) | +| Unblock user | `unblockUserDialog()` | [cometchat_user_info_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info_controller.dart) | +| Check blocked status | `user.blockedByMe` | [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | +| Blocked banner | Warning container | [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | +| Blocked composer | `_buildBlockedUserSection()` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | -| Feature | File | Method | -|:---------------------|:---------------------------------------------|:-----------------------------------------| -| Open User Info | [sample_app/lib/messages/messages.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) | `Navigator.push(...)` | -| Block User | [sample_app/lib/user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | `CometChatUIKit.blockUsers([...])` | -| Unblock User | [sample_app/lib/user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | `CometChatUIKit.unblockUsers([...])` | -| Group Management | [sample_app/lib/group_info/cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | Group-related actions (not blocking) | +--- ## Next Steps - - Display and manage user lists + + Display and manage user lists. - - View messages with blocked user handling + + Customize the message input component. - - Learn about group moderation features + + Browse all feature and formatter guides. - - Explore other implementation guides + + Full working sample application on GitHub. - \ No newline at end of file + diff --git a/ui-kit/flutter/guide-call-log-details.mdx b/ui-kit/flutter/guide-call-log-details.mdx index e7393ed16..09d09842e 100644 --- a/ui-kit/flutter/guide-call-log-details.mdx +++ b/ui-kit/flutter/guide-call-log-details.mdx @@ -1,171 +1,117 @@ --- -title: "Managing & Viewing Call Logs in Your Flutter Chat App" -sidebarTitle: "Call Logs" -description: "Display call history and detailed call information in your Flutter chat app" +title: "Call Log Details" +sidebarTitle: "Call Log Details" +description: "Display call history and detailed call information in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatCallLogs`, `CometChatCallLogDetails` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | Calls tab → `CometChatCallLogs` → tap item → `CometChatCallLogDetails` | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -// Display call logs list -CometChatCallLogs( - onItemClick: (callLog) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatCallLogDetails(callLog: callLog), - ), - ); - }, -); + -// Show call log details -CometChatCallLogDetails( - callLog: callLog, -); -``` +Call Log Details provides a dedicated Calls tab where users can view recent audio and video calls and inspect detailed information for each call. -**Key Components:** -- `CometChatCallLogs` → [Docs](/ui-kit/flutter/call-logs) -- `CometChatCallLogDetails` → Call details screen -- `CallLog` → Call log data model (SDK) +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -**Sample Implementation:** [call_log_details/cometchat_call_log_details.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) - -**Requirements:** Call functionality enabled in CometChat dashboard, microphone/camera permissions - - - -Learn how to integrate and customize CometChat’s `CometChatCallLogs` and `CometChatCallLogDetails` components to display call history and detailed call information in your Flutter chat app. - -## Overview +--- -- This feature provides a dedicated Calls tab where users can view a list of recent audio and video calls and inspect detailed information for each call. -- Enables users to review communication history, redial, or manage past calls directly within the app. -- Users access comprehensive call logs and individual call details via intuitive UI components. +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometChatCallLogs` | Displays the list of recent calls with tap callbacks | +| `CometChatCallLogDetails` | Shows detailed information (participants, duration, type) | +| `CallLog` | Call log data model from SDK | -- A Flutter project with **CometChat UIKit Flutter v5** installed -- CometChat credentials (`appID`, `region`, `authKey`) initialized -- Call functionality enabled in your CometChat app dashboard -- Required permissions for microphone and camera in your app -- Navigation setup for tabs and detail screens +--- -## Components +## Integration Steps -| Component | Role | -|:-----------------------------------|:---------------------------------------------------------------------| -| `CometChatCallLogs` | Displays the list of recent calls with tap callbacks | -| `CometChatCallLogDetails` | Shows detailed information (participants, duration, type) | -| `dashboard.dart` | Contains the Calls tab integration in the main UI | -| `call_log_details/cometchat_call_log_details.dart` | Implements the details screen UI | +### 1. Add Calls Tab -## Integration Steps +Integrate the Calls tab into your main dashboard using `CometChatCallLogs`. -### Add Calls Tab to Main UI +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ -Integrate the Calls tab into your main dashboard. ```dart -// In sample_app/lib/dashboard.dart, update your PageView or BottomNavigation -_pageController.selectedIndex == 2 - ? CometChatCallLogs( - onItemClick: (callLog) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatCallLogDetails(callLog: callLog), - ), - ); - }, - ) - : SizedBox.shrink(), +CometChatCallLogs( + onItemClick: (callLog) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatCallLogDetails(callLog: callLog), + ), + ); + }, +) ``` -**File reference:** -[`sample_app/lib/dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) +--- + +### 2. Display Call Logs -### Display Call Logs +Use `CometChatCallLogs` to fetch and show recent calls with customizable styling. + +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ -Use `CometChatCallLogs` to fetch and show recent calls. ```dart CometChatCallLogs( onItemClick: (callLog) { - // Navigates to details screen + // Navigate to details screen }, -); + callLogsStyle: CometChatCallLogsStyle( + backgroundColor: colorPalette.background1, + ), +) ``` -**File reference:** -[`sample_app/lib/dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) +--- + +### 3. Show Call Log Details -### Show Call Log Details +Present detailed information when a call log is tapped. + +_File: [cometchat_call_log_details.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart)_ -Present detailed information when a call log is tapped. ```dart CometChatCallLogDetails( callLog: callLog, -); +) ``` -**File reference:** -[`sample_app/lib/call_log_details/cometchat_call_log_details.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) - -## Implementation Flow - -1. User selects the Calls tab in the dashboard -2. `CometChatCallLogs` displays recent calls -3. User taps on a call log entry -4. App navigates to `CometChatCallLogDetails` showing call details - -## Customization Options - -- **Styling:** Override colors, fonts, and list item layouts via UIKit theming -- **Call Type Filters:** Apply filters in `CometChatCallLogs` if supported -- **Empty State:** Provide custom UI when no call logs are available - -## Filtering / Edge Cases - -- **No Call Logs:** Display an empty state message when call history is empty -- **Pagination:** Handle large call logs with lazy loading or pagination controls -- **Blocked Users:** Indicate or hide entries involving blocked users - -## Error Handling & Blocked-User Handling - -- **Network Errors:** Show `SnackBar` or error widgets when fetch fails -- **Blocked Users:** Disable detail navigation or show warning if a user is blocked -- **Retry Logic:** Offer retry options for failed fetch or navigation - -## Optional Context-Specific Notes +--- -- **Group Calls:** `CometChatCallLogDetails` will list all participants for group calls -- **1:1 Calls:** Details screen focuses on the other participant +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| Calls tab | `CometChatCallLogs` | [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | +| Display call logs | `CometChatCallLogs` | [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | +| Call details | `CometChatCallLogDetails` | [cometchat_call_log_details.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) | -| Feature | Component / Method | File(s) | -|:--------------------------|:------------------------------------|:---------------------------------------------------------------------| -| Calls tab integration | `CometChatCallLogs(onItemClick)` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | -| Display call logs | `CometChatCallLogs` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | -| Show call details | `CometChatCallLogDetails(callLog)` | [`call_log_details/cometchat_call_log_details.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/call_log_details/cometchat_call_log_details.dart) | +--- ## Next Steps - - Learn more about the Call Logs component + + Learn more about the Call Logs component. - - Explore all calling capabilities + + Explore all calling capabilities. - - Add call buttons to your chat interface + + Add call buttons to your chat interface. - - Explore other implementation guides + + Browse all feature and formatter guides. - \ No newline at end of file + diff --git a/ui-kit/flutter/guide-group-chat.mdx b/ui-kit/flutter/guide-group-chat.mdx index cdc640522..762b4b216 100644 --- a/ui-kit/flutter/guide-group-chat.mdx +++ b/ui-kit/flutter/guide-group-chat.mdx @@ -1,91 +1,50 @@ --- -title: "Managing Groups in Flutter UI Kit" -sidebarTitle: "Groups" -description: "Create groups, manage members, assign roles, and transfer ownership in your Flutter chat app" +title: "Group Management" +sidebarTitle: "Group Chat" +description: "Create groups, manage members, assign roles, and transfer ownership in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Create a group -await CometChat.createGroup( - group: Group( - guid: groupId, - name: groupName, - type: groupType, - password: groupPassword, - ), -); - -// Join a group -await CometChat.joinGroup(guid: groupId, groupType: groupType, password: password); - -// Add members -CometChatAddMembers(group: group); - -// Ban/unban members -CometChatBannedMembers(group: group); - -// Change member scope -CometChatChangeScope(group: group, user: user); - -// Transfer ownership -CometChatTransferOwnership(group: group); -``` - -**Key Components:** -- `CometChatGroups` → [Docs](/ui-kit/flutter/groups) -- `CometChatCreateGroup` → Group creation UI -- `CometChatGroupInfo` → Group info screen -- `CometChatAddMembers` → Add members UI -- `CometChatBannedMembers` → Banned members management -- `CometChatTransferOwnership` → Ownership transfer UI -- `JoinProtectedGroupUtils` → Password group join utility (sample app) - -**Sample Implementation:** [group_info/cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) - +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatGroups`, `CometChatCreateGroup`, `CometChatGroupInfo`, `CometChatAddMembers`, `CometChatBannedMembers`, `CometChatTransferOwnership` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | Groups tab → create/join group → `CometChatGroupInfo` for management | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | + -Learn how to create groups, join public/password groups, manage members, ban users, update roles, and transfer group ownership using CometChat UIKit for Flutter. +Group Management enables users to create groups, join public/password groups, manage members, ban users, update roles, and transfer ownership. -## Overview +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -Enable your users to: +--- -- Create or join public/private/password-protected groups -- View and manage group members -- Assign roles and moderate participants -- Transfer group ownership for continuity +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometChatGroups` | Displays groups and create button | +| `CometChatCreateGroup` | UI to create new groups | +| `CometChatGroupInfo` | Shows group info and member management | +| `CometChatAddMembers` | Add members to a group | +| `CometChatBannedMembers` | View/unban banned users | +| `CometChatTransferOwnership` | Transfer group ownership | +| `CometChatChangeScope` | Change a user's group role | +| `JoinProtectedGroupUtils` | Utility to join password-protected groups | -- **CometChat UIKit for Flutter** installed via `pubspec.yaml` -- CometChat initialized with `App ID`, `Region`, and `Auth Key` -- Group chat enabled in your CometChat app -- Navigation set up between group/member screens -- Internet permissions +--- -## Components +## Integration Steps -| Component/Class | Role | -|-----------------------------|------------------------------------------------------| -| `CometChatGroups` | Displays groups and a “create” button | -| `CometChatCreateGroup` | UI to create new groups | -| `CometChatContacts` | Lets users search/join groups | -| `CometChatGroupInfo` | Shows group info and member management options | -| `CometChatAddMembers` | Add members to a group | -| `CometChatBannedMembers` | View/unban banned users | -| `CometChatTransferOwnership`| Transfer group ownership | -| `CometChatChangeScope` | Change a user’s group role | -| `JoinProtectedGroupUtils` | Utility to join password-protected groups | +### 1. Create a Group -## Integration Steps +Show the create group dialog from the dashboard. -### Create a Group +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ ```dart IconButton( @@ -98,171 +57,126 @@ IconButton( ); }, icon: Icon(Icons.group_add), -); +) ``` +_File: [cometchat_create_group.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/create_group/cometchat_create_group.dart)_ + ```dart -ElevatedButton( - onPressed: () async { - await CometChat.createGroup( - group: Group( - guid: groupId, - name: groupName, - type: groupType, - password: groupPassword, - ), - onSuccess: (Group group) => Navigator.pop(context), - onError: (e) { - // Show error - }, - ); +await CometChat.createGroup( + group: Group( + guid: groupId, + name: groupName, + type: groupType, + password: groupPassword, + ), + onSuccess: (Group group) => Navigator.pop(context), + onError: (e) { + // Show error }, - child: Text('Create Group'), ); ``` -📄 [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) - --- -### Join Public/Password Group +### 2. Join Public/Password Group + +Handle group tap to join or prompt for password. + +_File: [join_protected_group_util.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/join_protected_group_util.dart)_ ```dart CometChatGroups( onItemTap: (context, group) { - JoinProtectedGroupUtils.onGroupItemTap(context, group, ...); + JoinProtectedGroupUtils.onGroupItemTap(context, group); }, -); +) ``` -```dart -if (group.type == GroupType.password) { - // Show password prompt - // Join via CometChat.joinGroup with password -} -``` +--- -📄 [`join_protected_group_util.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/join_protected_group_util.dart) +### 3. View Group Info ---- +Display group details and member management options. -### View Members +_File: [cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart)_ ```dart CometChatGroupInfo( group: group, -); +) ``` -📄 [`group_info/cometchat_group_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) - --- -### Add Members +### 4. Add Members + +Navigate to add members screen. + +_File: [cometchat_add_members.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/add_memebers/cometchat_add_members.dart)_ ```dart CometChatAddMembers( group: group, -); +) ``` -📄 [`add_members/cometchat_add_members.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/add_members/cometchat_add_members.dart) - --- -### Ban/Unban Members +### 5. Ban/Unban Members + +Manage banned members list. + +_File: [cometchat_banned_members.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/banned_members/cometchat_banned_members.dart)_ ```dart CometChatBannedMembers( group: group, -); +) ``` -📄 [`banned_members/cometchat_banned_members.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/banned_members/cometchat_banned_members.dart) - --- -### Change Member Scope +### 6. Transfer Ownership -```dart -CometChatChangeScope( - group: group, - user: user, -); -``` - -📄 [`group_info/cometchat_group_info_controller.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info_controller.dart) - ---- +Transfer group ownership to another member. -### Transfer Ownership +_File: [cometchat_transfer_ownership.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/transfer_ownership/cometchat_transfer_ownership.dart)_ ```dart CometChatTransferOwnership( group: group, -); +) ``` -📄 [`transfer_ownership/cometchat_transfer_ownership.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/transfer_ownership/cometchat_transfer_ownership.dart) - --- -## Implementation Flow - -1. User creates or joins a group -2. Admin views group info and member list -3. Admin can add, ban, change scope, or transfer ownership - -## Customization Options +## Feature Matrix -- Modify theme using CometChat UIKit theming APIs -- Add logic to validate group name or enforce limits -- Adjust member filters or role options as needed +| Feature | Component / Method | File | +|:---|:---|:---| +| Create group | `CometChatCreateGroup` | [cometchat_create_group.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/create_group/cometchat_create_group.dart) | +| Join group | `JoinProtectedGroupUtils` | [join_protected_group_util.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/join_protected_group_util.dart) | +| View members | `CometChatGroupInfo` | [cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | +| Add members | `CometChatAddMembers` | [cometchat_add_members.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/add_memebers/cometchat_add_members.dart) | +| Ban/unban | `CometChatBannedMembers` | [cometchat_banned_members.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/banned_members/cometchat_banned_members.dart) | +| Transfer ownership | `CometChatTransferOwnership` | [cometchat_transfer_ownership.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/transfer_ownership/cometchat_transfer_ownership.dart) | -## Filtering / Edge Cases - -- Filter by roles or banned status -- Prevent duplicate group IDs -- Prevent banning owner or transferring to non-member - -## Error Handling & Blocked Users - -- Show UI feedback (SnackBars) on failure -- Blocked users cannot be added or may be auto-banned -- Retry logic for failed actions (create, join, etc.) - -## Group Type Notes - -- Public: anyone can join -- Password: prompt required -- Private: invite-only -- Only admins can ban, change roles, or transfer ownership - -## Summary / Feature Matrix - -| Feature | Component / Method | File Path | -|---------------------|----------------------------------|-----------------------------------------------------| -| Create group | `CometChatCreateGroup` | `create_group/cometchat_create_group.dart` | -| Join group | `CometChatGroups`, `JoinProtectedGroupUtils` | `contacts/cometchat_contacts_controller.dart`, `utils/join_protected_group_util.dart` | -| View members | `CometChatGroupInfo` | `group_info/cometchat_group_info.dart` | -| Add members | `CometChatAddMembers` | `add_members/cometchat_add_members.dart` | -| Ban/unban members | `CometChatBannedMembers` | `banned_members/cometchat_banned_members.dart` | -| Change scope | `CometChatChangeScope` | `group_info/cometchat_group_info.dart` | -| Transfer ownership | `CometChatTransferOwnership` | `transfer_ownership/cometchat_transfer_ownership.dart` | +--- ## Next Steps - - Learn more about the Groups component + + Learn more about the Groups component. - - Display and manage group members + + Display and manage group members. - - View group conversations + + View group conversations. - - Explore other implementation guides + + Browse all feature and formatter guides. diff --git a/ui-kit/flutter/guide-message-agentic-flow.mdx b/ui-kit/flutter/guide-message-agentic-flow.mdx index 545f64be1..2b3c9144c 100644 --- a/ui-kit/flutter/guide-message-agentic-flow.mdx +++ b/ui-kit/flutter/guide-message-agentic-flow.mdx @@ -1,467 +1,197 @@ --- title: "AI Agent Integration" sidebarTitle: "AI Agent Integration" -description: "Integrate AI agents with chat history, contextual responses, and seamless handoffs in your Flutter app" +description: "Integrate AI agents with chat history, contextual responses, and seamless handoffs in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Check if user is an AI agent -bool isUserAgentic() { - return widget.user?.role == AIConstants.aiRole; -} +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatAIAssistantChatHistory`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | AI agent user → `AIAssistantChatScreen` with AI-specific styling | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -// AI Assistant chat screen -AIAssistantChatScreen( - user: aiUser, - group: group, - parentMessage: message, - isHistory: true, -); - -// AI chat history -CometChatAIAssistantChatHistory( - user: widget.user, - group: widget.group, - onNewChatButtonClicked: () => onNewChatClicked(true), - onMessageClicked: (message) => navigateToThread(message), -); - -// Custom AI bubble styling -CometChatAiAssistantBubbleStyle( - backgroundColor: Colors.transparent, - border: Border.all(color: Colors.blueAccent), - textColor: Color(0xFF141414), -); -``` + -**Key Components:** -- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) -- `CometChatMessageComposer` → [Docs](/ui-kit/flutter/message-composer) -- `CometChatMessageHeader` → [Docs](/ui-kit/flutter/message-header) -- `CometChatAIAssistantChatHistory` → [Docs](/ui-kit/flutter/ai-assistant-chat-history) -- `CometChatAiAssistantBubbleStyle` → AI bubble styling -- `AIConstants.aiRole` → AI role constant +AI Agent Integration enables intelligent conversational AI capabilities with chat history, contextual responses, and seamless handoffs. -**Sample Implementation:** Custom AI Assistant chat screen (see guide for full implementation) - +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. +--- -Enable intelligent conversational AI capabilities in your Android app using CometChat UIKit v5 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 offers 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. +## Components - - - +| Component / Class | Role | +|:---|:---| +| `CometChatMessageHeader` | Manages message interactions with AI-specific buttons | +| `CometChatMessageList` | Displays messages with AI-specific styling | +| `CometChatMessageComposer` | Composes messages with AI placeholders | +| `CometChatAIAssistantChatHistory` | Displays previous AI conversation history | +| `CometChatAiAssistantBubbleStyle` | Custom styling for AI chat bubbles | +| `AIConstants.aiRole` | Constant to detect AI agent users | -## Prerequisites +--- -- **CometChat UIKit for Flutter** installed via `pubspec.yaml` -- CometChat initialized with `App ID`, `Region`, and `Auth Key` -- Message chat enabled in your CometChat app -- Navigation set up between message and user/group screens -- Internet permissions +## Integration Steps -## Components +### 1. Detect AI Agent -| Component/Class | Role | -|------------------------------ |------------------------------------------------------| -| `CometChatMessageHeader` | Manages message interactions and state | -| `CometChatMessageList` | Displays a list of messages | -| `CometChatMessageComposer` | Composes and sends new messages | -| `CometChatAIAssistantChatHistory` | Displays previous AI conversation history. | +Check if the user is an AI agent by their role. +```dart +bool isUserAgentic() { + return widget.user?.role == AIConstants.aiRole; +} +``` -## Integration Steps +--- -### Step 1 - Screen Setup +### 2. AI Chat Screen Setup -Create a screen for AI Assistant chat using `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer`. +Create a screen for AI Assistant chat using standard message components with AI-specific styling. - - ```dart -import 'package:flutter/material.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart' as cc; - class AIAssistantChatScreen extends StatefulWidget { final User? user; final Group? group; final BaseMessage? parentMessage; final bool? isHistory; - const AIAssistantChatScreen( - {Key? key, this.user, this.group, this.parentMessage, this.isHistory}) - : super(key: key); + const AIAssistantChatScreen({ + Key? key, + this.user, + this.group, + this.parentMessage, + this.isHistory, + }) : super(key: key); @override State createState() => _AIAssistantChatScreenState(); } +``` -class _AIAssistantChatScreenState extends State { - late CometChatColorPalette colorPalette; - late CometChatTypography typography; - late CometChatSpacing spacing; - - @override - void initState() { - super.initState(); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - typography = CometChatThemeHelper.getTypography(context); - colorPalette = CometChatThemeHelper.getColorPalette(context); - spacing = CometChatThemeHelper.getSpacing(context); - } - - bool isUserAgentic() { - return widget.user?.role == AIConstants.aiRole; - } +--- - @override - Widget build(BuildContext context) { - final ccColor = CometChatThemeHelper.getColorPalette(context); - return Scaffold( - backgroundColor: ccColor.background1, - appBar: CometChatMessageHeader( - user: widget.user, - group: widget.group, - messageHeaderStyle: CometChatMessageHeaderStyle( - backgroundColor: - (isUserAgentic()) ? ccColor.background1 : null, - border: (isUserAgentic()) - ? Border( - bottom: BorderSide( - color: ccColor.borderLight ?? Colors.transparent, - width: 1.0, - ), - ) - : null, - statusIndicatorStyle: CometChatStatusIndicatorStyle( - backgroundColor: colorPalette.transparent, - borderRadius: BorderRadius.zero, - border: Border.all( - width: 0, - color: colorPalette.transparent ?? Colors.transparent, - ), - ), - ), - onBack: () { - FocusManager.instance.primaryFocus?.unfocus(); - Navigator.of(context).pop(); - }, - chatHistoryButtonClick: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatAIAssistantChatHistory( - user: widget.user, - group: widget.group, - onNewChatButtonClicked: () { - onNewChatClicked(true); - }, - onMessageClicked: (message) { - if (message != null) { - Navigator.of(context) - ..pop() - ..pop(); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => AIAssistantChatScreen( - user: widget.user, - group: widget.group, - parentMessage: message, - isHistory: true, - ), - ), - ); - } - }, - onClose: () { - Navigator.of(context).pop(); - }, - ), - ), - ); - }, - newChatButtonClick: () { - onNewChatClicked(false); - }, - ), - resizeToAvoidBottomInset: true, - body: Container( - color: ccColor.background3, - child: Column( - children: [ - Expanded( - child: GestureDetector( - onTap: () => FocusScope.of(context).unfocus(), - child: getMessageList( - user: widget.user, - group: widget.group, - context: context, - parentMessage: widget.parentMessage, - ), - ), - ), - getComposer(), - ], - ), - ), - ); - ; - } - - Widget getComposer() { - bool agentic = isUserAgentic(); - return CometChatMessageComposer( - user: widget.user, - group: widget.group, - disableMentions: (agentic) ? true : false, - placeholderText: - (agentic) ? "${cc.Translations.of(context).askAnything}..." : null, - parentMessageId: widget.parentMessage?.id ?? 0, - messageComposerStyle: CometChatMessageComposerStyle( - dividerColor: agentic ? Colors.transparent : null, - dividerHeight: agentic ? 0 : null, - backgroundColor: agentic ? colorPalette.background1 : null, - ), - ); - } +### 3. Message Header with AI Actions - onNewChatClicked(bool isHistory) async { - if (isHistory) { - Navigator.of(context).pop(); - } +Configure the message header with chat history and new chat buttons. - Navigator.pushReplacement( +```dart +CometChatMessageHeader( + user: widget.user, + group: widget.group, + chatHistoryButtonClick: () { + Navigator.push( context, MaterialPageRoute( - builder: (context) => AIAssistantChatScreen( + builder: (context) => CometChatAIAssistantChatHistory( user: widget.user, group: widget.group, + onNewChatButtonClicked: () => onNewChatClicked(true), + onMessageClicked: (message) => navigateToThread(message), + onClose: () => Navigator.of(context).pop(), ), ), ); - } - - Widget getMessageList({ - User? user, - Group? group, - context, - BaseMessage? parentMessage, - }) { - MessagesRequestBuilder? requestBuilder = MessagesRequestBuilder(); - - if (widget.isHistory != null && - widget.isHistory == true && - parentMessage != null && - isUserAgentic()) { - requestBuilder = MessagesRequestBuilder() - ..parentMessageId = parentMessage.id - ..withParent = true - ..hideReplies = true; - } - - return CometChatMessageList( - user: user, - group: group, - hideReplyInThreadOption: (isUserAgentic()) ? true : false, - hideThreadView: true, - messagesRequestBuilder: requestBuilder, - style: CometChatMessageListStyle( - backgroundColor: (isUserAgentic()) ? colorPalette.background3 : null, - outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( - textBubbleStyle: CometChatTextBubbleStyle( - backgroundColor: - (isUserAgentic()) ? colorPalette.background4 : null, - textColor: (isUserAgentic()) ? colorPalette.textPrimary : null, - messageBubbleDateStyle: CometChatDateStyle( - textColor: (isUserAgentic()) ? colorPalette.neutral600 : null, - ), - ), - messageBubbleDateStyle: CometChatDateStyle( - textColor: (isUserAgentic()) ? colorPalette.textPrimary : null, - ), - ), - ), - ); - } -} + }, + newChatButtonClick: () => onNewChatClicked(false), +) ``` - - - - - -### Step 2 - Chat History Screen +--- -Create a screen for AI Assistant chat history using CometChatAIAssistantChatHistory. +### 4. AI Message List -Add the following code inside your widget to navigate to the chat history screen when the user taps a button or icon. +Configure the message list with AI-specific styling and options. - - ```dart -chatHistoryButtonClick: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatAIAssistantChatHistory( - user: widget.user, - group: widget.group, - onNewChatButtonClicked: () { - onNewChatClicked(true); - }, - onMessageClicked: (message) { - if (message != null) { - Navigator.of(context) - ..pop() // Close ChatHistory - ..pop(); // Close current AI screen - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => AIAssistantChatScreen( - user: widget.user, - group: widget.group, - parentMessage: message, - isHistory: true, - ), - ), - ); - } - }, - onClose: () { - Navigator.of(context).pop(); - }, +CometChatMessageList( + user: user, + group: group, + hideReplyInThreadOption: isUserAgentic() ? true : false, + hideThreadView: true, + messagesRequestBuilder: requestBuilder, + style: CometChatMessageListStyle( + backgroundColor: isUserAgentic() ? colorPalette.background3 : null, + outgoingMessageBubbleStyle: CometChatOutgoingMessageBubbleStyle( + textBubbleStyle: CometChatTextBubbleStyle( + backgroundColor: isUserAgentic() ? colorPalette.background4 : null, + textColor: isUserAgentic() ? colorPalette.textPrimary : null, ), ), - ); -}, + ), +) ``` - - - - -This integration opens the AI Assistant Chat History screen, allowing users to: -- Browse their previous AI chat sessions. -- Resume a previous conversation (onMessageClicked). -- Start a new chat session (onNewChatButtonClicked). -- Close the chat history view (onClose). - -### Step 3 - Custom Styles +--- -Define custom styles for AI chat bubbles and the composer by using a ThemeExtension (CometChatAiAssistantBubbleStyle). +### 5. AI Composer +Configure the composer with AI-specific placeholder text. - - ```dart -import 'package:flutter/material.dart'; -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -void main() { - runApp(const MyApp()); -} - -class MyApp extends StatelessWidget { - const MyApp({super.key}); - - @override - Widget build(BuildContext context) { - return MaterialApp( - title: 'AI Chat Demo', - theme: ThemeData( - // Add your custom AI Assistant bubble styles here - extensions: [ - CometChatAiAssistantBubbleStyle( - backgroundColor: Colors.transparent, - border: Border.all(color: Colors.blueAccent, width: 1), - textColor: const Color(0xFF141414), - textStyle: const TextStyle( - fontFamily: 'TimesNewRoman', // Add this in pubspec.yaml under fonts - ), - ), - ], - ), - home: const AIAssistantChatScreen(), - ); - } -} +CometChatMessageComposer( + user: widget.user, + group: widget.group, + disableMentions: isUserAgentic() ? true : false, + placeholderText: isUserAgentic() + ? "${Translations.of(context).askAnything}..." + : null, + parentMessageId: widget.parentMessage?.id ?? 0, +) ``` - - - +--- -## Implementation Flow Summary +### 6. Custom AI Bubble Styling -| Step | Action | -|:-----|:-------------------------------------------- | -| 1 | User selects AI agent from chat list | -| 2 | `AIAssistantChatScreen` launches | -| 3 | Parse User data and detect agent chat (Role of user must be "@agentic") | -| 4 | Initialize UI with AI-specific styling | -| 6 | Configure chat history and navigation | -| 7 | Launch chat with AI agent | +Apply custom styles for AI chat bubbles using ThemeExtension. -## Customization Options +```dart +MaterialApp( + theme: ThemeData( + extensions: [ + CometChatAiAssistantBubbleStyle( + backgroundColor: Colors.transparent, + border: Border.all(color: Colors.blueAccent, width: 1), + textColor: const Color(0xFF141414), + ), + ], + ), +) +``` -- **Custom AI Assistant Empty Chat View:** Customize the empty state view using `emptyStateView`. -- **Streaming Speed:** Adjust AI response streaming speed via `streamingSpeed`. -- **AI Assistant Suggested Messages:** Create custom list of suggested messages and set quick prompts using `suggestedMessages`. -- **AI Assistant Tools:** Set tools for the AI agent using `setAiAssistantTools` callback. +--- ## Feature Matrix -| Feature | Implementation | UI Component | -|:-----------------------|:-------------------------------------------- |:------------------------| -| AI Chat | `AIAssistantChatScreen` | Full chat screen | -| Chat History | `CometChatAIAssistantChatHistory` | Chat history screen | +| Feature | Component / Method | Description | +|:---|:---|:---| +| AI detection | `AIConstants.aiRole` | Check if user is AI agent | +| AI chat screen | `AIAssistantChatScreen` | Full AI chat interface | +| Chat history | `CometChatAIAssistantChatHistory` | Browse previous AI sessions | +| AI styling | `CometChatAiAssistantBubbleStyle` | Custom AI bubble appearance | +| New chat | `onNewChatClicked()` | Start fresh AI conversation | --- ## Next Steps - - Explore all AI-powered features + + Explore all AI-powered features. - - Learn about message display and management + + Learn about AI chat history component. - - Compose messages with AI assistance + + Learn about message display and management. - - Explore other implementation guides + + Browse all feature and formatter guides. - \ No newline at end of file + diff --git a/ui-kit/flutter/guide-message-privately.mdx b/ui-kit/flutter/guide-message-privately.mdx index 245dbbf32..647f90925 100644 --- a/ui-kit/flutter/guide-message-privately.mdx +++ b/ui-kit/flutter/guide-message-privately.mdx @@ -1,163 +1,151 @@ --- -title: "Message a User Privately from a Group Chat" +title: "Message Privately" sidebarTitle: "Message Privately" -description: "Initiate private one-on-one chats with group members directly from group chat" +description: "Initiate private one-on-one chats with group members directly from group chat in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Navigate to user info from group chat -IconButton( - icon: Icon(Icons.info_outline), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatUserInfo(user: user), - ), - ); - }, -); - -// Start private chat with user -ElevatedButton( - onPressed: () { - PageManager().navigateToMessages( - context: context, - user: user, - ); - }, - child: Text('Message'), -); -``` +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometchatUserInfo`, `CometChatMessageList`, `PageManager` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | Group member tap → `CometchatUserInfo` → "Message" action | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -**Key Components:** -- `CometChatUserInfo` → User profile screen -- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) -- `PageManager` → Navigation utility (sample app) + -**Sample Implementation:** [user_info/cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) - +Message Privately lets users start a direct one-on-one chat with a group member without leaving the group context. +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -Learn how to initiate a private one-on-one chat with a group member directly from a group chat screen. - -## Overview +--- -This feature allows users to start a private, direct chat with a member of a group without leaving the group chat context. It enables seamless, context-aware private conversations, improving collaboration and user experience. Users can tap on a group member to instantly open a private chat. +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometChatMessageList` | Displays group messages and user avatars | +| `CometchatUserInfo` | Shows user details and actions (e.g., call, message) | +| `CometChatUserInfoController` | Manages user info state and actions | +| `PageManager` | Handles navigation to the private chat screen | -- A Flutter project with **CometChat UIKit Flutter v5** installed -- CometChat credentials (`appID`, `region`, `authKey`) initialized -- Group chat and user info screens implemented -- Navigation setup for moving between group and private chat screens +--- -## Components +## Integration Steps -| Component / Class | Role | -|:-------------------------------------|:---------------------------------------------------------------| -| `CometChatMessageList` | Displays group messages and user avatars | -| `CometChatUserInfo` | Shows user details and actions (e.g., "Message" button) | -| `PageManager` | Handles navigation to the private chat screen | -| `lib/messages.dart` | Main chat screen logic | -| `lib/user_info/cometchat_user_info.dart` | User info and action UI | +### 1. Navigate to User Info -## Integration Steps +Open the user info screen when tapping on a group member's profile or info icon. -### Add User Info/Action in Group Chat +_File: [cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart)_ -Allow users to view group member info and provide a "Message" action. ```dart -IconButton( - icon: Icon(Icons.info_outline), - onPressed: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatUserInfo(user: user), - ), - ); - }, +Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometchatUserInfo(user: selectedUser), + ), ); ``` -**File reference:** -[`lib/group_info/cometchat_group_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) +--- + +### 2. Display User Profile with Actions + +The `CometchatUserInfo` widget displays the user's profile with action tiles for voice call, video call, and messaging. -### Handle Private Message Navigation +_File: [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart)_ -Start a private chat with the selected user. ```dart -ElevatedButton( - onPressed: () { - PageManager().navigateToMessages( - context: context, - user: user, - ); - }, - child: Text('Message'), -); +Widget _getOptionTiles(CometChatUserInfoController controller) { + return Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + tile( + Icon(Icons.call_outlined, color: colorPalette.iconHighlight), + Translations.of(context).voice, + () => controller.initiateCallWorkflow(CallTypeConstants.audioCall, context), + ), + tile( + Icon(Icons.videocam_outlined, color: colorPalette.iconHighlight), + Translations.of(context).video, + () => controller.initiateCallWorkflow(CallTypeConstants.videoCall, context), + ), + ], + ); +} ``` -**File reference:** -[`lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) +--- -## Implementation Flow +### 3. Start Private Chat -1. User taps a group member’s avatar or info icon -2. `CometChatUserInfo` screen opens -3. User taps "Message" -4. App navigates to the private chat screen with that user +Navigate to the private chat screen using `PageManager` when the user wants to message privately. -## Customization Options +_File: [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart)_ -- **Styling:** Customize the user info screen and action buttons using UIKit theming -- **APIs:** Add more actions (e.g., block, view profile) in the user info screen -- **Configuration:** Control which users can be messaged (e.g., block list, admin-only) +```dart +PageManager().navigateToMessages( + context: context, + user: user, +); +``` -## Filtering / Edge Cases +--- -- **Exclude Blocked Users:** Remove blocked users from selection -- **Existing Conversation:** Navigate to an existing private chat if one exists -- **User Blocked:** Disable the "Message" button if the user is blocked +### 4. Handle Mentions Navigation -## Error Handling & Blocked-User-Handling +When a user taps on a mention in a message, navigate to that user's profile or start a private chat. -- **UI States:** Disable the message button and show a tooltip if a user is blocked -- **Feedback:** Use `SnackBar` or `Toast` for error messages (e.g., "Cannot message this user") -- **Retry Logic:** Allow retrying navigation if a network error occurs +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -## Optional Context-Specific Notes +```dart +CometChatMentionsFormatter getMentionsTap() { + return CometChatMentionsFormatter( + user: widget.user, + group: widget.group, + onMentionTap: (mention, mentionedUser, {message}) { + if (mentionedUser.uid != CometChatUIKit.loggedInUser!.uid) { + PageManager().navigateToMessages( + context: context, + user: mentionedUser, + ); + } + }, + ); +} +``` -- **Group vs. User:** This flow applies only to group members; use the standard new chat flow for users outside the group +--- + +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| User info screen | `CometchatUserInfo` | [cometchat_user_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | +| Voice/video call | `initiateCallWorkflow()` | [cometchat_user_info_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info_controller.dart) | +| Navigate to chat | `PageManager.navigateToMessages` | [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | +| Mention tap | `CometChatMentionsFormatter` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Access from group | Group member list | [cometchat_group_info.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | -| Feature | Component / Method | File(s) | -|:------------------------|:---------------------------------|:---------------------------------------------------------------------| -| Show user info | `CometChatUserInfo` | [`lib/group_info/cometchat_group_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/group_info/cometchat_group_info.dart) | -| Message user | `PageManager.navigateToMessages` | [`lib/user_info/cometchat_user_info.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/user_info/cometchat_user_info.dart) | -| Access from group | Avatar/IconButton | [`lib/messages.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) | +--- ## Next Steps - - Display and manage group lists + + Display and manage group lists. - - View and manage group members + + View and manage group members. - - Display messages in private chats + + Display messages in private chats. - - Explore other implementation guides + + Browse all feature and formatter guides. - \ No newline at end of file +
diff --git a/ui-kit/flutter/guide-new-chat.mdx b/ui-kit/flutter/guide-new-chat.mdx index c337f3fce..48027ccc3 100644 --- a/ui-kit/flutter/guide-new-chat.mdx +++ b/ui-kit/flutter/guide-new-chat.mdx @@ -1,83 +1,50 @@ --- -title: "New Chat / Create Conversation in Your Flutter Chat App" +title: "New Chat" sidebarTitle: "New Chat" -description: "Enable users to start one-on-one or group chats with a searchable contact list" +description: "Enable users to start one-on-one or group chats with a searchable contact list in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Add avatar menu with "Create Conversation" option -PopupMenuButton( - icon: CometChatAvatar( - image: CometChatUIKit.loggedInUser?.avatar, - name: CometChatUIKit.loggedInUser?.name, - ), - itemBuilder: (context) => [ - PopupMenuItem(value: '/Create', child: Text("Create Conversation")), - ], - onSelected: (value) { - if (value == '/Create') { - Navigator.push( - context, - MaterialPageRoute(builder: (context) => CometChatContacts()), - ); - } - }, -); - -// Handle user/group selection -CometChatUsers( - onItemTap: (context, user) => PageManager.navigateToMessages(context: context, user: user), -); -``` +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatContacts`, `CometChatUsers`, `CometChatGroups`, `CometChatAvatar` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | Avatar menu → "Create Conversation" → `CometChatContacts` | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -**Key Components:** -- `CometChatAvatar` → Avatar display widget -- `CometChatContacts` → Contact selection screen -- `CometChatUsers` → [Docs](/ui-kit/flutter/users) -- `CometChatGroups` → [Docs](/ui-kit/flutter/groups) -- `CometChatContactsController` → Tab switching controller (sample app) + -**Sample Implementation:** [contacts/cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) - +New Chat enables users to start one-on-one or group conversations by selecting from a searchable contact list. +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -Enable users to start one-on-one or group chats by integrating CometChat’s avatar menu and `CometChatContacts` screen, providing a seamless flow from the dashboard to a conversation. - -## Overview +--- -- Users can start a new one-on-one or group chat by tapping the avatar in the top bar, selecting “Create Conversation,” and choosing a contact from a searchable list. -- Streamlines finding contacts or groups and initiating conversations, improving user experience and engagement. -- Quick creation or opening of chats directly from the main screen. +## Components -## Prerequisites +| Component / Class | Role | +|:---|:---| +| `CometChatAvatar` | Displays the user avatar in the app bar | +| `PopupMenuButton` | Shows menu options when the avatar is tapped | +| `CometChatContacts` | UI for the "Start Conversation" screen with tabs | +| `CometChatContactsController` | Manages tab switching and item selection | +| `CometChatUsers` | Lists users with search and selection | +| `CometChatGroups` | Lists groups with search and selection | +| `PageManager` | Handles navigation to the chat screen | -- Flutter project with **CometChat UIKit Flutter v5** installed -- CometChat credentials (`appID`, `region`, `authKey`) initialized -- Navigation configured in your app -- Internet/network permissions granted +--- -## Components +## Integration Steps -| Component / Class | Role | -|:-------------------------------|:--------------------------------------------------------------| -| `CometChatAvatar` | Displays the user avatar in the app bar | -| `PopupMenuButton` | Shows menu options when the avatar is tapped | -| `CometChatContacts` | UI for the “Start Conversation” screen | -| `CometChatContactsController` | Manages tab switching and item selection | -| `CometChatUsers` / `CometChatGroups` | Lists users or groups with search and selection | -| `PageManager` | Handles navigation to the chat screen | +### 1. Add Avatar Menu -## Integration Steps +Show the avatar in the app bar and open a menu on tap with "Create Conversation" option. -### Add Avatar Menu +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ -Show the avatar in the app bar and open a menu on tap. ```dart PopupMenuButton( icon: CometChatAvatar( @@ -90,17 +57,24 @@ PopupMenuButton( PopupMenuItem(value: '/Create', child: Text("Create Conversation")), ], onSelected: (value) { - if (value == '/Create') openCreateConversation(context); + if (value == '/Create') { + Navigator.push( + context, + MaterialPageRoute(builder: (context) => CometChatContacts()), + ); + } }, ); ``` -**File reference:** -[`sample_app/lib/dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) +--- + +### 2. Open Contacts Screen -### Open Start Conversation Screen +Navigate to the `CometChatContacts` screen which provides tabs for Users and Groups. + +_File: [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart)_ -Navigate to the “Start Conversation” screen when “Create Conversation” is selected. ```dart void openCreateConversation(BuildContext context) { Navigator.push( @@ -110,33 +84,34 @@ void openCreateConversation(BuildContext context) { } ``` -**File reference:** -[`sample_app/lib/dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) +--- + +### 3. Handle User/Group Selection + +Wire up the `onItemTap` callback to navigate to the chat screen when a user or group is selected. -### Select User or Group +_File: [cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart)_ -Let the user pick a contact or group to chat with. ```dart -CometChatContactsController( - currentView: [ - CometChatUsers( - hideAppbar: true, - onItemTap: (context, user) => _onItemTap(context: context, user: user), - ), - CometChatGroups( - hideAppbar: true, - onItemTap: (context, group) => _onItemTap(context: context, group: group), - ), - ], +CometChatUsers( + hideAppbar: true, + onItemTap: (context, user) => _onItemTap(context: context, user: user), +); + +CometChatGroups( + hideAppbar: true, + onItemTap: (context, group) => _onItemTap(context: context, group: group), ); ``` -**File reference:** -[`sample_app/lib/contacts/cometchat_contacts_controller.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) +--- + +### 4. Navigate to Chat + +Open the chat screen for the selected user or group using `PageManager`. -### Navigate to Chat +_File: [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart)_ -Open the chat screen for the selected user or group. ```dart void _onItemTap({required BuildContext context, User? user, Group? group}) { if (user != null) { @@ -147,62 +122,34 @@ void _onItemTap({required BuildContext context, User? user, Group? group}) { } ``` -**File reference:** -[`sample_app/lib/utils/page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) - -## Implementation Flow - -1. User taps avatar → menu opens -2. User selects “Create Conversation” → navigates to `CometChatContacts` -3. User searches and selects a user or group → triggers `_onItemTap` -4. App navigates to the chat screen for the selected user or group - -## Customization Options - -- **Styling:** Customize avatar, menu, and contact list appearance via UIKit theming -- **APIs:** Use callbacks like `onSearch` and `onItemTap` for custom logic -- **Configuration:** Adjust tab visibility, search placeholder, or add custom menu actions - -## Filtering / Edge Cases - -- **Filtering:** `CometChatUsers` and `CometChatGroups` provide real-time search -- **Empty Results:** Display an empty state if no matches are found -- **Blocked Users:** Exclude blocked users from search and messaging - -## Error Handling & Blocked-User Handling - -- **UI States:** Default UIKit states handle network errors or empty results -- **Feedback:** Use `SnackBar` or `Toast` for custom error messages -- **Blocked Users:** Blocked users cannot be selected or messaged - -## Optional Context-Specific Notes +--- -- **User vs. Group:** The flow is identical; only the data source changes +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| Avatar menu | `PopupMenuButton`, `CometChatAvatar` | [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | +| Contacts screen | `CometChatContacts` | [dashboard.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | +| List users | `CometChatUsers` | [cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) | +| List groups | `CometChatGroups` | [cometchat_contacts_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) | +| Handle selection | `_onItemTap` | [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | +| Navigate to chat | `PageManager.navigateToMessages` | [page_manager.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | -| Feature | Component / Method | File(s) | -|------------------------|-------------------------------------------------|-------------------------------------------------| -| Show avatar/menu | `PopupMenuButton`, `CometChatAvatar` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | -| Open conversation UI | `CometChatContacts` | [`dashboard.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/dashboard.dart) | -| List/search users | `CometChatUsers` | [`cometchat_contacts_controller.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) | -| List/search groups | `CometChatGroups` | [`cometchat_contacts_controller.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/contacts/cometchat_contacts_controller.dart) | -| Handle selection | `_onItemTap` | [`page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | -| Navigate to chat | `PageManager.navigateToMessages` | [`page_manager.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/utils/page_manager.dart) | +--- ## Next Steps - - Display and search user lists + + Display and search user lists. - - Display and manage group lists + + Display and manage group lists. - - View and manage conversation history + + View and manage conversation history. - - Explore other implementation guides + + Browse all feature and formatter guides. - \ No newline at end of file +
diff --git a/ui-kit/flutter/guide-overview.mdx b/ui-kit/flutter/guide-overview.mdx index 0cecb9a9c..46f3dc93b 100644 --- a/ui-kit/flutter/guide-overview.mdx +++ b/ui-kit/flutter/guide-overview.mdx @@ -4,32 +4,17 @@ sidebarTitle: "Overview" description: "Task-oriented feature guides for implementing specific capabilities in the Flutter UI Kit" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -Available implementation guides for Flutter UI Kit: +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Purpose | Index of task-oriented feature guides for the Flutter UI Kit | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Components | [Components Overview](/ui-kit/flutter/components-overview) | +| Guides | [Block/Unblock](/ui-kit/flutter/guide-block-unblock-user) · [Call Log Details](/ui-kit/flutter/guide-call-log-details) · [Group Chat](/ui-kit/flutter/guide-group-chat) · [Message Privately](/ui-kit/flutter/guide-message-privately) · [New Chat](/ui-kit/flutter/guide-new-chat) · [Search Messages](/ui-kit/flutter/guide-search-messages) · [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) · [AI Agent](/ui-kit/flutter/guide-message-agentic-flow) | -**Feature Guides:** -- [Threaded Messages](/ui-kit/flutter/guide-threaded-messages) → `CometChatThreadedMessageList` -- [Block/Unblock User](/ui-kit/flutter/guide-block-unblock-user) → `CometChatUIKit.blockUsers()` -- [New Chat](/ui-kit/flutter/guide-new-chat) → `CometChatContacts` -- [Message Privately](/ui-kit/flutter/guide-message-privately) → `CometChatUserInfo` -- [Search Messages](/ui-kit/flutter/guide-search-messages) → `CometChatSearch` -- [Group Management](/ui-kit/flutter/guide-group-chat) → `CometChatGroups` -- [Call Log Details](/ui-kit/flutter/guide-call-log-details) → `CometChatCallLogs` -- [AI Agent Integration](/ui-kit/flutter/guide-message-agentic-flow) → `CometChatAIAssistantChatHistory` - -**Formatter Guides:** -- [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) → `CometChatTextFormatter` -- [Mentions Formatter](/ui-kit/flutter/mentions-formatter-guide) → `CometChatMentionsFormatter` -- [URL Formatter](/ui-kit/flutter/url-formatter-guide) → `CometChatUrlFormatter` -- [Shortcut Formatter](/ui-kit/flutter/shortcut-formatter-guide) → `ShortcutFormatter` - -**Sample App:** [GitHub Repository](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) - -Each guide provides end-to-end implementation with code examples and component references. - + This page indexes focused, task‑oriented feature guides for the Flutter UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UI kit components. diff --git a/ui-kit/flutter/guide-threaded-messages.mdx b/ui-kit/flutter/guide-threaded-messages.mdx index 510f2dc63..967135bdc 100644 --- a/ui-kit/flutter/guide-threaded-messages.mdx +++ b/ui-kit/flutter/guide-threaded-messages.mdx @@ -1,212 +1,194 @@ --- title: "Threaded Messages" sidebarTitle: "Threaded Messages" -description: "Enable threaded replies in your Flutter chat app with focused sub-conversations" +description: "Implement threaded message replies with parent context, reply list, and focused thread composer in CometChat Flutter UI Kit." --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key components | `CometChatThread`, `CometChatThreadedHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Entry point | `CometChatMessageList.onThreadRepliesClick` opens thread view from messages | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [All Guides](/ui-kit/flutter/guide-overview) | -// Enable thread replies in message list -CometChatMessageList( - onThreadRepliesClick: (BaseMessage message) { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => CometChatThread(parentMessage: message), - ), - ); - }, -); - -// Display threaded messages -CometChatThreadedMessageList( - parentMessageId: parentMessage.id, -); + -// Send threaded reply -CometChatMessageComposer( - parentMessageId: parentMessage.id, -); -``` +Threaded messages let users create sub-conversations by replying to specific messages. This reduces clutter and keeps discussions focused. -**Key Components:** -- `CometChatMessageList` → [Docs](/ui-kit/flutter/message-list) -- `CometChatThreadedMessageList` → Displays threaded messages -- `CometChatMessageComposer` → [Docs](/ui-kit/flutter/message-composer) -- `CometChatThreadedHeader` → [Docs](/ui-kit/flutter/threaded-messages-header) +Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. -**Sample Implementation:** [thread_screen/cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) - - - -Enhance your Flutter chat app with threaded messaging by integrating CometChat’s `CometChatThreadedMessageList` and `CometChatMessageList` components to reply to messages in threads and view focused sub-conversations seamlessly. - -## Overview +--- -The sample app demonstrates how to enable threaded messaging in Flutter using CometChat’s UI Kit: +## Components -- Reply to specific messages to start focused sub-conversations. -- View all replies grouped under the parent message. -- Seamlessly switch back to the main conversation. +| Component / Class | Role | +|:---|:---| +| `CometChatThread` | Main container widget for threaded messages | +| `CometChatThreadedHeader` | Displays parent message and thread context | +| `CometChatMessageList` | Shows messages filtered by `parentMessageId` | +| `CometChatMessageComposer` | Input for composing threaded replies | +| `MessagesRequestBuilder` | Builds request to fetch thread replies | -## Prerequisites +--- -- A Flutter project with **CometChat UIKit Flutter v5** installed. -- Initialized CometChat credentials (`appID`, `region`, `authKey`). - -## Components +## Integration Steps -| Component | Role | -|:-----------------------------------|:-------------------------------------------------------------| -| `CometChatMessageList` | Displays main chat; provides `onThreadRepliesClick` callback.| -| `CometChatThreadedMessageList` | Fetches and displays replies for a parent message. | -| `CometChatMessageComposer` | Sends new messages; pass `parentMessageId` to send replies. | -| `CometChatThreadedHeader` | Shows the parent message and thread context at the top. | +### 1. Thread Trigger in Messages -## Integration Steps +Wire the `onThreadRepliesClick` callback on `CometChatMessageList`. When a user clicks the thread reply icon on any message, this fires with the parent message object. -### Show the “Reply in Thread” Option +_File: [messages.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart)_ -Trigger thread view when tapping the thread icon. ```dart CometChatMessageList( onThreadRepliesClick: (BaseMessage message) { Navigator.push( context, MaterialPageRoute( - builder: (_) => CometChatThread(parentMessage: message), + builder: (_) => CometChatThread( + message: message, + user: user, + group: group, + ), ), ); }, - // …other props ); ``` -**File reference:** -[`sample_app/lib/messages/messages.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) +--- -Captures the user's intent to view or add to a thread. +### 2. Thread Screen Widget -### Navigate to the Thread Screen +Create the thread screen with header, message list, and composer. The `CometChatThread` widget handles the complete thread UI. -Display a dedicated thread view. -```dart -class CometChatThread extends StatelessWidget { - final BaseMessage parentMessage; +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ - CometChatThread({required this.parentMessage}); +```dart +class CometChatThread extends StatefulWidget { + const CometChatThread({ + this.user, + this.group, + required this.message, + super.key, + }); + + final User? user; + final Group? group; + final BaseMessage message; @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar(title: Text("Thread")), - body: Column( - children: [ - CometChatThreadedHeader(message: parentMessage), - Expanded( - child: CometChatThreadedMessageList( - parentMessageId: parentMessage.id, - ), - ), - CometChatMessageComposer( - parentMessageId: parentMessage.id, - ), - ], - ), - ); - } + State createState() => _CometChatThreadState(); } ``` -**File reference:** -[`lib/thread_screen/cometchat_thread.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) +--- + +### 3. Thread Header and Message List -Provides a focused UI for thread interactions. +Display the parent message context and threaded replies using `CometChatThreadedHeader` and `CometChatMessageList` with `parentMessageId`. -### Send a Threaded Message +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -Send replies in the context of a thread. ```dart -CometChatMessageComposer( - parentMessageId: parentMessage.id, - // …other composer props -); +Column( + children: [ + CometChatThreadedHeader( + parentMessage: widget.message, + loggedInUser: CometChatUIKit.loggedInUser!, + ), + Expanded( + child: CometChatMessageList( + user: widget.user, + group: widget.group, + messagesRequestBuilder: MessagesRequestBuilder() + ..parentMessageId = widget.message.id, + ), + ), + ], +) ``` -**File reference:** -[`lib/thread_screen/cometchat_thread.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) +--- -Automatically associates new messages with the parent thread. +### 4. Thread Composer -### Fetch & Display Thread Replies +Add the message composer with `parentMessageId` to send replies in the thread context. -Retrieve and show all replies under a parent message. -```dart -MessagesRequest request = MessagesRequestBuilder() - .setParentMessageId(parentMessageId) - .build(); +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -request.fetchPrevious().then((replies) { - // Render these replies in the list -}); +```dart +CometChatMessageComposer( + user: widget.user, + group: widget.group, + parentMessageId: widget.message.id, +) ``` -**File reference:** -[`lib/thread_screen/cometchat_thread.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) - -Ensures only relevant threaded messages are shown. - -## Customization Options - -- **Header Styling:** Customize `CometChatThreadedHeader` appearance (colors, fonts). -- **List Pagination:** Adjust `limit` in `MessagesRequestBuilder`. -- **Composer Placeholder:** Change placeholder text based on thread context. +--- -## Filtering / Edge Cases +### 5. Blocked User Handling -- **Parent Deleted:** Show a fallback message or disable composer if parent is deleted. -- **No Replies:** Display an empty state (e.g., “No replies yet”). -- **Offline Mode:** Queue thread operations or show connectivity indicators. +When a user is blocked, replace the composer with an unblock prompt. -## Error Handling & Edge Cases +_File: [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart)_ -- **Fetch Failures:** Show error UI with retry option on `fetchPrevious` errors. -- **Send Failures:** Display SnackBar on composer send errors; allow retry. -- **Loading States:** Show loading indicators during fetch/send operations. +```dart +Widget getComposer(CometChatThreadController controller) { + if (controller.user?.blockedByMe == true) { + return Container( + padding: EdgeInsets.symmetric(vertical: 8, horizontal: 20), + child: Column( + children: [ + Text(Translations.of(context).cantSendMessageBlockedUser), + ElevatedButton( + onPressed: () => controller.unBlockUser(), + child: Text(Translations.of(context).unBlock), + ), + ], + ), + ); + } + return CometChatMessageComposer( + user: widget.user, + group: widget.group, + parentMessageId: widget.message.id, + ); +} +``` -## Optional Context-Specific Notes +--- -- **Group vs. Direct Threads:** Threads work the same for groups and 1:1 chats. -- **Blocked Users:** Threading respects block state; blocked users cannot send replies. +## Feature Matrix -## Summary / Feature Matrix +| Feature | Component / Method | File | +|:---|:---|:---| +| Show thread option | `onThreadRepliesClick` | [messages.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/messages/messages.dart) | +| Thread screen | `CometChatThread` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Thread header | `CometChatThreadedHeader` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Display thread msgs | `CometChatMessageList` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Compose reply | `CometChatMessageComposer` | [cometchat_thread.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread.dart) | +| Thread controller | `CometChatThreadController` | [cometchat_thread_controller.dart](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app/lib/thread_screen/cometchat_thread_controller.dart) | -| Feature | Component / Method | -|:------------------------------|:-----------------------------------------------| -| Show thread option | `CometChatMessageList.onThreadRepliesClick` | -| Thread view screen | `CometChatThread` widget | -| Display threaded messages | `CometChatThreadedMessageList(parentMessageId)`| -| Send threaded message | `CometChatMessageComposer(parentMessageId)` | -| Fetch thread replies | `MessagesRequestBuilder.setParentMessageId` | +--- ## Next Steps - - Display and manage conversation messages + + Render real-time message threads. - - Compose and send messages with threading support + + Customize the thread header component. - - Display thread context and parent message + + Browse all feature and formatter guides. - - Explore other implementation guides + + Full working sample application on GitHub. - \ No newline at end of file +
diff --git a/ui-kit/flutter/mentions-formatter-guide.mdx b/ui-kit/flutter/mentions-formatter-guide.mdx index 97a49cfed..b5977e760 100644 --- a/ui-kit/flutter/mentions-formatter-guide.mdx +++ b/ui-kit/flutter/mentions-formatter-guide.mdx @@ -1,7 +1,21 @@ --- title: "Mentions Formatter" +description: "Add @mentions with user suggestions and styled tokens in CometChat Flutter UI Kit." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key class | `CometChatMentionsFormatter` (extends `CometChatTextFormatter`) | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Purpose | Add @mentions with user suggestions, styled tokens, and click handling | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) · [All Guides](/ui-kit/flutter/guide-overview) | + + + ## Overview The `CometChatMentionsFormatter` class is a part of the CometChat UI Kit, a ready-to-use chat UI widget library for integrating CometChat into your Android applications. This class provides functionality to format mentions within text messages displayed in the chat interface. Mentions allow users to reference other users within a conversation, providing a convenient way to direct messages or involve specific participants. diff --git a/ui-kit/flutter/shortcut-formatter-guide.mdx b/ui-kit/flutter/shortcut-formatter-guide.mdx index cae25ad9e..e5c79f044 100644 --- a/ui-kit/flutter/shortcut-formatter-guide.mdx +++ b/ui-kit/flutter/shortcut-formatter-guide.mdx @@ -1,7 +1,21 @@ --- title: "Shortcut Formatter" +description: "Provide !shortcut style expansions invoking extension APIs or dialogs before inserting content in CometChat Flutter UI Kit." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Key class | `ShortcutFormatter` (extends `CometChatTextFormatter`) | +| Init | `CometChatUIKit.init(uiKitSettings)` then `CometChatUIKit.login(uid)` | +| Purpose | Provide !shortcut style expansions invoking extension APIs | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-flutter/tree/v5/sample_app) | +| Related | [Custom Text Formatter](/ui-kit/flutter/custom-text-formatter-guide) · [All Guides](/ui-kit/flutter/guide-overview) | + + + ## Introduction The `ShortcutFormatter` class extends the `CometChatTextFormatter` class to provide a mechanism for handling shortcuts within messages. This guide will walk you through the process of using ShortcutFormatter to implement shortcut extensions in your CometChat application. From 39f30310951f1caccdebe690f262a353243c0447 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:28:05 +0530 Subject: [PATCH 037/106] updates Reference { "group": "Reference", "pages": [ "ui-kit/flutter/methods", "ui-kit/flutter/events" ] }, --- ui-kit/flutter/events.mdx | 15 +++ ui-kit/flutter/methods.mdx | 259 ++++++++++++++++++++++++++++++------- 2 files changed, 226 insertions(+), 48 deletions(-) diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 4d99da659..022885d91 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -3,6 +3,21 @@ title: "Events" description: "Listen to and handle real-time events for users, groups, conversations, messages, calls, and UI interactions in Flutter UI Kit" --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Conversation events | `ccConversationDeleted`, `ccUpdateConversation` | +| User events | `ccUserBlocked`, `ccUserUnblocked` | +| Group events | `ccGroupCreated`, `ccGroupDeleted`, `ccGroupLeft`, `ccGroupMemberScopeChanged`, `ccGroupMemberKicked`, `ccGroupMemberBanned`, `ccGroupMemberUnbanned`, `ccGroupMemberJoined`, `ccGroupMemberAdded`, `ccOwnershipChanged` | +| Message events | `ccMessageSent`, `ccMessageEdited`, `ccReplyToMessage`, `ccMessageDeleted`, `ccMessageRead`, `ccLiveReaction`, `ccMessageForwarded`, plus SDK listener events | +| Call events | `ccOutgoingCall`, `ccCallAccepted`, `ccCallRejected`, `ccCallEnded` | +| UI events | `ccActiveChatChanged`, `showPanel`, `hidePanel`, `openChat`, `ccComposeMessage`, `onAiFeatureTapped` | +| Purpose | Decoupled communication between UI Kit components — subscribe to events to react to changes without direct component references | + + + {/* TL;DR for Agents and Quick Reference */} **Quick Reference for AI Agents & Developers** diff --git a/ui-kit/flutter/methods.mdx b/ui-kit/flutter/methods.mdx index bed14c418..222a617cf 100644 --- a/ui-kit/flutter/methods.mdx +++ b/ui-kit/flutter/methods.mdx @@ -1,7 +1,25 @@ --- title: "Methods" +description: "Reference for CometChat Flutter UI Kit methods including init, login, logout, and message-sending wrappers." --- + + +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Import | `import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';` | +| Init | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` | +| Login (dev) | `CometChatUIKit.login(uid)` | +| Login (prod) | `CometChatUIKit.loginWithAuthToken(authToken)` | +| Other methods | `CometChatUIKit.logout()`, `CometChatUIKit.getLoggedInUser()`, `CometChatUIKit.createUser(user)`, `CometChatUIKit.updateUser(user)` | +| Send messages | `CometChatUIKit.sendTextMessage()`, `CometChatUIKit.sendMediaMessage()`, `CometChatUIKit.sendCustomMessage()` | +| Interactive messages | `CometChatUIKit.sendFormMessage()`, `CometChatUIKit.sendCardMessage()`, `CometChatUIKit.sendSchedulerMessage()` | +| Reactions | `CometChatUIKit.addReaction()`, `CometChatUIKit.removeReaction()` | +| Note | Use these wrapper methods instead of raw SDK calls — they manage internal UI Kit eventing | + + + ## Overview The UI Kit's core function is to extend the [Chat SDK](/sdk/flutter/overview), essentially translating the raw data and functionality provided by the underlying methods into visually appealing and easy-to-use UI components. @@ -20,10 +38,16 @@ As a developer, you need to invoke this method every time before you use any oth This initialization is a critical step that ensures the UI Kit and Chat SDK function correctly and as intended in your application. Typical practice is to make this one of the first lines of code executed in your application's lifecycle when it comes to implementing CometChat. - + +`CometChatUIKit.init()` must be called before rendering any UI Kit components or calling any SDK methods. Initialization must complete before login. + -Make sure you replace the **APP\_ID**, **REGION** and **AUTH\_KEY** with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#login-using-auth-token) to log in securely. + +Auth Key is for development/testing only. In production, generate Auth Tokens on the server using the REST API and pass them to the client via `loginWithAuthToken()`. Never expose Auth Keys in production client code. + + +Make sure you replace the **APP\_ID**, **REGION** and **AUTH\_KEY** with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#login-using-auth-token) to log in securely. As a developer, the `UIKitSettings` is an important parameter of the `init()` function. It functions as a base settings object, housing properties such as `appId`, `region`, and `authKey`, contained within `UIKitSettings`. @@ -51,20 +75,24 @@ The concluding code block: -```dart +```dart highlight={3-5} UIKitSettings uiKitSettings = (UIKitSettingsBuilder() ..subscriptionType = CometChatSubscriptionType.allUsers ..autoEstablishSocketConnection = true - ..region = "your_region"// Replace with your region - ..appId = "your_appID" // Replace with your app Id - ..authKey = "your_authKey" // Replace with your app auth key + ..region = "your_region" // Replace with your region + ..appId = "your_appID" // Replace with your app Id + ..authKey = "your_authKey" // Replace with your app auth key ).build(); -CometChatUIKit.init(uiKitSettings: uiKitSettings,onSuccess: (successMessage) async { - // TODO("Not yet implemented") -}, onError: (error) { - // TODO("Not yet implemented") -}); +CometChatUIKit.init( + uiKitSettings: uiKitSettings, + onSuccess: (successMessage) async { + // Initialization successful, proceed to login + }, + onError: (error) { + // Handle initialization error + }, +); ``` @@ -79,12 +107,18 @@ Only the `UID` of a user is needed to log in. This simple authentication procedu -```dart -CometChatUIKit.login(uid, onSuccess: (s) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +```dart highlight={1} +String uid = "user1"; + +CometChatUIKit.login( + uid, + onSuccess: (user) { + // Login successful, mount your app + }, + onError: (e) { + // Handle login error + }, +); ``` @@ -95,7 +129,7 @@ CometChatUIKit.login(uid, onSuccess: (s) { ### Login using Auth Token -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. +Production-safe authentication that does not expose the Auth Key in client code. 1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. @@ -105,12 +139,18 @@ This advanced authentication procedure does not use the Auth Key directly in you -```dart -CometChatUIKit.loginWithAuthToken("authToken", onSuccess: (user) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +```dart highlight={1} +String authToken = "AUTH_TOKEN"; + +CometChatUIKit.loginWithAuthToken( + authToken, + onSuccess: (user) { + // Login successful, mount your app + }, + onError: (e) { + // Handle login error + }, +); ``` @@ -351,16 +391,53 @@ CometChatUIKit.init( #### Text Message -As a developer, if you need to send a text message to a single user or a group, you'll need to utilize the `sendMessage()` function. This function requires a `TextMessage` object as its argument, which contains the necessary information for delivering the message. +Sends a text message in a 1:1 or group chat. Takes a `TextMessage` object. - -```dart -CometChatUIKit.sendTextMessage(textMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); + +```dart highlight={1-2} +String receiverID = "UID"; +String messageText = "Hello world!"; + +TextMessage textMessage = TextMessage( + text: messageText, + receiverUid: receiverID, + receiverType: ReceiverType.user, +); + +CometChatUIKit.sendTextMessage( + textMessage, + onSuccess: (message) { + // Message sent successfully + }, + onError: (e) { + // Handle error + }, +); +``` + + + + +```dart highlight={1-2} +String receiverID = "GUID"; +String messageText = "Hello world!"; + +TextMessage textMessage = TextMessage( + text: messageText, + receiverUid: receiverID, + receiverType: ReceiverType.group, +); + +CometChatUIKit.sendTextMessage( + textMessage, + onSuccess: (message) { + // Message sent successfully + }, + onError: (e) { + // Handle error + }, +); ``` @@ -371,16 +448,55 @@ CometChatUIKit.sendTextMessage(textMessageObject, onSuccess: (p0) { #### Media Message -As a developer, if you need to send a media message to a single user or a group, you'll need to utilize the `sendMediaMessage()` function. This function requires a `MediaMessage` object as its argument, which contains the necessary information for delivering the message. +Sends a media message in a 1:1 or group chat. Takes a `MediaMessage` object. - -```dart -CometChatUIKit.sendMediaMessage(mediaMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); + +```dart highlight={1-2} +String receiverID = "UID"; +String filePath = "/path/to/file"; + +MediaMessage mediaMessage = MediaMessage( + receiverUid: receiverID, + receiverType: ReceiverType.user, + type: MessageType.file, + file: filePath, +); + +CometChatUIKit.sendMediaMessage( + mediaMessage, + onSuccess: (message) { + // Media message sent successfully + }, + onError: (e) { + // Handle error + }, +); +``` + + + + +```dart highlight={1-2} +String receiverID = "GUID"; +String filePath = "/path/to/file"; + +MediaMessage mediaMessage = MediaMessage( + receiverUid: receiverID, + receiverType: ReceiverType.group, + type: MessageType.file, + file: filePath, +); + +CometChatUIKit.sendMediaMessage( + mediaMessage, + onSuccess: (message) { + // Media message sent successfully + }, + onError: (e) { + // Handle error + }, +); ``` @@ -391,16 +507,63 @@ CometChatUIKit.sendMediaMessage(mediaMessageObject, onSuccess: (p0) { #### Custom Message -As a developer, if you need to send a media message to a single user or a group, you'll need to utilize the `sendCustomMessage()` function. This function requires a `CustomMessage` object as its argument, which contains the necessary information for delivering the message. +Sends a custom message (neither text nor media) in a 1:1 or group chat. Takes a `CustomMessage` object. - -```dart -CometChatUIKit.sendCustomMessage(customMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); + +```dart highlight={1,3-4} +String receiverID = "UID"; +Map customData = { + "latitude": "50.6192171633316", + "longitude": "-72.68182268750002", +}; +String customType = "location"; + +CustomMessage customMessage = CustomMessage( + receiverUid: receiverID, + receiverType: ReceiverType.user, + type: customType, + customData: customData, +); + +CometChatUIKit.sendCustomMessage( + customMessage, + onSuccess: (message) { + // Custom message sent successfully + }, + onError: (e) { + // Handle error + }, +); +``` + + + + +```dart highlight={1,3-4} +String receiverID = "GUID"; +Map customData = { + "latitude": "50.6192171633316", + "longitude": "-72.68182268750002", +}; +String customType = "location"; + +CustomMessage customMessage = CustomMessage( + receiverUid: receiverID, + receiverType: ReceiverType.group, + type: customType, + customData: customData, +); + +CometChatUIKit.sendCustomMessage( + customMessage, + onSuccess: (message) { + // Custom message sent successfully + }, + onError: (e) { + // Handle error + }, +); ``` From cc08203b2f9ce5d91cc156543933be3b8563d4a7 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:36:12 +0530 Subject: [PATCH 038/106] updates features --- ui-kit/flutter/ai-features.mdx | 49 ++------ ui-kit/flutter/call-features.mdx | 55 +++------ ui-kit/flutter/core-features.mdx | 29 ++--- ui-kit/flutter/extensions.mdx | 190 ++++++++++++++++++++++--------- 4 files changed, 169 insertions(+), 154 deletions(-) diff --git a/ui-kit/flutter/ai-features.mdx b/ui-kit/flutter/ai-features.mdx index 8ffcac57f..034555fd8 100644 --- a/ui-kit/flutter/ai-features.mdx +++ b/ui-kit/flutter/ai-features.mdx @@ -1,44 +1,21 @@ --- title: "AI Features" +sidebarTitle: "Smart Chat" description: "Enhance user interaction with AI-powered conversation starters, smart replies, and conversation summaries in your Flutter app" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; - -// Enable AI features in UIKitSettings -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..aiFeature = [ - AISmartRepliesExtension(), - AIConversationStarterExtension(), - AIAssistBotExtension(), - AIConversationSummaryExtension() - ] -).build(); - -// Initialize with AI features -CometChatUIKit.init(uiKitSettings: uiKitSettings); -``` - -**Key AI Extensions:** -- `AISmartRepliesExtension` → Smart reply suggestions -- `AIConversationStarterExtension` → Conversation starters -- `AIAssistBotExtension` → AI assistant bot -- `AIConversationSummaryExtension` → Conversation summaries - -**Components:** -- Conversation Starters → Auto-displayed in `CometChatMessageList` ([Docs](/ui-kit/flutter/message-list)) -- Smart Replies → Available in `CometChatMessageComposer` action sheet ([Docs](/ui-kit/flutter/message-composer)) -- Conversation Summary → Available in `CometChatMessageComposer` action sheet ([Docs](/ui-kit/flutter/message-composer)) +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Required setup | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` then `CometChatUIKit.login(uid)` + AI features enabled in [CometChat Dashboard](/fundamentals/ai-user-copilot/overview) | +| AI features | Conversation Starter, Smart Replies, Conversation Summary, AI Assist Bot | +| Key components | `CometChatMessageList` → [Message List](/ui-kit/flutter/message-list) (Conversation Starter), `CometChatMessageComposer` → [Message Composer](/ui-kit/flutter/message-composer) (Smart Replies, Summary) | +| AI Extensions | `AISmartRepliesExtension()`, `AIConversationStarterExtension()`, `AIAssistBotExtension()`, `AIConversationSummaryExtension()` | +| Activation | Enable each AI feature from the CometChat Dashboard — UI Kit auto-integrates them after configuration | -Activate features from [CometChat Dashboard](https://app.cometchat.com) → Extensions → AI - - -## Overview + CometChat's AI capabilities greatly enhance user interaction and engagement in your application. Let's understand how the Flutter UI Kit achieves these features. @@ -46,10 +23,6 @@ CometChat's AI capabilities greatly enhance user interaction and engagement in y - -**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [Dashboard](https://app.cometchat.com) - - *** ## Usage diff --git a/ui-kit/flutter/call-features.mdx b/ui-kit/flutter/call-features.mdx index 2322a5c28..dd278bde9 100644 --- a/ui-kit/flutter/call-features.mdx +++ b/ui-kit/flutter/call-features.mdx @@ -1,53 +1,24 @@ --- title: "Call Features" +sidebarTitle: "Calls" description: "Integrate one-on-one and group audio/video calling capabilities into your Flutter app with CometChat UI Kit" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart'; - -// Enable calling features in UIKitSettings -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "APP_ID" - ..authKey = "AUTH_KEY" - ..region = "REGION" - ..callingExtension = CometChatCallingExtension() -).build(); - -// Initialize with calling support -CometChatUIKit.init(uiKitSettings: uiKitSettings); - -// Set navigation key for incoming calls -CometChatUsersWithMessages(key: CallNavigationContext.navigatorKey) - -// Add call listener -CometChat.addCallListener(listenerId, this); -``` - -**Key Calling Components:** -- `CometChatCallButtons` → [Docs](/ui-kit/flutter/call-buttons) -- `CometChatIncomingCall` → [Docs](/ui-kit/flutter/incoming-call) -- `CometChatOutgoingCall` → [Docs](/ui-kit/flutter/outgoing-call) -- `CometChatCallLogs` → [Docs](/ui-kit/flutter/call-logs) -- `CometChatCallingExtension` → Calling extension -- `CallNavigationContext` → Navigation context for calls - -**Requirements:** `cometchat_calls_uikit` package, minSdkVersion 24 (Android), iOS 12+ - - -## Overview +| Field | Value | +| --- | --- | +| Packages | `cometchat_chat_uikit` + `cometchat_calls_uikit` (add to `pubspec.yaml`) | +| Required setup | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` then `CometChatUIKit.login(uid)` — Calls SDK must also be installed | +| Call features | Incoming Call, Outgoing Call, Call Logs, Call Buttons | +| Key components | `CometChatCallButtons` → [Call Buttons](/ui-kit/flutter/call-buttons), `CometChatIncomingCall` → [Incoming Call](/ui-kit/flutter/incoming-call), `CometChatOutgoingCall` → [Outgoing Call](/ui-kit/flutter/outgoing-call), `CometChatCallLogs` → [Call Logs](/ui-kit/flutter/call-logs) | +| Auto-detection | UI Kit automatically detects the Calls SDK and enables call UI components | +| Requirements | minSdkVersion 24 (Android), iOS 12+ | + + CometChat's Calls feature is an advanced functionality that 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 Flutter UI Kit. - - -**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) - - + ## 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/flutter/getting-started) guide. This guide will walk you through a step-by-step process of integrating our UI Kit into your Flutter project. diff --git a/ui-kit/flutter/core-features.mdx b/ui-kit/flutter/core-features.mdx index fc991048d..12d9dd625 100644 --- a/ui-kit/flutter/core-features.mdx +++ b/ui-kit/flutter/core-features.mdx @@ -4,27 +4,18 @@ sidebarTitle: "Core" description: "Comprehensive guide to CometChat's core messaging features including instant messaging, media sharing, read receipts, and more" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** - -Key components for core features: -- **Instant Messaging** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) -- **Media Sharing** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) -- **Read Receipts** → [Conversations](/ui-kit/flutter/conversations) | [MessageList](/ui-kit/flutter/message-list) -- **Typing Indicators** → [Conversations](/ui-kit/flutter/conversations) | [MessageHeader](/ui-kit/flutter/message-header) -- **User Presence** → [Conversations](/ui-kit/flutter/conversations) | [Users](/ui-kit/flutter/users) -- **Reactions** → [MessageList](/ui-kit/flutter/message-list) -- **Mentions** → [MessageComposer](/ui-kit/flutter/message-composer) | [MessageList](/ui-kit/flutter/message-list) -- **Threaded Messages** → [Threaded Messages](/ui-kit/flutter/threaded-messages-header) -- **Group Chat** → [Groups](/ui-kit/flutter/groups) - + -The UI Kit comprises a variety of widgets, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Required setup | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` then `CometChatUIKit.login(uid)` — 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, Search, Threaded Conversations, Moderation, Report Message, Group Chat | +| Key components | `CometChatConversations` → [Conversations](/ui-kit/flutter/conversations), `CometChatMessageList` → [Message List](/ui-kit/flutter/message-list), `CometChatMessageComposer` → [Message Composer](/ui-kit/flutter/message-composer), `CometChatMessageHeader` → [Message Header](/ui-kit/flutter/message-header), `CometChatUsers` → [Users](/ui-kit/flutter/users), `CometChatGroups` → [Groups](/ui-kit/flutter/groups), `CometChatGroupMembers` → [Group Members](/ui-kit/flutter/group-members) | - -**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [REST API](https://api-explorer.cometchat.com) - + + +The UI Kit comprises a variety of widgets, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. Here's how different UI Kit widgets work together to achieve CometChat's Core features: diff --git a/ui-kit/flutter/extensions.mdx b/ui-kit/flutter/extensions.mdx index 6a8a01c01..82511a0ca 100644 --- a/ui-kit/flutter/extensions.mdx +++ b/ui-kit/flutter/extensions.mdx @@ -1,54 +1,104 @@ --- title: "Extensions" +sidebarTitle: "Extensions" description: "Enhance your chat with built-in extensions including stickers, polls, collaborative tools, message translation, and link previews" --- -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** + -```dart -// Enable extensions during initialization -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..appId = "YOUR_APP_ID" - ..region = "YOUR_REGION" - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() -).build(); +| Field | Value | +| --- | --- | +| Package | `cometchat_chat_uikit` | +| Required setup | `CometChatUIKit.init(uiKitSettings: UIKitSettings)` then `CometChatUIKit.login(uid)` + Extensions enabled in [CometChat Dashboard](/fundamentals/extensions-overview) | +| Extension categories | User Experience, User Engagement, Collaboration, Security | +| Key components | `CometChatMessageComposer` → [Message Composer](/ui-kit/flutter/message-composer) (Stickers, Polls, Whiteboard, Document), `CometChatMessageList` → [Message List](/ui-kit/flutter/message-list) (Translation, Link Preview, Thumbnails) | +| Activation | Enable each extension from the CometChat Dashboard — UI Kit auto-integrates them, no additional code required | -await CometChatUIKit.init(uiKitSettings: uiKitSettings); -``` + -**Built-in Extensions:** -- **Stickers** → Express emotions with pre-designed stickers -- **Polls** → Create polls for group discussions -- **Collaborative Whiteboard** → Real-time drawing and brainstorming -- **Collaborative Document** → Shared document editing -- **Message Translation** → Translate messages to local locale -- **Link Preview** → Show URL summaries with thumbnails -- **Thumbnail Generation** → Auto-generate image previews +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. -**Enable from:** [CometChat Dashboard](https://app.cometchat.com) → Extensions - +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). -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. +Once you have successfully enabled the desired extension in your dashboard, it will be reflected in your CometChat application upon initialization and successful login. The extension features will only be available if they are supported by CometChat UI Kit. - -**Available via:** [UI Kits](/ui-kit/flutter/overview) | [SDK](/sdk/flutter/overview) | [Dashboard](https://app.cometchat.com) - +*** -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) +## Built-in Extensions -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 the extension features will only be available if they are supported by CometChat UI Kit. +The grouping below mirrors the CometChat Dashboard. -CometChat's UI Kit offers built-in support for 12 powerful 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 widgets of your application, providing a richer and more engaging experience for your users. +### User Experience + +#### 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 Widget](/ui-kit/flutter/message-list) widget of UI Kits. + + + + *** -## Built-in Extensions +#### 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 Widget](/ui-kit/flutter/message-list) widget of UI Kits. + + + + + +*** + +#### Bitly + +Shortens long URLs in text messages using Bitly. See [Bitly Extension](/fundamentals/bitly). + +*** + +#### TinyURL + +URL shortening using TinyURL. See [TinyURL Extension](/fundamentals/tinyurl). + +*** + +#### Message Shortcuts + +Sends predefined messages using short codes (e.g., `!hb` expands to `Happy birthday!`). See [Message Shortcuts Extension](/fundamentals/message-shortcuts). + +*** + +#### Pin Message + +Pins important messages in a conversation for easy access. See [Pin Message Extension](/fundamentals/pin-message). + +*** + +#### Save Message + +Bookmarks messages for later reference. Saved messages are private to the user. See [Save Message Extension](/fundamentals/save-message). + +*** + +#### Rich Media Preview + +Generates rich preview panels for URLs using iFramely. See [Rich Media Preview Extension](/fundamentals/rich-media-preview). -Here's a guide on how you can enable and integrate these extensions: +*** + +#### Voice Transcription -### Stickers +Converts audio messages to text. See [Voice Transcription Extension](/fundamentals/voice-transcription). + +*** + +### User Engagement + +#### 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). @@ -60,7 +110,7 @@ Once you have successfully activated the [Sticker Extension](/fundamentals/stick *** -### Polls +#### 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). @@ -72,7 +122,45 @@ Once you have successfully activated the [Polls Extension](/fundamentals/polls) *** -### Collaborative Whiteboard +#### 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 Widget](/ui-kit/flutter/message-list) widget of UI Kits. + + + + + +*** + +#### Giphy + +Search and share GIFs from Giphy. See [Giphy Extension](/fundamentals/giphy). + +*** + +#### Tenor + +Search and share GIFs from Tenor. See [Tenor Extension](/fundamentals/tenor). + +*** + +#### Stipop + +Integrates Stipop's sticker library. See [Stipop Extension](/fundamentals/stickers-stipop). + +*** + +#### Reminders + +Sets reminders for messages or creates personal reminders. A bot sends a notification when due. See [Reminders Extension](/fundamentals/reminders). + +*** + +### Collaboration + +#### 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](/fundamentals/collaborative-whiteboard). @@ -84,7 +172,7 @@ Once you have successfully activated the [Collaborative Whiteboard Extension](/f *** -### Collaborative Document +#### 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](/fundamentals/collaborative-document). @@ -96,39 +184,31 @@ Once you have successfully activated the [Collaborative Document Extension](/fun *** -### Message Translation +### Security -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 Widget](/ui-kit/flutter/message-list) widget of UI Kits. +#### Disappearing Messages - - - +Messages auto-delete after a specified interval. Works for 1:1 and group messages. See [Disappearing Messages Extension](/fundamentals/disappearing-messages). *** -### Link Preview +### Customer Support -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). +#### Chatwoot -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 Widget](/ui-kit/flutter/message-list) widget of UI Kits. - - - - +Routes user messages to Chatwoot for customer support. See [Chatwoot Extension](/fundamentals/chatwoot). *** -### Thumbnail Generation +#### Intercom -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). +Integrates Intercom for in-app customer support. See [Intercom Extension](/fundamentals/intercom). -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 Widget](/ui-kit/flutter/message-list) widget of UI Kits. +*** - - - +### Smart Chat Features + +For AI-powered features like Conversation Starter, Smart Replies, and Conversation Summary, see [AI Features](/ui-kit/flutter/ai-features). *** From dec59b5d447cab7e8317ce38c206eaa25adf2cd3 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:40:15 +0530 Subject: [PATCH 039/106] Update call-features.mdx --- ui-kit/flutter/call-features.mdx | 210 +++++++++++++++---------------- 1 file changed, 98 insertions(+), 112 deletions(-) diff --git a/ui-kit/flutter/call-features.mdx b/ui-kit/flutter/call-features.mdx index dd278bde9..f674c8b37 100644 --- a/ui-kit/flutter/call-features.mdx +++ b/ui-kit/flutter/call-features.mdx @@ -25,118 +25,104 @@ First, make sure that you've correctly integrated the UI Kit library into your p 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. Here's how you do it: -Step 1 - -### Add Dependency - -Add the following dependency to your `pubspec.yaml` file: - - - -```dart -dependencies: - cometchat_calls_uikit: ^5.0.12 -``` - - - -*** - -Step 2 - -### Update build.gradle - -If your Flutter project's minimum Android SDK version (minSdkVersion) is below API level 24, you should update it to at least 24. To achieve this, navigate to the `android/app/build.gradle` file and modify the `minSdkVersion` property within the `defaultConfig` section. - - - -```gradle -defaultConfig { - minSdkVersion 24 - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName -} -``` - - - - -If you want to use the Flutter UI Kit or enable calling support within it, you'll need to set the `minSdkVersion` to 24 in your `android/app/build.gradle` file. - - -*** - -Step 3 - -### Update iOS Podfile - -In your Podfile located at `ios/Podfile`, update the minimum iOS version that your project supports to 12. - - - -```xml -platform :ios, '12.0' -``` - - - -*** - -Step 4 - -### Modify UIKitSettings - -To activate the calling features, you'll need to modify the UIKitSettings using `callingExtension` and pass the key in the widget. - -Example - - - -```dart -UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..autoEstablishSocketConnection = true - ..region = "REGION" // Replace with your App Region - ..appId = "APP_ID" // Replace with your App ID - ..authKey = "AUTH_KEY" // Replace with your app Auth Key - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() - ..callingExtension = CometChatCallingExtension() // Enable calling feature -).build(); - -CometChatUIKit.init( - uiKitSettings: uiKitSettings, - onSuccess: (successMessage) { - // TODO("Not yet implemented") - }, - onError: (e) { - // TODO("Not yet implemented") - } -); -``` - - - -To allow launching of Incoming Call screen from any widget whenever a call is received provide set key: CallNavigationContext.navigatorKey in the top most widget of your project (the widget that appears first of your app launch). - - - -```dart -CometChatUIKit.login(uid, onSuccess: (s) { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => CometChatUsersWithMessages( - key: CallNavigationContext.navigatorKey - ) - ) - ); -}, onError: (e) { - // TODO("Not yet implemented") -}); -``` - - + + + Add the following dependency to your `pubspec.yaml` file: + + + + ```yaml + dependencies: + cometchat_calls_uikit: ^5.0.12 + ``` + + + + + + If your Flutter project's minimum Android SDK version (minSdkVersion) is below API level 24, you should update it to at least 24. Navigate to the `android/app/build.gradle` file and modify the `minSdkVersion` property within the `defaultConfig` section. + + + + ```gradle + defaultConfig { + minSdkVersion 24 + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + ``` + + + + + If you want to use the Flutter UI Kit or enable calling support within it, you'll need to set the `minSdkVersion` to 24 in your `android/app/build.gradle` file. + + + + + In your Podfile located at `ios/Podfile`, update the minimum iOS version that your project supports to 12. + + + + ```ruby + platform :ios, '12.0' + ``` + + + + + + To activate the calling features, you'll need to modify the UIKitSettings using `callingExtension` and pass the key in the widget. + + + + ```dart highlight={8} + UIKitSettings uiKitSettings = (UIKitSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..autoEstablishSocketConnection = true + ..region = "REGION" // Replace with your App Region + ..appId = "APP_ID" // Replace with your App ID + ..authKey = "AUTH_KEY" // Replace with your app Auth Key + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + ..callingExtension = CometChatCallingExtension() // Enable calling feature + ).build(); + + CometChatUIKit.init( + uiKitSettings: uiKitSettings, + onSuccess: (successMessage) { + // Initialization successful + }, + onError: (e) { + // Handle error + } + ); + ``` + + + + To allow launching of Incoming Call screen from any widget whenever a call is received, set `key: CallNavigationContext.navigatorKey` in the top most widget of your project (the widget that appears first on app launch). + + + + ```dart highlight={6} + CometChatUIKit.login(uid, onSuccess: (s) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => CometChatUsersWithMessages( + key: CallNavigationContext.navigatorKey + ) + ) + ); + }, onError: (e) { + // Handle error + }); + ``` + + + + After adding this dependency, the Flutter UI Kit will automatically detect it and activate the calling features. Now, your application supports both audio and video calling. You will see [CallButtons](/ui-kit/flutter/call-buttons) widget rendered in [MessageHeader](/ui-kit/flutter/message-header) Widget. From 274453a0b18f6693d4f1a3af06216c6e364b3f4a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:49:01 +0530 Subject: [PATCH 040/106] Update components-overview.mdx --- ui-kit/flutter/components-overview.mdx | 41 +++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/components-overview.mdx b/ui-kit/flutter/components-overview.mdx index f549bf175..7fc03fe55 100644 --- a/ui-kit/flutter/components-overview.mdx +++ b/ui-kit/flutter/components-overview.mdx @@ -26,10 +26,49 @@ The UI Kit is a set of independent widgets that compose into chat layouts. A typ - **CometChatMessageList** — scrollable message feed with reactions, receipts, and threads - **CometChatMessageComposer** — rich text input with attachments, mentions, and voice notes -Data flow: selecting a conversation in CometChatConversations yields a `User` or `Group` object. That object is passed as a prop (`user` or `group`) to CometChatMessageHeader, CometChatMessageList, and CometChatMessageComposer. The message components use the SDK internally — CometChatMessageComposer sends messages, CometChatMessageList receives them via real-time listeners. +**Data flow**: selecting a conversation in CometChatConversations yields a `User` or `Group` object. That object is passed as a prop (`user` or `group`) to CometChatMessageHeader, CometChatMessageList, and CometChatMessageComposer. The message components use the SDK internally — CometChatMessageComposer sends messages, CometChatMessageList receives them via real-time listeners. + +```mermaid +flowchart LR + subgraph Sidebar + A[CometChatConversations] + end + + subgraph "Chat Panel" + B[CometChatMessageHeader] + C[CometChatMessageList] + D[CometChatMessageComposer] + end + + subgraph SDK + E[CometChat SDK] + end + + A -->|"User/Group object"| B + A -->|"User/Group object"| C + A -->|"User/Group object"| D + D -->|"sendMessage()"| E + E -->|"Real-time listeners"| C +``` Components communicate through a publish/subscribe event bus (`CometChatMessageEvents`, `CometChatConversationEvents`, `CometChatGroupEvents`, etc.). A component emits events that other components or application code can subscribe to without direct references. See [Events](/ui-kit/flutter/events) for the full list. +```mermaid +flowchart TB + subgraph "Event Bus" + E1[CometChatMessageEvents] + E2[CometChatConversationEvents] + E3[CometChatGroupEvents] + end + + C1[Component A] -->|"emit"| E1 + E1 -->|"subscribe"| C2[Component B] + E1 -->|"subscribe"| C3[App Code] + + C4[Component C] -->|"emit"| E2 + E2 -->|"subscribe"| C5[Component D] +``` + Each component accepts callback props (`on`), view slot props (`View`) for replacing UI sections, `RequestBuilder` props for data filtering, and style class overrides via `CometChatStyle`. --- From f7af525a14437359f842cad2f3e9ba138c516b47 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 15:52:56 +0530 Subject: [PATCH 041/106] Removed all 3 references to community.cometchat.com --- ui-kit/flutter/guide-overview.mdx | 2 +- ui-kit/flutter/overview.mdx | 3 --- ui-kit/flutter/troubleshooting.mdx | 1 - 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/ui-kit/flutter/guide-overview.mdx b/ui-kit/flutter/guide-overview.mdx index 46f3dc93b..390da3adb 100644 --- a/ui-kit/flutter/guide-overview.mdx +++ b/ui-kit/flutter/guide-overview.mdx @@ -44,7 +44,7 @@ Use these after finishing [Getting Started](/ui-kit/flutter/getting-started) and | [URL Formatter](/ui-kit/flutter/url-formatter-guide) | Auto-detect and style URLs as clickable links. | | [Shortcut Formatter](/ui-kit/flutter/shortcut-formatter-guide) | Create keyboard shortcuts for quick text insertion. | -Need another guide? Request one via the [Developer Community](http://community.cometchat.com/) or Support. +Need another guide? Request one via [CometChat Support](https://www.cometchat.com/support). --- diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index e1391ba86..815576fdb 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -71,7 +71,4 @@ The CometChat Flutter UI Kit provides prebuilt, customizable widgets for adding Open a support ticket - - Developer community forum -
diff --git a/ui-kit/flutter/troubleshooting.mdx b/ui-kit/flutter/troubleshooting.mdx index afde830f4..51c28fda8 100644 --- a/ui-kit/flutter/troubleshooting.mdx +++ b/ui-kit/flutter/troubleshooting.mdx @@ -208,4 +208,3 @@ If you're still experiencing issues: 1. Check the [CometChat Documentation](https://www.cometchat.com/docs) 2. Search the [GitHub Issues](https://github.com/cometchat/cometchat-uikit-flutter/issues) 3. Contact [CometChat Support](https://www.cometchat.com/support) -4. Join the [CometChat Community](https://community.cometchat.com) From daa0432174826629345905b8979e01be6bed5e49 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 16:35:04 +0530 Subject: [PATCH 042/106] updates ignore files --- .gitignore | 1 + .mintignore | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 19273fa01..51b40734f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .kiro/ /codebase +/doc-auditor diff --git a/.mintignore b/.mintignore index a2bfd86bc..15ada5362 100644 --- a/.mintignore +++ b/.mintignore @@ -1,2 +1,3 @@ .kiro/ -/codebase \ No newline at end of file +/codebase +/doc-auditor \ No newline at end of file From c547a9c1ad7faa2bcb04a72b30a94b1ad57eae85 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 18:20:28 +0530 Subject: [PATCH 043/106] updates components --- ui-kit/flutter/call-buttons.mdx | 32 +++++++++++++++++ ui-kit/flutter/call-logs.mdx | 55 +++++++++++++++++++++++++++++ ui-kit/flutter/incoming-call.mdx | 51 ++++++++++++++++++++++++++ ui-kit/flutter/message-template.mdx | 29 +++++++++++++++ ui-kit/flutter/outgoing-call.mdx | 45 +++++++++++++++++++++++ 5 files changed, 212 insertions(+) diff --git a/ui-kit/flutter/call-buttons.mdx b/ui-kit/flutter/call-buttons.mdx index 0f404d59b..e39b6b0c2 100644 --- a/ui-kit/flutter/call-buttons.mdx +++ b/ui-kit/flutter/call-buttons.mdx @@ -1,6 +1,38 @@ --- title: "Call Buttons" +description: "Widget that provides users with the ability to make voice and video calls with customizable icons and styles." --- + +```json +{ + "component": "CometChatCallButtons", + "package": "cometchat_calls_uikit", + "import": "import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart';", + "description": "Widget that provides users with the ability to make voice and video calls with customizable icons and styles.", + "props": { + "data": { + "user": { "type": "User?", "default": "null" }, + "group": { "type": "Group?", "default": "null" } + }, + "visibility": { + "hideVoiceCallButton": { "type": "bool?", "default": "false" }, + "hideVideoCallButton": { "type": "bool?", "default": "false" } + }, + "icons": { + "voiceCallIcon": "Widget?", + "videoCallIcon": "Widget?" + }, + "style": { + "callButtonsStyle": "CometChatCallButtonsStyle?" + }, + "configuration": { + "outgoingCallConfiguration": "CometChatOutgoingCallConfiguration?", + "callSettingsBuilder": "CallSettingsBuilder Function(User? user, Group? group, bool? isAudioOnly)?" + } + } +} +``` + ## Overview diff --git a/ui-kit/flutter/call-logs.mdx b/ui-kit/flutter/call-logs.mdx index 053d4db84..1c65634c3 100644 --- a/ui-kit/flutter/call-logs.mdx +++ b/ui-kit/flutter/call-logs.mdx @@ -1,6 +1,61 @@ --- title: "Call Logs" +description: "Widget that shows the list of Call Logs available with filtering, call-back actions, and custom views." --- + +```json +{ + "component": "CometChatCallLogs", + "package": "cometchat_calls_uikit", + "import": "import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart';", + "description": "Widget that shows the list of Call Logs available with filtering, call-back actions, and custom views.", + "props": { + "data": { + "callLogsRequestBuilder": { "type": "CallLogRequestBuilder?", "default": "null" }, + "callLogsBuilderProtocol": { "type": "CallLogsBuilderProtocol?", "default": "null" } + }, + "callbacks": { + "onItemClick": "Function(CallLog callLog)?", + "onItemLongPress": "Function(CallLog callLog)?", + "onCallLogIconClicked": "Function(CallLog callLog)?", + "onBack": "VoidCallback?", + "onError": "OnError?", + "onLoad": "OnLoad?", + "onEmpty": "OnEmpty?" + }, + "visibility": { + "hideAppbar": { "type": "bool?", "default": "false" }, + "showBackButton": { "type": "bool?", "default": "true" } + }, + "viewSlots": { + "listItemView": "Widget? Function(CallLog callLog, BuildContext context)?", + "subTitleView": "Widget? Function(CallLog callLog, BuildContext context)?", + "trailingView": "Function(BuildContext context, CallLog callLog)?", + "leadingStateView": "Widget? Function(BuildContext, CallLog)?", + "titleView": "Widget? Function(BuildContext, CallLog)?", + "backButton": "Widget?", + "emptyStateView": "WidgetBuilder?", + "errorStateView": "WidgetBuilder?", + "loadingStateView": "WidgetBuilder?" + }, + "style": { + "callLogsStyle": "CometChatCallLogsStyle?" + }, + "icons": { + "audioCallIcon": "Widget?", + "videoCallIcon": "Widget?", + "incomingCallIcon": "Widget?", + "outgoingCallIcon": "Widget?", + "missedCallIcon": "Widget?" + }, + "formatting": { + "datePattern": "String?", + "dateSeparatorPattern": "String?" + } + } +} +``` + ## Overview diff --git a/ui-kit/flutter/incoming-call.mdx b/ui-kit/flutter/incoming-call.mdx index 41895e4ae..7891817c9 100644 --- a/ui-kit/flutter/incoming-call.mdx +++ b/ui-kit/flutter/incoming-call.mdx @@ -1,6 +1,57 @@ --- title: "Incoming Call" +description: "Widget that serves as a visual representation when the user receives an incoming call, providing options to answer or decline." --- + +```json +{ + "component": "CometChatIncomingCall", + "package": "cometchat_calls_uikit", + "import": "import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart';", + "description": "Widget that serves as a visual representation when the user receives an incoming call, providing options to answer or decline.", + "props": { + "data": { + "call": { "type": "Call", "required": true }, + "user": { "type": "User?", "default": "null" } + }, + "callbacks": { + "onDecline": "Function(BuildContext, Call)?", + "onAccept": "Function(BuildContext, Call)?", + "onError": "OnError?" + }, + "viewSlots": { + "titleView": "Widget? Function(BuildContext context, Call call)?", + "subTitleView": "Widget? Function(BuildContext context, Call call)?", + "leadingView": "Widget? Function(BuildContext context, Call call)?", + "itemView": "Widget? Function(BuildContext context, Call call)?", + "trailingView": "Widget? Function(BuildContext context, Call call)?" + }, + "style": { + "incomingCallStyle": "CometChatIncomingCallStyle?" + }, + "layout": { + "height": { "type": "double?", "default": "null" }, + "width": { "type": "double?", "default": "null" } + }, + "icons": { + "callIcon": "Widget?" + }, + "text": { + "declineButtonText": "String?", + "acceptButtonText": "String?" + }, + "sound": { + "disableSoundForCalls": { "type": "bool?", "default": "false" }, + "customSoundForCalls": "String?", + "customSoundForCallsPackage": "String?" + }, + "configuration": { + "callSettingsBuilder": "CallSettingsBuilder?" + } + } +} +``` + ## Overview diff --git a/ui-kit/flutter/message-template.mdx b/ui-kit/flutter/message-template.mdx index 6be26a674..c70fc6a66 100644 --- a/ui-kit/flutter/message-template.mdx +++ b/ui-kit/flutter/message-template.mdx @@ -1,7 +1,36 @@ --- title: "Message Template" +description: "Data structure defining how message bubbles render in CometChatMessageList — controls header, content, footer, bottom, status info, reply, and bubble views per message type and category." --- + +```json +{ + "component": "CometChatMessageTemplate", + "kind": "model-class", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Data structure defining how message bubbles render in CometChatMessageList. Each template maps a type+category pair to view functions.", + "usage": "Pass a list of CometChatMessageTemplate instances to CometChatMessageList via the templates property.", + "properties": { + "type": { "type": "String", "required": true, "description": "CometChat message type" }, + "category": { "type": "String", "default": "\"\"", "description": "CometChat message category" }, + "headerView": { "type": "Function?", "default": "null", "description": "Custom header view builder function" }, + "contentView": { "type": "Function?", "default": "null", "description": "Custom content view builder function" }, + "footerView": { "type": "Function?", "default": "null", "description": "Custom footer view builder function" }, + "bottomView": { "type": "Function?", "default": "null", "description": "Custom bottom view builder function" }, + "bubbleView": { "type": "Function?", "default": "null", "description": "Replaces entire bubble" }, + "statusInfoView": { "type": "Function?", "default": "null", "description": "Custom status info view builder function" }, + "replyView": { "type": "Function?", "default": "null", "description": "Custom reply preview builder function" }, + "threadView": { "type": "Function?", "default": "null", "description": "Custom thread view builder function" }, + "options": { "type": "Function", "description": "Returns action sheet items for long-press" } + }, + "relatedComponents": ["CometChatMessageList"], + "events": null +} +``` + + ## Overview A MessageTemplate provides you with the capability to define and customize both the structure and the behavior of the [MessageBubble](/ui-kit/flutter/message-bubble-styling). It acts as a schema or design blueprint for the creation of a variety of [MessageBubble](/ui-kit/flutter/message-bubble-styling) widgets, allowing you to manage the appearance and interactions of [MessageBubble](/ui-kit/flutter/message-bubble-styling) within your application effectively and consistently. diff --git a/ui-kit/flutter/outgoing-call.mdx b/ui-kit/flutter/outgoing-call.mdx index 2bbc3a3fa..1a73ce2eb 100644 --- a/ui-kit/flutter/outgoing-call.mdx +++ b/ui-kit/flutter/outgoing-call.mdx @@ -1,6 +1,51 @@ --- title: "Outgoing Call" +description: "Widget that serves as a visual representation of a user-initiated call, providing options to control the call experience." --- + +```json +{ + "component": "CometChatOutgoingCall", + "package": "cometchat_calls_uikit", + "import": "import 'package:cometchat_calls_uikit/cometchat_calls_uikit.dart';", + "description": "Widget that serves as a visual representation of a user-initiated call, providing options to control the call experience.", + "props": { + "data": { + "call": { "type": "Call", "required": true }, + "user": { "type": "User?", "default": "null" } + }, + "callbacks": { + "onCancelled": "Function(BuildContext context, Call call)?", + "onError": "OnError?" + }, + "viewSlots": { + "subtitleView": "Widget? Function(BuildContext context, Call call)?", + "avatarView": "Widget? Function(BuildContext context, Call call)?", + "titleView": "Widget? Function(BuildContext context, Call call)?", + "cancelledView": "Widget? Function(BuildContext context, Call call)?" + }, + "style": { + "outgoingCallStyle": "CometChatOutgoingCallStyle?" + }, + "layout": { + "height": { "type": "double?", "default": "null" }, + "width": { "type": "double?", "default": "null" } + }, + "icons": { + "declineButtonIcon": "Widget?" + }, + "sound": { + "disableSoundForCalls": { "type": "bool?", "default": "false" }, + "customSoundForCalls": "String?", + "customSoundForCallsPackage": "String?" + }, + "configuration": { + "callSettingsBuilder": "CallSettingsBuilder?" + } + } +} +``` + ## Overview From cc6825592283a3f4ad197d47681f9df7a8d7d2fe Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 18:48:25 +0530 Subject: [PATCH 044/106] Update troubleshooting.mdx --- ui-kit/flutter/troubleshooting.mdx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ui-kit/flutter/troubleshooting.mdx b/ui-kit/flutter/troubleshooting.mdx index 51c28fda8..dd24b6e9f 100644 --- a/ui-kit/flutter/troubleshooting.mdx +++ b/ui-kit/flutter/troubleshooting.mdx @@ -204,7 +204,4 @@ void dispose() { ## Getting Help If you're still experiencing issues: - -1. Check the [CometChat Documentation](https://www.cometchat.com/docs) -2. Search the [GitHub Issues](https://github.com/cometchat/cometchat-uikit-flutter/issues) -3. Contact [CometChat Support](https://www.cometchat.com/support) +- Contact [CometChat Support](https://www.cometchat.com/support) From d37dbde8a4deda323c8a3255e2a07df1b899ca64 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 18:58:22 +0530 Subject: [PATCH 045/106] from V4 to V5 --- ui-kit/flutter/property-changes.mdx | 2 +- ui-kit/flutter/upgrading-from-v4.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-kit/flutter/property-changes.mdx b/ui-kit/flutter/property-changes.mdx index c38585b34..8014bc558 100644 --- a/ui-kit/flutter/property-changes.mdx +++ b/ui-kit/flutter/property-changes.mdx @@ -1,5 +1,5 @@ --- -title: "Property Changes" +title: "Property changes from V4 to V5" --- ## Conversations diff --git a/ui-kit/flutter/upgrading-from-v4.mdx b/ui-kit/flutter/upgrading-from-v4.mdx index c2e9183e0..201b44f7c 100644 --- a/ui-kit/flutter/upgrading-from-v4.mdx +++ b/ui-kit/flutter/upgrading-from-v4.mdx @@ -1,5 +1,5 @@ --- -title: "Upgrading From V4" +title: "Upgrading from V4 to V5" --- From db4b840e9428b37a43deceeac408a199577d7ae7 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 18:59:17 +0530 Subject: [PATCH 046/106] mintlify component --- ui-kit/flutter/color-resources.mdx | 12 ++++ ui-kit/flutter/component-styling.mdx | 92 ++++++++++++++++++++++++++ ui-kit/flutter/message-header.mdx | 68 +++++++++++++++++++ ui-kit/flutter/theme-introduction.mdx | 27 ++++++-- ui-kit/flutter/url-formatter-guide.mdx | 28 ++++++++ 5 files changed, 220 insertions(+), 7 deletions(-) diff --git a/ui-kit/flutter/color-resources.mdx b/ui-kit/flutter/color-resources.mdx index 5ac72fe51..4ec539b47 100644 --- a/ui-kit/flutter/color-resources.mdx +++ b/ui-kit/flutter/color-resources.mdx @@ -124,6 +124,8 @@ description: "Complete reference for CometChatColorPalette tokens in Flutter UI + + ```dart ThemeData( extensions: [ @@ -147,6 +149,8 @@ ThemeData( ], ) ``` + + --- @@ -156,6 +160,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -178,6 +184,8 @@ ThemeData( ], ) ``` + + --- @@ -187,6 +195,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -209,3 +219,5 @@ ThemeData( ], ) ``` + + diff --git a/ui-kit/flutter/component-styling.mdx b/ui-kit/flutter/component-styling.mdx index 5ca6af35a..c3fd79f62 100644 --- a/ui-kit/flutter/component-styling.mdx +++ b/ui-kit/flutter/component-styling.mdx @@ -30,6 +30,8 @@ Style individual components by adding their style classes to `ThemeData.extensio + + ```dart ThemeData( extensions: [ @@ -45,6 +47,8 @@ ThemeData( ], ) ``` + + ### Message List @@ -52,6 +56,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -64,6 +70,8 @@ ThemeData( ], ) ``` + + ### Message Composer @@ -71,6 +79,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -82,6 +92,8 @@ ThemeData( ], ) ``` + + ### Message Header @@ -89,6 +101,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -105,6 +119,8 @@ ThemeData( ], ) ``` + + ### Users @@ -112,6 +128,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -127,6 +145,8 @@ ThemeData( ], ) ``` + + ### Groups @@ -134,6 +154,8 @@ ThemeData( + + ```dart ThemeData( extensions: [ @@ -149,9 +171,13 @@ ThemeData( ], ) ``` + + ### Group Members + + ```dart ThemeData( extensions: [ @@ -173,6 +199,8 @@ ThemeData( ], ) ``` + + --- @@ -184,12 +212,16 @@ ThemeData( + + ```dart CometChatAvatarStyle( borderRadius: BorderRadius.circular(8), backgroundColor: Color(0xFFFBAA75), ) ``` + + ### Badge @@ -197,12 +229,16 @@ CometChatAvatarStyle( + + ```dart CometChatBadgeStyle( borderRadius: BorderRadius.circular(4), backgroundColor: Color(0xFFF44649), ) ``` + + ### Status Indicator @@ -210,12 +246,16 @@ CometChatBadgeStyle( + + ```dart CometChatStatusIndicatorStyle( backgroundColor: Color(0xFFFFAB00), borderRadius: BorderRadius.circular(2), ) ``` + + ### Receipts @@ -223,11 +263,15 @@ CometChatStatusIndicatorStyle( + + ```dart CometChatMessageReceiptStyle( readIconColor: Color(0xFFFFAB00), ) ``` + + ### Reactions @@ -235,23 +279,33 @@ CometChatMessageReceiptStyle( + + ```dart CometChatReactionsStyle( borderRadius: BorderRadius.circular(8), ) ``` + + ### Reaction List + + ```dart CometChatReactionListStyle( activeTabTextColor: Color(0xFFF76808), activeTabIndicatorColor: Color(0xFFF76808), ) ``` + + ### Media Recorder + + ```dart CometChatMediaRecorderStyle( recordIndicatorBackgroundColor: Color(0xFFF44649), @@ -261,6 +315,8 @@ CometChatMediaRecorderStyle( stopButtonBorderRadius: BorderRadius.circular(8), ) ``` + + --- @@ -268,6 +324,8 @@ CometChatMediaRecorderStyle( ### Message Option Sheet + + ```dart ThemeData( extensions: [ @@ -278,9 +336,13 @@ ThemeData( ], ) ``` + + ### Attachment Option Sheet + + ```dart ThemeData( extensions: [ @@ -291,9 +353,13 @@ ThemeData( ], ) ``` + + ### Message Information + + ```dart ThemeData( extensions: [ @@ -309,9 +375,13 @@ ThemeData( ], ) ``` + + ### Mentions + + ```dart ThemeData( extensions: [ @@ -324,6 +394,8 @@ ThemeData( ], ) ``` + + --- @@ -335,12 +407,16 @@ ThemeData( + + ```dart CometChatAIConversationStarterStyle( backgroundColor: Color(0xFFFEEDE1), border: Border.all(color: Color(0xFFFBBB90)), ) ``` + + ### Smart Replies @@ -348,6 +424,8 @@ CometChatAIConversationStarterStyle( + + ```dart CometChatAISmartRepliesStyle( backgroundColor: Color(0xFFFEEDE1), @@ -356,27 +434,39 @@ CometChatAISmartRepliesStyle( itemBorder: Border.all(color: Color(0xFFFBBB90)), ) ``` + + ### Conversation Summary + + ```dart CometChatAIConversationSummaryStyle( backgroundColor: Color(0xFFFEEDE1), titleStyle: TextStyle(color: Color(0xFFF76808)), ) ``` + + ### AI Option Sheet + + ```dart CometChatAiOptionSheetStyle( backgroundColor: Color(0xFFFFF9F5), iconColor: Color(0xFFF76808), ) ``` + + ### AI Assistant Chat History + + ```dart final ccColor = CometChatThemeHelper.getColorPalette(context); @@ -396,3 +486,5 @@ CometChatAIAssistantChatHistory( ), ) ``` + + diff --git a/ui-kit/flutter/message-header.mdx b/ui-kit/flutter/message-header.mdx index ab5ee45dc..3cc79020d 100644 --- a/ui-kit/flutter/message-header.mdx +++ b/ui-kit/flutter/message-header.mdx @@ -1,6 +1,74 @@ --- title: "Message Header" +description: "Widget that showcases the User or Group details in the toolbar with typing indicator and back navigation button." --- + +```json +{ + "component": "CometChatMessageHeader", + "package": "cometchat_chat_uikit", + "import": "import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart';", + "description": "Widget that showcases the User or Group details in the toolbar with typing indicator and back navigation button.", + "props": { + "data": { + "user": { "type": "User?", "default": "null" }, + "group": { "type": "Group?", "default": "null" } + }, + "callbacks": { + "onBack": "VoidCallback?", + "newChatButtonClick": "VoidCallback?", + "chatHistoryButtonClick": "VoidCallback?" + }, + "visibility": { + "showBackButton": { "type": "bool?", "default": "true" }, + "hideVideoCallButton": { "type": "bool?", "default": "false" }, + "hideVoiceCallButton": { "type": "bool?", "default": "false" }, + "usersStatusVisibility": { "type": "bool?", "default": "true" }, + "hideNewChatButton": { "type": "bool?", "default": "false" }, + "hideChatHistoryButton": { "type": "bool?", "default": "false" } + }, + "viewSlots": { + "backButton": "WidgetBuilder?", + "subtitleView": "Widget? Function(Group? group, User? user, BuildContext context)?", + "listItemView": "Widget Function(Group? group, User? user, BuildContext context)?", + "trailingView": "List? Function(User? user, Group? group, BuildContext context)?", + "leadingStateView": "Widget? Function(Group? group, User? user, BuildContext context)?", + "titleView": "Widget? Function(Group? group, User? user, BuildContext context)?", + "auxiliaryButtonView": "Widget? Function(Group? group, User? user, BuildContext context)?" + }, + "style": { + "messageHeaderStyle": "CometChatMessageHeaderStyle?", + "listItemStyle": "ListItemStyle?" + }, + "layout": { + "avatarHeight": { "type": "double?", "default": "null" }, + "avatarWidth": { "type": "double?", "default": "null" }, + "height": { "type": "double?", "default": "65" }, + "padding": { "type": "EdgeInsetsGeometry?", "default": "null" } + }, + "icons": { + "menuIcon": "Widget?", + "newChatIcon": "IconData?", + "chatHistoryIcon": "IconData?" + }, + "formatting": { + "dateTimeFormatterCallback": "DateTimeFormatterCallback?" + } + }, + "sdkListeners": [ + "onUserOnline", + "onUserOffline", + "onTypingStarted", + "onTypingEnded", + "onGroupMemberJoined", + "onGroupMemberLeft", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup" + ] +} +``` + ## Overview diff --git a/ui-kit/flutter/theme-introduction.mdx b/ui-kit/flutter/theme-introduction.mdx index 984444790..417ff033b 100644 --- a/ui-kit/flutter/theme-introduction.mdx +++ b/ui-kit/flutter/theme-introduction.mdx @@ -60,6 +60,8 @@ Theming controls the look and feel of the chat UI — colors, fonts, and spacing Override theme properties in your `MaterialApp`: + + ```dart title="main.dart" MaterialApp( theme: ThemeData( @@ -75,6 +77,8 @@ MaterialApp( home: MyApp(), ) ``` + + --- @@ -84,7 +88,9 @@ MaterialApp( -```dart title="Light Theme" + + +```dart ThemeData( extensions: [ CometChatColorPalette( @@ -97,12 +103,9 @@ ThemeData( ], ) ``` - - - - - -```dart title="Dark Theme" + + +```dart ThemeData( extensions: [ CometChatColorPalette( @@ -115,6 +118,12 @@ ThemeData( ], ) ``` + + + + + + --- @@ -124,6 +133,8 @@ ThemeData( + + ```dart ThemeData( fontFamily: 'Times New Roman', @@ -136,6 +147,8 @@ ThemeData( ], ) ``` + + --- diff --git a/ui-kit/flutter/url-formatter-guide.mdx b/ui-kit/flutter/url-formatter-guide.mdx index 6627d0be0..b66fe6a6e 100644 --- a/ui-kit/flutter/url-formatter-guide.mdx +++ b/ui-kit/flutter/url-formatter-guide.mdx @@ -48,17 +48,23 @@ The `CometChatUrlFormatter` is automatically applied to messages. URLs are: The URL formatter is included by default. No additional setup required. + + ```dart CometChatMessageList( user: chatUser, // URL formatter is automatically included ) ``` + + ### Custom URL Formatter Create a custom URL formatter with your own styling and behavior. + + ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; @@ -113,9 +119,13 @@ class CustomUrlFormatter extends CometChatUrlFormatter { } } ``` + + ### Apply Custom Formatter + + ```dart CometChatMessageList( user: chatUser, @@ -125,6 +135,8 @@ CometChatMessageList( ], ) ``` + + --- @@ -134,6 +146,8 @@ CometChatMessageList( Override `getMessageBubbleTextStyle` to customize link appearance: + + ```dart @override TextStyle getMessageBubbleTextStyle( @@ -155,11 +169,15 @@ TextStyle getMessageBubbleTextStyle( ); } ``` + + ### Custom URL Pattern Use a custom regex pattern to match specific URL formats: + + ```dart CometChatUrlFormatter( pattern: RegExp( @@ -167,11 +185,15 @@ CometChatUrlFormatter( ), ) ``` + + ### Handle URL Clicks Override `getAttributedText` to add custom click handling: + + ```dart @override List getAttributedText( @@ -213,6 +235,8 @@ List getAttributedText( ); } ``` + + --- @@ -229,6 +253,8 @@ List getAttributedText( ## Complete Example + + ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:flutter/material.dart'; @@ -279,6 +305,8 @@ class _UrlFormatterExampleState extends State { } } ``` + + --- From 314a74f9ce34cbd8464818f5f69f64e78bbc24eb Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 4 Mar 2026 19:29:52 +0530 Subject: [PATCH 047/106] Update docs.json --- docs.json | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/docs.json b/docs.json index f12ad9f4f..359a41f34 100644 --- a/docs.json +++ b/docs.json @@ -1839,12 +1839,7 @@ { "group": " ", "pages": [ - { - "group": "Overview", - "pages": [ - "ui-kit/flutter/overview" - ] - }, + "ui-kit/flutter/overview", { "group": "Getting Started", "pages": [ From 91ede9682dcdf2f8d51c29327987291499e50657 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 5 Mar 2026 12:05:45 +0530 Subject: [PATCH 048/106] Update .gitignore --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 96adadbc8..d392eca55 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ .DS_Store .kiro/ +/codebase +/prompts +/docs-test-suite +/doc-auditor From 8b9c371cf7d00b2e4f4709c25eae13f0e747a942 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 5 Mar 2026 23:01:05 +0530 Subject: [PATCH 049/106] updates format of docs --- ui-kit/ios/conversations.mdx | 976 +++++++++++++++----- ui-kit/ios/group-members.mdx | 840 ++++++++++++------ ui-kit/ios/groups.mdx | 1192 +++++++++++++------------ ui-kit/ios/message-composer.mdx | 986 ++++++++++----------- ui-kit/ios/message-header.mdx | 867 +++++++++--------- ui-kit/ios/message-list.mdx | 1470 +++++++++++++++++-------------- ui-kit/ios/search.mdx | 140 ++- ui-kit/ios/users.mdx | 1239 +++++++++++++++----------- 8 files changed, 4507 insertions(+), 3203 deletions(-) diff --git a/ui-kit/ios/conversations.mdx b/ui-kit/ios/conversations.mdx index c62e53e11..5afcc86d4 100644 --- a/ui-kit/ios/conversations.mdx +++ b/ui-kit/ios/conversations.mdx @@ -9,34 +9,112 @@ The `CometChatConversations` component displays a list of all conversations (one -## Prerequisites - -Before using this component, ensure you have: - -1. [Initialized the CometChat UI Kit](/ui-kit/ios/getting-started) -2. [Logged in a user](/ui-kit/ios/getting-started#login) - -## Basic Usage - -```swift -import CometChatUIKitSwift - -class ConversationsViewController: UIViewController { - - override func viewDidLoad() { - super.viewDidLoad() - - let conversations = CometChatConversations() - - // Push to navigation stack - navigationController?.pushViewController(conversations, animated: true) + +```json +{ + "component": "CometChatConversations", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays a list of all conversations for the logged-in user with real-time updates for messages, typing indicators, and presence.", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onItemClick", + "type": "(Conversation, IndexPath) -> Void" + }, + "props": { + "data": { + "conversationRequestBuilder": { + "type": "ConversationRequest.ConversationRequestBuilder?", + "default": "nil", + "note": "Custom request builder for filtering conversations" + } + }, + "callbacks": { + "onItemClick": "(Conversation, IndexPath) -> Void", + "onItemLongClick": "(Conversation, IndexPath) -> Void", + "onBack": "() -> Void", + "onSelection": "([Conversation]) -> Void", + "onError": "(CometChatException) -> Void", + "onEmpty": "() -> Void", + "onLoad": "([Conversation]) -> Void" + }, + "visibility": { + "hideSearch": { "type": "Bool", "default": false }, + "hideReceipts": { "type": "Bool", "default": false }, + "hideUserStatus": { "type": "Bool", "default": false }, + "hideGroupType": { "type": "Bool", "default": false }, + "hideDeleteConversationOption": { "type": "Bool", "default": false }, + "hideNavigationBar": { "type": "Bool", "default": false }, + "hideBackButton": { "type": "Bool", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "Bool", "default": false }, + "customSoundForMessages": { "type": "URL?", "default": "nil" } + }, + "selection": { + "selectionMode": { "type": "SelectionMode", "default": ".none" } + }, + "viewSlots": { + "listItemView": "(Conversation) -> UIView", + "leadingView": "(Conversation) -> UIView", + "titleView": "(Conversation) -> UIView", + "subtitleView": "(Conversation) -> UIView", + "tailView": "(Conversation) -> UIView", + "emptyStateView": "() -> UIView", + "errorStateView": "() -> UIView", + "loadingStateView": "() -> UIView" + }, + "formatting": { + "datePattern": "(Conversation) -> String", + "textFormatters": "[CometChatTextFormatter]" + } + }, + "events": [ + { + "name": "ccConversationDelete", + "payload": "Conversation", + "description": "Fires when a conversation is deleted" + } + ], + "sdkListeners": [ + "onMessageReceived", + "onMessageEdited", + "onMessageDeleted", + "onTypingStarted", + "onTypingEnded", + "onUserOnline", + "onUserOffline", + "onGroupMemberJoined", + "onGroupMemberLeft" + ], + "compositionExample": { + "description": "Conversations list navigating to Messages", + "components": ["CometChatConversations", "CometChatMessages"], + "flow": "User taps conversation → onItemClick fires → Navigate to CometChatMessages with user/group" + }, + "types": { + "Conversation": { + "conversationId": "String?", + "conversationType": "ConversationType", + "conversationWith": "AppEntity?", + "lastMessage": "BaseMessage?", + "unreadMessageCount": "Int" + }, + "ConversationType": { + "user": "One-on-one conversation", + "group": "Group conversation", + "both": "All conversation types" } + } } ``` + -## Production-Ready Implementation +--- + +## Where It Fits -This example shows a complete conversations screen with navigation to messages, custom filtering, and error handling: +`CometChatConversations` serves as the main entry point for chat functionality. It displays all conversations and navigates to `CometChatMessages` when a conversation is selected. ```swift import UIKit @@ -53,105 +131,217 @@ class ChatListViewController: UIViewController { } private func setupConversations() { - // Create custom request builder for filtering - let requestBuilder = ConversationRequest.ConversationRequestBuilder(limit: 30) - .set(conversationType: .both) // Show both user and group conversations - - // Initialize conversations component - conversationsController = CometChatConversations(conversationRequestBuilder: requestBuilder) + conversationsController = CometChatConversations() // Handle conversation selection - navigate to messages conversationsController.set(onItemClick: { [weak self] conversation, indexPath in self?.openMessages(for: conversation) }) - // Handle long press for additional options - conversationsController.set(onItemLongClick: { [weak self] conversation, indexPath in - self?.showConversationOptions(for: conversation) - }) - - // Handle errors - conversationsController.set(onError: { error in - print("Conversations error: \(error.errorDescription)") - }) - - // Handle empty state - conversationsController.set(onEmpty: { - print("No conversations found") - }) - - // Handle when conversations are loaded - conversationsController.set(onLoad: { conversations in - print("Loaded \(conversations.count) conversations") - }) - - // Present the conversations navigationController?.pushViewController(conversationsController, animated: true) } private func openMessages(for conversation: Conversation) { + let messagesVC = CometChatMessages() + if let user = conversation.conversationWith as? User { - let messagesVC = CometChatMessages() messagesVC.set(user: user) - navigationController?.pushViewController(messagesVC, animated: true) } else if let group = conversation.conversationWith as? Group { - let messagesVC = CometChatMessages() messagesVC.set(group: group) - navigationController?.pushViewController(messagesVC, animated: true) } + + navigationController?.pushViewController(messagesVC, animated: true) } +} +``` + + + + + +--- + +## Minimal Render + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() +navigationController?.pushViewController(conversations, animated: true) +``` + + + + + +--- + +## Filtering + +Use `ConversationRequest.ConversationRequestBuilder` to filter which conversations appear in the list. The builder pattern allows chaining multiple filter conditions. + +```swift +import CometChatUIKitSwift +import CometChatSDK + +// Create a custom request builder +let requestBuilder = ConversationRequest.ConversationRequestBuilder(limit: 30) + .set(conversationType: .both) + +let conversations = CometChatConversations(conversationRequestBuilder: requestBuilder) +``` + +### Filter Recipes + +| Recipe | Code | +|--------|------| +| Show only one-on-one chats | `.set(conversationType: .user)` | +| Show only group chats | `.set(conversationType: .group)` | +| Filter by tags | `.withTags(true).set(tags: ["support", "sales"])` | +| Limit results | `ConversationRequestBuilder(limit: 20)` | +| Include user/group tags | `.withUserAndGroupTags(true)` | + +--- + +## Actions and Events + +### Callback Props + +#### onItemClick + +Fires when a user taps on a conversation. Use this to navigate to the messages screen. + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +conversations.set(onItemClick: { [weak self] conversation, indexPath in + guard let self = self else { return } - private func showConversationOptions(for conversation: Conversation) { - let alert = UIAlertController(title: "Options", message: nil, preferredStyle: .actionSheet) - - alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { _ in - CometChat.deleteConversation( - conversationWith: conversation.conversationWith?.uid ?? "", - conversationType: conversation.conversationType - ) { success in - print("Conversation deleted") - } onError: { error in - print("Delete failed: \(error?.errorDescription ?? "")") - } - }) - - alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) - present(alert, animated: true) + let messagesVC = CometChatMessages() + + if let user = conversation.conversationWith as? User { + messagesVC.set(user: user) + } else if let group = conversation.conversationWith as? Group { + messagesVC.set(group: group) + } + + self.navigationController?.pushViewController(messagesVC, animated: true) +}) +``` + +#### onItemLongClick + +Fires when a user long-presses on a conversation. Use this to show additional options like delete or mute. + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +conversations.set(onItemLongClick: { [weak self] conversation, indexPath in + guard let self = self else { return } + + let alert = UIAlertController(title: "Options", message: nil, preferredStyle: .actionSheet) + + alert.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] _ in + self?.deleteConversation(conversation) + }) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + self.present(alert, animated: true) +}) + +// Helper method to delete conversation using SDK +private func deleteConversation(_ conversation: Conversation) { + CometChat.deleteConversation( + conversationWith: conversation.conversationWith?.uid ?? "", + conversationType: conversation.conversationType + ) { success in + print("Conversation deleted successfully") + } onError: { error in + print("Delete failed: \(error?.errorDescription ?? "")") } } ``` -## Filter Conversations +#### onBack -Use `ConversationRequestBuilder` to filter which conversations appear: +Fires when the back button is pressed. Use this for custom navigation handling. ```swift -// Show only one-on-one conversations -let userOnlyBuilder = ConversationRequest.ConversationRequestBuilder(limit: 20) - .set(conversationType: .user) +import CometChatUIKitSwift + +let conversations = CometChatConversations() -let conversations = CometChatConversations(conversationRequestBuilder: userOnlyBuilder) +conversations.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) +}) ``` +#### onSelection + +Fires when conversations are selected in selection mode. Returns the list of selected conversations. + ```swift -// Show only group conversations -let groupOnlyBuilder = ConversationRequest.ConversationRequestBuilder(limit: 20) - .set(conversationType: .group) +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() +conversations.selectionMode = .multiple -let conversations = CometChatConversations(conversationRequestBuilder: groupOnlyBuilder) +conversations.set(onSelection: { [weak self] selectedConversations in + print("Selected \(selectedConversations.count) conversations") +}) ``` +#### onError + +Fires when an error occurs while loading conversations. + ```swift -// Filter by tags -let taggedBuilder = ConversationRequest.ConversationRequestBuilder(limit: 20) - .set(conversationType: .both) - .withTags(true) - .set(tags: ["support", "sales"]) +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +conversations.set(onError: { error in + print("Error loading conversations: \(error.errorDescription)") +}) +``` + +#### onEmpty + +Fires when the conversation list is empty. + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() -let conversations = CometChatConversations(conversationRequestBuilder: taggedBuilder) +conversations.set(onEmpty: { + print("No conversations found") +}) ``` -## Actions Reference +#### onLoad + +Fires when conversations are successfully loaded. + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +conversations.set(onLoad: { conversations in + print("Loaded \(conversations.count) conversations") +}) +``` + +### Actions Reference | Method | Description | Example | |--------|-------------|---------| @@ -163,66 +353,74 @@ let conversations = CometChatConversations(conversationRequestBuilder: taggedBui | `set(onEmpty:)` | Triggered when list is empty | Show empty state | | `set(onLoad:)` | Triggered when conversations load | Analytics tracking | -## Styling +### Global UI Events -### Quick Styling +| Event | Fires when | Payload | +|-------|------------|---------| +| `ccConversationDelete` | A conversation is deleted | `Conversation` | ```swift -let conversations = CometChatConversations() - -// Apply custom colors -CometChatConversation.style.backgroundColor = .systemBackground -CometChatConversation.style.lastMessageTextColor = .secondaryLabel -CometChatConversation.style.typingIndicatorColor = .systemGreen - -// Custom avatar style -let avatarStyle = AvatarStyle() -avatarStyle.backgroundColor = UIColor(hex: "#6851D6") -avatarStyle.cornerRadius = 8 -CometChatConversation.style.avatarStyle = avatarStyle +import CometChatUIKitSwift +import CometChatSDK -// Custom badge style for unread count -let badgeStyle = BadgeStyle() -badgeStyle.backgroundColor = UIColor(hex: "#F44649") -badgeStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 10) -CometChatConversation.style.badgeStyle = badgeStyle +class MyViewController: UIViewController, CometChatConversationEventListener { + + override func viewDidLoad() { + super.viewDidLoad() + CometChatConversationEvents.addListener("my-listener", self) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatConversationEvents.removeListener("my-listener") + } + + func ccConversationDelete(conversation: Conversation) { + print("Conversation deleted: \(conversation.conversationId ?? "")") + } +} ``` -### Style Properties - -| Property | Description | -|----------|-------------| -| `backgroundColor` | Background color of the list | -| `lastMessageTextColor` | Color of the last message preview | -| `typingIndicatorColor` | Color of "typing..." indicator | -| `separatorColor` | Color of row separators | -| `avatarStyle` | Style for user/group avatars | -| `badgeStyle` | Style for unread message count | -| `receiptStyle` | Style for read/delivered receipts | -| `dateStyle` | Style for timestamp labels | +### SDK Events (Real-Time, Automatic) -## Hide UI Elements +| SDK Listener | Internal behavior | +|--------------|-------------------| +| `onMessageReceived` | Updates last message and moves conversation to top | +| `onMessageEdited` | Updates last message preview if edited message is latest | +| `onMessageDeleted` | Updates last message preview if deleted message was latest | +| `onTypingStarted` | Shows typing indicator for the conversation | +| `onTypingEnded` | Hides typing indicator for the conversation | +| `onUserOnline` | Updates online status indicator for user conversations | +| `onUserOffline` | Updates offline status indicator for user conversations | +| `onGroupMemberJoined` | Updates group member count | +| `onGroupMemberLeft` | Updates group member count | -```swift -let conversations = CometChatConversations() +--- -// Hide elements as needed -conversations.hideSearch = true // Hide search bar -conversations.hideReceipts = true // Hide read/delivered receipts -conversations.hideUserStatus = true // Hide online/offline status -conversations.hideGroupType = true // Hide public/private group icons -conversations.hideDeleteConversationOption = true // Hide delete option -conversations.hideNavigationBar = true // Hide navigation bar -conversations.hideBackButton = true // Hide back button -``` +## Custom View Slots -## Custom Views +| Slot | Signature | Replaces | +|------|-----------|----------| +| `listItemView` | `(Conversation) -> UIView` | Entire conversation row | +| `leadingView` | `(Conversation) -> UIView` | Avatar / left section | +| `titleView` | `(Conversation) -> UIView` | Name / title text | +| `subtitleView` | `(Conversation) -> UIView` | Last message preview | +| `tailView` | `(Conversation) -> UIView` | Right side (time, badge) | +| `emptyStateView` | `() -> UIView` | Empty state display | +| `errorStateView` | `() -> UIView` | Error state display | +| `loadingStateView` | `() -> UIView` | Loading state display | -### Custom List Item +### listItemView -Replace the entire conversation row with your own design: +Replace the entire conversation row with a custom design. ```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + conversations.set(listItemView: { conversation in let customView = CustomConversationCell() customView.configure(with: conversation) @@ -238,7 +436,6 @@ class CustomConversationCell: UIView { private let nameLabel = UILabel() private let messageLabel = UILabel() private let timeLabel = UILabel() - private let unreadBadge = UILabel() override init(frame: CGRect) { super.init(frame: frame) @@ -250,119 +447,329 @@ class CustomConversationCell: UIView { } private func setupUI() { - avatarView.translatesAutoresizingMaskIntoConstraints = false - nameLabel.translatesAutoresizingMaskIntoConstraints = false - messageLabel.translatesAutoresizingMaskIntoConstraints = false - timeLabel.translatesAutoresizingMaskIntoConstraints = false - unreadBadge.translatesAutoresizingMaskIntoConstraints = false + nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .semibold) + messageLabel.font = UIFont.systemFont(ofSize: 14) + messageLabel.textColor = UIColor.secondaryLabel + timeLabel.font = UIFont.systemFont(ofSize: 12) + timeLabel.textColor = UIColor.tertiaryLabel - nameLabel.font = .systemFont(ofSize: 16, weight: .semibold) - messageLabel.font = .systemFont(ofSize: 14) - messageLabel.textColor = .secondaryLabel - timeLabel.font = .systemFont(ofSize: 12) - timeLabel.textColor = .tertiaryLabel - - unreadBadge.font = .systemFont(ofSize: 12, weight: .bold) - unreadBadge.textColor = .white - unreadBadge.backgroundColor = .systemBlue - unreadBadge.textAlignment = .center - unreadBadge.layer.cornerRadius = 10 - unreadBadge.clipsToBounds = true - - addSubview(avatarView) - addSubview(nameLabel) - addSubview(messageLabel) - addSubview(timeLabel) - addSubview(unreadBadge) - - NSLayoutConstraint.activate([ - avatarView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), - avatarView.centerYAnchor.constraint(equalTo: centerYAnchor), - avatarView.widthAnchor.constraint(equalToConstant: 50), - avatarView.heightAnchor.constraint(equalToConstant: 50), - - nameLabel.leadingAnchor.constraint(equalTo: avatarView.trailingAnchor, constant: 12), - nameLabel.topAnchor.constraint(equalTo: avatarView.topAnchor, constant: 4), - nameLabel.trailingAnchor.constraint(lessThanOrEqualTo: timeLabel.leadingAnchor, constant: -8), - - messageLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor), - messageLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 4), - messageLabel.trailingAnchor.constraint(lessThanOrEqualTo: unreadBadge.leadingAnchor, constant: -8), - - timeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), - timeLabel.topAnchor.constraint(equalTo: nameLabel.topAnchor), - - unreadBadge.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), - unreadBadge.centerYAnchor.constraint(equalTo: messageLabel.centerYAnchor), - unreadBadge.widthAnchor.constraint(greaterThanOrEqualToConstant: 20), - unreadBadge.heightAnchor.constraint(equalToConstant: 20) - ]) + // Add subviews and constraints... } func configure(with conversation: Conversation) { - var name = "" - var avatarURL: String? - if let user = conversation.conversationWith as? User { - name = user.name ?? "" - avatarURL = user.avatar + nameLabel.text = user.name + avatarView.setAvatar(avatarUrl: user.avatar, with: user.name ?? "") } else if let group = conversation.conversationWith as? Group { - name = group.name ?? "" - avatarURL = group.icon + nameLabel.text = group.name + avatarView.setAvatar(avatarUrl: group.icon, with: group.name ?? "") } - nameLabel.text = name - avatarView.setAvatar(avatarUrl: avatarURL, with: name) - - // Set last message if let textMessage = conversation.lastMessage as? TextMessage { messageLabel.text = textMessage.text - } else if conversation.lastMessage is MediaMessage { - messageLabel.text = "📎 Attachment" - } else { - messageLabel.text = "No messages yet" } - - // Set time - if let sentAt = conversation.lastMessage?.sentAt { - let date = Date(timeIntervalSince1970: TimeInterval(sentAt)) - let formatter = DateFormatter() - formatter.dateFormat = "h:mm a" - timeLabel.text = formatter.string(from: date) - } - - // Set unread count - let unreadCount = conversation.unreadMessageCount - unreadBadge.isHidden = unreadCount == 0 - unreadBadge.text = unreadCount > 99 ? "99+" : "\(unreadCount)" } } ``` -### Custom Subtitle View +### subtitleView -Customize just the subtitle area (below the name): +Customize just the subtitle area below the conversation name. ```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + conversations.set(subtitleView: { conversation in let label = UILabel() - label.font = .systemFont(ofSize: 13) - label.textColor = .secondaryLabel + label.font = UIFont.systemFont(ofSize: 13) + label.textColor = UIColor.secondaryLabel if let textMessage = conversation.lastMessage as? TextMessage { label.text = textMessage.text } else if conversation.lastMessage is MediaMessage { label.text = "📷 Photo" + } else { + label.text = "No messages yet" } return label }) ``` -### Custom Date Format +### tailView + +Customize the right side of the conversation row (time, unread badge). Note: The setter method is `set(trailView:)`. ```swift -conversations.set(datePattern: { conversation in +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +conversations.set(trailView: { conversation in + let stackView = UIStackView() + stackView.axis = .vertical + stackView.alignment = .trailing + stackView.spacing = 4 + + // Time label + let timeLabel = UILabel() + timeLabel.font = UIFont.systemFont(ofSize: 12) + timeLabel.textColor = UIColor.tertiaryLabel + + if let sentAt = conversation.lastMessage?.sentAt { + let date = Date(timeIntervalSince1970: TimeInterval(sentAt)) + let formatter = DateFormatter() + formatter.dateFormat = "h:mm a" + timeLabel.text = formatter.string(from: date) + } + + stackView.addArrangedSubview(timeLabel) + + // Unread badge + if conversation.unreadMessageCount > 0 { + let badge = UILabel() + badge.text = "\(conversation.unreadMessageCount)" + badge.font = UIFont.systemFont(ofSize: 12, weight: .bold) + badge.textColor = UIColor.white + badge.backgroundColor = UIColor.systemRed + badge.textAlignment = .center + badge.layer.cornerRadius = 10 + badge.clipsToBounds = true + badge.widthAnchor.constraint(greaterThanOrEqualToConstant: 20).isActive = true + badge.heightAnchor.constraint(equalToConstant: 20).isActive = true + stackView.addArrangedSubview(badge) + } + + return stackView +}) +``` + +--- + +## Styling + +### Style Hierarchy + +1. Global styles (`CometChatConversation.style`) apply to all instances +2. Instance styles override global for specific instances + +### Global Level Styling + +```swift +import UIKit +import CometChatUIKitSwift + +// Apply global styles that affect all CometChatConversations instances +CometChatConversation.style.backgroundColor = UIColor.systemBackground +CometChatConversation.style.titleFont = UIFont.systemFont(ofSize: 17, weight: .bold) +CometChatConversation.style.titleColor = UIColor.label +CometChatConversation.style.listItemTitleTextColor = UIColor.label +CometChatConversation.style.listItemSubTitleTextColor = UIColor.secondaryLabel + +// Custom avatar style +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor(red: 0.41, green: 0.32, blue: 0.84, alpha: 1.0) +avatarStyle.cornerRadius = 8 +CometChatConversation.style.avatarStyle = avatarStyle + +// Custom badge style for unread count +let badgeStyle = BadgeStyle() +badgeStyle.backgroundColor = UIColor.systemRed +badgeStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 10) +CometChatConversation.style.badgeStyle = badgeStyle +``` + +### Instance Level Styling + +```swift +import UIKit +import CometChatUIKitSwift + +// Create a custom style for a specific instance +var customStyle = ConversationsStyle() +customStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +customStyle.titleColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) +customStyle.listItemBackground = UIColor.white +customStyle.listItemCornerRadius = CometChatCornerStyle(cornerRadius: 12) + +let conversations = CometChatConversations() +conversations.style = customStyle +``` + + + + + +### Key Style Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color of the list | +| `titleFont` | `UIFont?` | `CometChatTypography.setFont(size: 17, weight: .bold)` | Font for the navigation title | +| `titleColor` | `UIColor?` | `CometChatTheme.textColorPrimary` | Color for the navigation title | +| `listItemTitleTextColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Color for conversation names | +| `listItemTitleFont` | `UIFont` | `CometChatTypography.Heading4.medium` | Font for conversation names | +| `listItemSubTitleTextColor` | `UIColor` | `CometChatTheme.textColorSecondary` | Color for last message preview | +| `listItemSubTitleFont` | `UIFont` | `CometChatTypography.Body.regular` | Font for last message preview | +| `listItemBackground` | `UIColor` | `.clear` | Background color for list items | +| `listItemCornerRadius` | `CometChatCornerStyle` | `CometChatCornerStyle(cornerRadius: 0)` | Corner radius for list items | +| `borderWidth` | `CGFloat` | `0` | Border width for the component | +| `borderColor` | `UIColor` | `.clear` | Border color for the component | + +### Customization Matrix + +| What to change | Where | Property/API | Example | +|----------------|-------|--------------|---------| +| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | +| Title appearance | Style | `titleFont`, `titleColor` | `UIFont.boldSystemFont(ofSize: 18)` | +| List item look | Style | `listItemBackground` | `UIColor(white: 0.95, alpha: 1.0)` | +| Unread badge | Style | `badgeStyle` | `BadgeStyle()` with custom colors | +| Avatar appearance | Style | `avatarStyle` | `AvatarStyle()` with custom radius | +| Hide search | Property | `hideSearch` | `conversations.hideSearch = true` | +| Hide receipts | Property | `hideReceipts` | `conversations.hideReceipts = true` | +| Custom row | View Slot | `set(listItemView:)` | See Custom View Slots section | + +--- + +## Props + +All props are optional. Sorted alphabetically. + +### conversationRequestBuilder + +Custom request builder for filtering which conversations appear. + +| | | +|---|---| +| Type | `ConversationRequest.ConversationRequestBuilder?` | +| Default | `nil` | + +### customSoundForMessages + +Custom sound URL for new message notifications. + +| | | +|---|---| +| Type | `URL?` | +| Default | `nil` | + +### disableSoundForMessages + +Disables notification sounds for new messages. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideBackButton + +Hides the back button in the navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideDeleteConversationOption + +Hides the delete option in conversation actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideGroupType + +Hides the public/private group type icons. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideNavigationBar + +Hides the entire navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideReceipts + +Hides read/delivered receipt indicators. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideSearch + +Hides the search bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideUserStatus + +Hides online/offline status indicators. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### selectionMode + +Sets the selection mode for multi-select functionality. + +| | | +|---|---| +| Type | `SelectionMode` | +| Default | `.none` | + +### textFormatters + +Array of text formatters for customizing message text display. + +| | | +|---|---| +| Type | `[CometChatTextFormatter]` | +| Default | `[]` | + +--- + +## Events + +| Event | Payload | Fires when | +|-------|---------|------------| +| `ccConversationDelete` | `Conversation` | A conversation is deleted from the list | + +--- + +## Date Time Formatter + +Customize how timestamps appear in the conversation list using the `datePattern` callback. + +### Global Level Formatting + +```swift +import CometChatUIKitSwift + +// Set a global date pattern for all conversations instances +CometChatConversations.datePattern = { conversation in guard let sentAt = conversation.lastMessage?.sentAt else { return "" } let date = Date(timeIntervalSince1970: TimeInterval(sentAt)) @@ -376,37 +783,136 @@ conversations.set(datePattern: { conversation in formatter.dateFormat = "MMM d" } + return formatter.string(from: date) +} +``` + +### Instance Level Formatting + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +conversations.set(datePattern: { conversation in + guard let sentAt = conversation.lastMessage?.sentAt else { return "" } + + let date = Date(timeIntervalSince1970: TimeInterval(sentAt)) + let formatter = DateFormatter() + + if Calendar.current.isDateInToday(date) { + formatter.dateFormat = "HH:mm" // 24-hour format + } else if Calendar.current.isDateInYesterday(date) { + return "Yesterday" + } else if Calendar.current.isDate(date, equalTo: Date(), toGranularity: .weekOfYear) { + formatter.dateFormat = "EEEE" // Day name + } else { + formatter.dateFormat = "dd/MM/yy" + } + return formatter.string(from: date) }) ``` -## Listen for Events +### Available Formatters -React to conversation changes in your app: +| Formatter | Purpose | Default Format | +|-----------|---------|----------------| +| `datePattern` | Format for all timestamps | `h:mm a` for today, `MMM d` for older | + +### Common Customizations ```swift -class MyViewController: UIViewController, CometChatConversationEventListener { +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +// 24-hour time format +conversations.set(datePattern: { conversation in + guard let sentAt = conversation.lastMessage?.sentAt else { return "" } + let date = Date(timeIntervalSince1970: TimeInterval(sentAt)) + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + return formatter.string(from: date) +}) + +// Relative time (e.g., "2h ago") +conversations.set(datePattern: { conversation in + guard let sentAt = conversation.lastMessage?.sentAt else { return "" } + let date = Date(timeIntervalSince1970: TimeInterval(sentAt)) + let formatter = RelativeDateTimeFormatter() + formatter.unitsStyle = .abbreviated + return formatter.localizedString(for: date, relativeTo: Date()) +}) +``` + +--- + +## Mention Configuration + +Configure how @all mentions appear in conversation list items. When a message contains an @all mention, the conversation subtitle displays the mention with a customizable label. + +### setMentionAllLabel + +Sets a custom label for @all mentions displayed in conversation list items. + +```swift +@discardableResult +public func setMentionAllLabel(_ id: String, _ label: String) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `id` | `String` | The identifier for the @all mention (typically "all") | +| `label` | `String` | The display text shown to users when @all is mentioned | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +// Set a custom label for @all mentions +conversations.setMentionAllLabel("all", "Everyone") +``` + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class MentionConfiguredViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - CometChatConversationEvents.addListener("my-listener", self) - } - - override func viewWillDisappear(_ animated: Bool) { - super.viewWillDisappear(animated) - CometChatConversationEvents.removeListener("my-listener") + + let conversations = CometChatConversations() + .setMentionAllLabel("all", "Team Members") + .set(onItemClick: { [weak self] conversation, indexPath in + self?.openMessages(for: conversation) + }) + + navigationController?.pushViewController(conversations, animated: true) } - // Called when a conversation is deleted - func ccConversationDelete(conversation: Conversation) { - print("Conversation deleted: \(conversation.conversationId ?? "")") + private func openMessages(for conversation: Conversation) { + let messagesVC = CometChatMessages() + + if let user = conversation.conversationWith as? User { + messagesVC.set(user: user) + } else if let group = conversation.conversationWith as? Group { + messagesVC.set(group: group) + } + + navigationController?.pushViewController(messagesVC, animated: true) } } ``` +--- + ## Complete App Example -Here's a full implementation with tab bar integration: +Here's a full implementation with tab bar integration showing how to use CometChatConversations in a real app: ```swift import UIKit @@ -474,18 +980,24 @@ class ConversationsContainerViewController: UINavigationController { } ``` +--- + ## Troubleshooting | Issue | Solution | |-------|----------| | Empty conversation list | Ensure user is logged in and has existing conversations | -| Conversations not updating | Check that real-time listeners are active | -| Navigation not working | Verify `navigationController` is not nil | -| Custom views not appearing | Ensure custom view has proper constraints | +| Conversations not updating in real-time | Check that CometChat SDK is properly initialized and connected | +| Navigation not working | Verify `navigationController` is not nil; embed in UINavigationController | +| Custom views not appearing | Ensure custom view has proper constraints and non-zero frame | +| Typing indicator not showing | Verify `hideTypingIndicator` is not set to true | + +--- ## Related Components -- [Messages](/ui-kit/ios/message-header) - Display messages in a conversation +- [Messages](/ui-kit/ios/messages) - Display messages in a conversation - [Users](/ui-kit/ios/users) - List all users to start new conversations - [Groups](/ui-kit/ios/groups) - List all groups -- [Message Composer](/ui-kit/ios/message-composer) - Send messages +- [Message Composer](/ui-kit/ios/message-composer) - Send messages in a conversation +- [Conversation With Messages](/ui-kit/ios/conversation-with-messages) - Combined conversations and messages view diff --git a/ui-kit/ios/group-members.mdx b/ui-kit/ios/group-members.mdx index 3a5a9c3e7..88a9515ca 100644 --- a/ui-kit/ios/group-members.mdx +++ b/ui-kit/ios/group-members.mdx @@ -3,48 +3,131 @@ title: "Group Members" description: "Display and manage members of a CometChat group" --- -The `CometChatGroupMembers` component displays all members of a group with their roles (owner, admin, participant). It supports member management actions like kick, ban, and role changes. +The `CometChatGroupMembers` component displays all members of a group with their roles (owner, admin, moderator, participant). It supports member management actions like kick, ban, and role changes based on the logged-in user's permissions. -## Prerequisites - -Before using this component: -1. [Initialize CometChat UI Kit](/ui-kit/ios/getting-started) -2. [Log in a user](/ui-kit/ios/getting-started#step-4-initialize-and-login) -3. Have a valid `Group` object - -## Basic Usage - -```swift -import UIKit -import CometChatUIKitSwift -import CometChatSDK - -class GroupDetailViewController: UIViewController { - - var group: Group! - - func showGroupMembers() { - let groupMembers = CometChatGroupMembers(group: group) - let nav = UINavigationController(rootViewController: groupMembers) - present(nav, animated: true) + +```json +{ + "component": "CometChatGroupMembers", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays all members of a group with their roles and supports member management actions like kick, ban, and role changes.", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onItemClick", + "type": "(GroupMember, IndexPath) -> Void" + }, + "props": { + "data": { + "group": { + "type": "Group", + "required": true, + "note": "The group whose members to display" + }, + "groupMembersRequestBuilder": { + "type": "GroupMembersRequest.GroupMembersRequestBuilder?", + "default": "nil", + "note": "Custom request builder for filtering members" + } + }, + "callbacks": { + "onItemClick": "(GroupMember, IndexPath) -> Void", + "onItemLongClick": "(GroupMember, IndexPath) -> Void", + "onBack": "() -> Void", + "onSelection": "([GroupMember]) -> Void", + "onError": "(CometChatException) -> Void", + "onEmpty": "() -> Void", + "onLoad": "([GroupMember]) -> Void" + }, + "visibility": { + "hideSearch": { "type": "Bool", "default": false }, + "hideNavigationBar": { "type": "Bool", "default": false }, + "hideBackIcon": { "type": "Bool", "default": false }, + "hideUserStatus": { "type": "Bool", "default": false }, + "hideKickMemberOption": { "type": "Bool", "default": false }, + "hideBanMemberOption": { "type": "Bool", "default": false }, + "hideScopeChangeOption": { "type": "Bool", "default": false }, + "hideErrorView": { "type": "Bool", "default": false }, + "hideLoadingState": { "type": "Bool", "default": false } + }, + "selection": { + "selectionMode": { "type": "SelectionMode", "default": ".none" } + }, + "viewSlots": { + "listItemView": "(GroupMember?) -> UIView", + "leadingView": "(GroupMember?) -> UIView", + "titleView": "(GroupMember?) -> UIView", + "subtitleView": "(GroupMember?) -> UIView", + "trailView": "(GroupMember?) -> UIView", + "emptyStateView": "UIView", + "errorStateView": "UIView", + "loadingStateView": "UIView" + } + }, + "events": [ + { + "name": "ccGroupMemberKicked", + "payload": "{ user: User, group: Group }", + "description": "Fires when a member is kicked" + }, + { + "name": "ccGroupMemberBanned", + "payload": "{ user: User, group: Group }", + "description": "Fires when a member is banned" + }, + { + "name": "ccGroupMemberScopeChanged", + "payload": "{ user: User, group: Group, scope: MemberScope }", + "description": "Fires when a member's scope is changed" + } + ], + "sdkListeners": [ + "onGroupMemberKicked", + "onGroupMemberBanned", + "onGroupMemberUnbanned", + "onGroupMemberScopeChanged", + "onMemberAddedToGroup" + ], + "compositionExample": { + "description": "GroupMembers is typically accessed from group details or settings", + "components": ["CometChatGroups", "CometChatGroupMembers", "CometChatMessages"], + "flow": "User opens group → views members → taps member → starts direct chat" + }, + "types": { + "GroupMember": { + "uid": "String", + "name": "String", + "avatar": "String?", + "scope": "MemberScope", + "joinedAt": "Int" + }, + "MemberScope": { + "owner": "Group owner with full permissions", + "admin": "Administrator with management permissions", + "moderator": "Moderator with limited management", + "participant": "Regular member" } + } } ``` + -## Production-Ready Implementation +--- + +## Where It Fits -Complete example with member actions and navigation: +`CometChatGroupMembers` displays all members of a specific group. It's typically accessed from group details or settings screens. ```swift import UIKit import CometChatUIKitSwift import CometChatSDK -class GroupMembersViewController: UIViewController { +class GroupDetailViewController: UIViewController { var group: Group! @@ -56,62 +139,57 @@ class GroupMembersViewController: UIViewController { private func setupGroupMembers() { let groupMembers = CometChatGroupMembers(group: group) - // Handle member tap + // Handle member tap - start direct chat groupMembers.set(onItemClick: { [weak self] member, indexPath in - self?.showMemberProfile(member) + self?.startDirectChat(with: member) }) - // Handle long press for options - groupMembers.set(onItemLongClick: { [weak self] member, indexPath in - self?.showMemberOptions(member) - }) - - // Handle errors - groupMembers.set(onError: { error in - print("Error: \(error.errorDescription)") - }) - - // Handle empty state - groupMembers.set(onEmpty: { - print("No members found") - }) - - // Handle back button - groupMembers.set(onBack: { [weak self] in - self?.navigationController?.popViewController(animated: true) - }) - - navigationController?.pushViewController(groupMembers, animated: true) - } - - private func showMemberProfile(_ member: GroupMember) { - // Open user profile or start direct chat - let messages = CometChatMessages() - messages.set(user: member) - navigationController?.pushViewController(messages, animated: true) + let navController = UINavigationController(rootViewController: groupMembers) + present(navController, animated: true) } - private func showMemberOptions(_ member: GroupMember) { - let alert = UIAlertController(title: member.name, message: nil, preferredStyle: .actionSheet) - - alert.addAction(UIAlertAction(title: "Message", style: .default) { [weak self] _ in - self?.showMemberProfile(member) - }) - - alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) - present(alert, animated: true) + private func startDirectChat(with member: GroupMember) { + let messagesVC = CometChatMessages() + messagesVC.set(user: member) + navigationController?.pushViewController(messagesVC, animated: true) } } ``` -## Filter Members + + + -Use `GroupMembersRequestBuilder` to filter the member list: +--- + +## Minimal Render + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) +let navController = UINavigationController(rootViewController: groupMembers) +present(navController, animated: true) +``` + + + + + +--- + +## Filtering + +Use `GroupMembersRequest.GroupMembersRequestBuilder` to filter which members appear in the list. ```swift -// Filter by scope (admin, moderator, participant) +import CometChatUIKitSwift +import CometChatSDK + +// Create a custom request builder let requestBuilder = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid) - .set(limit: 20) + .set(limit: 30) .set(scopes: ["admin", "moderator"]) let groupMembers = CometChatGroupMembers( @@ -120,168 +198,235 @@ let groupMembers = CometChatGroupMembers( ) ``` +### Filter Recipes + +| Recipe | Code | +|--------|------| +| Admins only | `.set(scopes: ["admin"])` | +| Admins and moderators | `.set(scopes: ["admin", "moderator"])` | +| Search by name | `.set(searchKeyword: "john")` | +| Limit results | `.set(limit: 20)` | + +--- + +## Actions and Events + +### Callback Props + +#### onItemClick + +Fires when a user taps on a member. Use this to start a direct chat or view profile. + ```swift -// Search members -let searchBuilder = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid) - .set(searchKeyword: "john") +import CometChatUIKitSwift +import CometChatSDK -let groupMembers = CometChatGroupMembers( - group: group, - groupMembersRequestBuilder: searchBuilder -) -``` +let groupMembers = CometChatGroupMembers(group: group) -## Actions Reference +groupMembers.set(onItemClick: { [weak self] member, indexPath in + guard let self = self else { return } + + let messagesVC = CometChatMessages() + messagesVC.set(user: member) + self.navigationController?.pushViewController(messagesVC, animated: true) +}) +``` -| Method | Description | -|--------|-------------| -| `set(onItemClick:)` | Member tapped | -| `set(onItemLongClick:)` | Member long-pressed | -| `set(onBack:)` | Back button pressed | -| `set(onSelection:)` | Selection changed (multi-select mode) | -| `set(onError:)` | Error occurred | -| `set(onEmpty:)` | No members found | -| `set(onLoad:)` | Members loaded | +#### onItemLongClick -## Hide UI Elements +Fires when a user long-presses on a member. Use this to show member options. ```swift +import CometChatUIKitSwift +import CometChatSDK + let groupMembers = CometChatGroupMembers(group: group) -groupMembers.hideSearch = true // Hide search bar -groupMembers.hideUserStatus = true // Hide online/offline status -groupMembers.hideKickMemberOption = true // Hide kick option -groupMembers.hideBanMemberOption = true // Hide ban option -groupMembers.hideScopeChangeOption = true // Hide role change option -groupMembers.hideNavigationBar = true // Hide navigation bar -groupMembers.hideBackIcon = true // Hide back button +groupMembers.set(onItemLongClick: { [weak self] member, indexPath in + guard let self = self else { return } + + let alert = UIAlertController(title: member.name, message: nil, preferredStyle: .actionSheet) + + alert.addAction(UIAlertAction(title: "Message", style: .default) { _ in + // Start direct chat + }) + + alert.addAction(UIAlertAction(title: "View Profile", style: .default) { _ in + // View profile + }) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + self.present(alert, animated: true) +}) ``` -## Styling +#### onBack -### Quick Styling +Fires when the back button is pressed. ```swift -// Global styling -CometChatGroupMembers.style.titleColor = UIColor(hex: "#6851D6") -CometChatGroupMembers.style.titleFont = .systemFont(ofSize: 20, weight: .bold) -CometChatGroupMembers.style.backgroundColor = .systemBackground +import CometChatUIKitSwift -// Custom avatar style -let avatarStyle = AvatarStyle() -avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) -CometChatGroupMembers.avatarStyle = avatarStyle +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) +}) ``` -### Instance Styling +#### onSelection + +Fires when members are selected in selection mode. ```swift -let groupMembersStyle = GroupMembersStyle() -groupMembersStyle.titleColor = UIColor(hex: "#F76808") -groupMembersStyle.backgroundColor = .white -groupMembersStyle.listItemTitleTextColor = .black +import CometChatUIKitSwift +import CometChatSDK let groupMembers = CometChatGroupMembers(group: group) -groupMembers.style = groupMembersStyle +groupMembers.selectionMode = .multiple + +groupMembers.set(onSelection: { [weak self] selectedMembers in + print("Selected \(selectedMembers.count) members") +}) ``` - - - +#### onError -## Custom Views +Fires when an error occurs while loading members. -### Custom List Item +```swift +import CometChatUIKitSwift -Replace the entire member row with your own design: +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(onError: { error in + print("Error loading members: \(error.errorDescription)") +}) +``` + +#### onEmpty + +Fires when the member list is empty. ```swift +import CometChatUIKitSwift + let groupMembers = CometChatGroupMembers(group: group) -groupMembers.set(listItemView: { member in - let customView = MemberRowView() - customView.configure(with: member!) - return customView +groupMembers.set(onEmpty: { + print("No members found") }) ``` - - - +#### onLoad + +Fires when members are successfully loaded. ```swift -// MemberRowView.swift -import UIKit +import CometChatUIKitSwift import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(onLoad: { members in + print("Loaded \(members.count) members") +}) +``` + +### Actions Reference + +| Method | Description | Example | +|--------|-------------|---------| +| `set(onItemClick:)` | Triggered when a member is tapped | Start direct chat | +| `set(onItemLongClick:)` | Triggered on long press | Show options menu | +| `set(onBack:)` | Triggered when back button is pressed | Custom navigation | +| `set(onSelection:)` | Triggered in selection mode | Multi-select members | +| `set(onError:)` | Triggered when an error occurs | Show error alert | +| `set(onEmpty:)` | Triggered when list is empty | Show empty state | +| `set(onLoad:)` | Triggered when members load | Analytics tracking | + +### Global UI Events + +| Event | Fires when | Payload | +|-------|------------|---------| +| `ccGroupMemberKicked` | A member is kicked | `User, Group` | +| `ccGroupMemberBanned` | A member is banned | `User, Group` | +| `ccGroupMemberScopeChanged` | A member's role is changed | `User, Group, MemberScope` | + +```swift import CometChatUIKitSwift +import CometChatSDK -class MemberRowView: UIView { +class MyViewController: UIViewController, CometChatGroupEventListener { - private let avatar = CometChatAvatar(image: UIImage()) - private let nameLabel = UILabel() - private let roleButton = UIButton(type: .system) + override func viewDidLoad() { + super.viewDidLoad() + CometChatGroupEvents.addListener("my-listener", self) + } - override init(frame: CGRect) { - super.init(frame: frame) - setupUI() + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatGroupEvents.removeListener("my-listener") } - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") + func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { + print("\(kickedUser.name ?? "") was kicked from \(kickedGroup.name ?? "")") } - private func setupUI() { - avatar.translatesAutoresizingMaskIntoConstraints = false - avatar.layer.cornerRadius = 20 - - nameLabel.translatesAutoresizingMaskIntoConstraints = false - nameLabel.font = .systemFont(ofSize: 16, weight: .semibold) - - roleButton.translatesAutoresizingMaskIntoConstraints = false - roleButton.titleLabel?.font = .systemFont(ofSize: 12, weight: .medium) - roleButton.setTitleColor(.white, for: .normal) - roleButton.backgroundColor = .systemPurple - roleButton.layer.cornerRadius = 10 - roleButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) - - addSubview(avatar) - addSubview(nameLabel) - addSubview(roleButton) - - NSLayoutConstraint.activate([ - avatar.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), - avatar.centerYAnchor.constraint(equalTo: centerYAnchor), - avatar.widthAnchor.constraint(equalToConstant: 40), - avatar.heightAnchor.constraint(equalToConstant: 40), - - nameLabel.leadingAnchor.constraint(equalTo: avatar.trailingAnchor, constant: 12), - nameLabel.centerYAnchor.constraint(equalTo: centerYAnchor), - - roleButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), - roleButton.centerYAnchor.constraint(equalTo: centerYAnchor) - ]) + func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { + print("\(bannedUser.name ?? "") was banned from \(bannedGroup.name ?? "")") } - func configure(with member: GroupMember) { - nameLabel.text = member.name ?? "" - avatar.setAvatar(avatarUrl: member.avatar ?? "", with: member.name ?? "") - roleButton.setTitle(member.scope.rawValue.capitalized, for: .normal) + func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { + print("\(updatedUser.name ?? "") role changed to \(scopeChangedTo)") } } ``` -### Custom Subtitle View +### SDK Events (Real-Time, Automatic) + +| SDK Listener | Internal behavior | +|--------------|-------------------| +| `onGroupMemberKicked` | Removes member from list | +| `onGroupMemberBanned` | Removes member from list | +| `onGroupMemberUnbanned` | Updates member info | +| `onGroupMemberScopeChanged` | Updates member role badge | +| `onMemberAddedToGroup` | Adds new member to list | + +--- + +## Custom View Slots + +| Slot | Setter Method | Signature | Replaces | +|------|---------------|-----------|----------| +| `listItemView` | `set(listItemView:)` | `(GroupMember?) -> UIView` | Entire member row | +| `leadingView` | `set(leadingView:)` | `(GroupMember?) -> UIView` | Avatar / left section | +| `titleView` | `set(titleView:)` | `(GroupMember?) -> UIView` | Name / title text | +| `subtitleView` | `set(subtitleView:)` | `(GroupMember?) -> UIView` | Role / subtitle text | +| `trailView` | `set(trailView:)` | `(GroupMember?) -> UIView` | Right side (role badge) | +| `emptyStateView` | - | `UIView` | Empty state display | +| `errorStateView` | - | `UIView` | Error state display | +| `loadingStateView` | - | `UIView` | Loading state display | -Customize the subtitle area below the member name: +### subtitleView + +Customize the subtitle area below the member name. ```swift -groupMembers.setSubtitleView(subtitleView: { member in +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(subtitleView: { member in let label = UILabel() - label.font = .systemFont(ofSize: 12) - label.textColor = .secondaryLabel + label.font = UIFont.systemFont(ofSize: 12) + label.textColor = UIColor.secondaryLabel - let date = Date(timeIntervalSince1970: Double(member!.joinedAt)) + guard let member = member else { return label } + + let date = Date(timeIntervalSince1970: Double(member.joinedAt)) let formatter = DateFormatter() formatter.dateStyle = .medium label.text = "Joined: \(formatter.string(from: date))" @@ -290,37 +435,256 @@ groupMembers.setSubtitleView(subtitleView: { member in }) ``` - - - - -### Custom Tail View +### tailView -Add custom content on the right side of each row: +Customize the right side of the member row (role badge). Note: The setter method is `set(trailView:)`. ```swift -groupMembers.setTailView(tailView: { member in +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(trailView: { member in let badge = UILabel() - badge.text = member!.scope.rawValue.capitalized - badge.font = .systemFont(ofSize: 10, weight: .semibold) - badge.textColor = UIColor(hex: "#6852D6") - badge.backgroundColor = UIColor(hex: "#EDEAFA") + badge.font = UIFont.systemFont(ofSize: 10, weight: .semibold) badge.textAlignment = .center badge.layer.cornerRadius = 10 badge.clipsToBounds = true + + guard let member = member else { return badge } + + switch member.scope { + case .owner: + badge.text = "Owner" + badge.textColor = UIColor.systemOrange + badge.backgroundColor = UIColor.systemOrange.withAlphaComponent(0.2) + case .admin: + badge.text = "Admin" + badge.textColor = UIColor.systemPurple + badge.backgroundColor = UIColor.systemPurple.withAlphaComponent(0.2) + case .moderator: + badge.text = "Mod" + badge.textColor = UIColor.systemBlue + badge.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.2) + default: + badge.text = "Member" + badge.textColor = UIColor.systemGray + badge.backgroundColor = UIColor.systemGray.withAlphaComponent(0.2) + } + return badge }) ``` +--- + +## Styling + +### Style Hierarchy + +1. Global styles (`CometChatGroupMembers.style`) apply to all instances +2. Instance styles override global for specific instances + +### Global Level Styling + +```swift +import UIKit +import CometChatUIKitSwift + +// Apply global styles +CometChatGroupMembers.style.backgroundColor = UIColor.systemBackground +CometChatGroupMembers.style.titleColor = UIColor.label +CometChatGroupMembers.style.titleFont = UIFont.systemFont(ofSize: 20, weight: .bold) +CometChatGroupMembers.style.listItemTitleTextColor = UIColor.label + +// Custom avatar style +let avatarStyle = AvatarStyle() +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) +CometChatGroupMembers.avatarStyle = avatarStyle +``` + +### Instance Level Styling + +```swift +import UIKit +import CometChatUIKitSwift + +var customStyle = GroupMembersStyle() +customStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +customStyle.titleColor = UIColor.darkGray +customStyle.listItemBackground = UIColor.white + +let groupMembers = CometChatGroupMembers(group: group) +groupMembers.style = customStyle +``` + - + +### Key Style Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color | +| `titleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Navigation title color | +| `titleFont` | `UIFont` | `CometChatTypography.Heading4.medium` | Navigation title font | +| `listItemTitleTextColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Member name color | +| `listItemTitleFont` | `UIFont` | `CometChatTypography.Heading4.medium` | Member name font | +| `listItemSubTitleTextColor` | `UIColor` | `CometChatTheme.textColorSecondary` | Subtitle color | +| `listItemBackground` | `UIColor` | `.clear` | List item background | + +### Customization Matrix + +| What to change | Where | Property/API | Example | +|----------------|-------|--------------|---------| +| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | +| Title appearance | Style | `titleColor`, `titleFont` | Custom colors and fonts | +| List item look | Style | `listItemBackground` | `UIColor.white` | +| Avatar appearance | Style | `avatarStyle` | `AvatarStyle()` with custom radius | +| Hide search | Property | `hideSearch` | `groupMembers.hideSearch = true` | +| Hide kick option | Property | `hideKickMemberOption` | `groupMembers.hideKickMemberOption = true` | +| Custom row | View Slot | `set(listItemView:)` | See Custom View Slots | + +--- + +## Props + +All props are optional except `group`. Sorted alphabetically. + +### group (required) + +The group whose members to display. + +| | | +|---|---| +| Type | `Group` | +| Required | `true` | + +### groupMembersRequestBuilder + +Custom request builder for filtering members. + +| | | +|---|---| +| Type | `GroupMembersRequest.GroupMembersRequestBuilder?` | +| Default | `nil` | + +### hideBackIcon + +Hides the back button in the navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideBanMemberOption + +Hides the ban member option in swipe actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideErrorView + +Hides the error state view. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideKickMemberOption + +Hides the kick member option in swipe actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideLoadingState + +Hides the loading state indicator. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideNavigationBar + +Hides the entire navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideScopeChangeOption + +Hides the role change option in swipe actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideSearch + +Hides the search bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideUserStatus + +Hides online/offline status indicators. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### selectionMode + +Sets the selection mode for multi-select functionality. + +| | | +|---|---| +| Type | `SelectionMode` | +| Default | `.none` | + +--- + +## Events + +| Event | Payload | Fires when | +|-------|---------|------------| +| `ccGroupMemberKicked` | `User, Group` | A member is kicked | +| `ccGroupMemberBanned` | `User, Group` | A member is banned | +| `ccGroupMemberScopeChanged` | `User, Group, MemberScope` | A member's role is changed | + +--- + ## Custom Swipe Options Add custom actions when swiping on a member: ```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + let deleteOption = CometChatGroupMemberOption( id: "delete", title: "Remove", @@ -353,88 +717,72 @@ groupMembers.setOptions(options: { group, member in +--- + ## Custom Menu Buttons Add buttons to the navigation bar: ```swift -let addButton = UIBarButtonItem( - image: UIImage(systemName: "person.badge.plus"), - style: .plain, - target: self, - action: #selector(addMemberTapped) -) - -groupMembers.set(menus: [addButton]) - -@objc func addMemberTapped() { - // Show add member screen - let addMembers = CometChatAddMembers(group: group) - navigationController?.pushViewController(addMembers, animated: true) -} -``` - - - - - -## Listen for Events - -React to member changes in your app: +import UIKit +import CometChatUIKitSwift +import CometChatSDK -```swift -class MyViewController: UIViewController, CometChatGroupEventListener { +class GroupMembersViewController: UIViewController { + + var group: Group! override func viewDidLoad() { super.viewDidLoad() - CometChatGroupEvents.addListener("member-listener", self) - } - - override func viewWillDisappear(_ animated: Bool) { - super.viewWillDisappear(animated) - CometChatGroupEvents.removeListener("member-listener") - } - - // Member kicked - func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { - print("\(kickedUser.name ?? "") was kicked") + setupGroupMembers() } - // Member banned - func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { - print("\(bannedUser.name ?? "") was banned") + private func setupGroupMembers() { + let groupMembers = CometChatGroupMembers(group: group) + + let addButton = UIBarButtonItem( + image: UIImage(systemName: "person.badge.plus"), + style: .plain, + target: self, + action: #selector(addMemberTapped) + ) + + groupMembers.set(menus: [addButton]) + + let navController = UINavigationController(rootViewController: groupMembers) + present(navController, animated: true) } - // Member role changed - func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { - print("\(updatedUser.name ?? "") is now \(scopeChangedTo)") + @objc func addMemberTapped() { + // Show add member screen + let addMembers = CometChatAddMembers(group: group) + navigationController?.pushViewController(addMembers, animated: true) } } ``` -## Style Properties + + + -| Property | Description | -|----------|-------------| -| `backgroundColor` | Background color | -| `titleColor` | Title text color | -| `titleFont` | Title font | -| `listItemTitleTextColor` | Member name color | -| `listItemTitleFont` | Member name font | -| `listItemSubTitleTextColor` | Subtitle color | -| `listItemBackground` | Row background color | -| `separatorColor` | Row separator color | +--- ## Troubleshooting | Issue | Solution | |-------|----------| -| Empty member list | Verify group GUID is correct | -| Actions not showing | Check user has admin/owner permissions | -| Custom views not appearing | Ensure views have proper constraints | -| Events not firing | Verify listener is added before actions | +| Empty member list | Ensure group object is valid and has members | +| Management options not showing | Check logged-in user's permissions (must be admin/owner) | +| Search not working | Verify `hideSearch` is not set to true | +| Status not showing | Check that `hideUserStatus` is not set to true | +| Custom views not appearing | Ensure custom view has proper constraints | + +--- ## Related Components - [Groups](/ui-kit/ios/groups) - List all groups -- [Banned Members](/ui-kit/ios/banned-members) - View banned users +- [Messages](/ui-kit/ios/messages) - Display messages in a group +- [Add Members](/ui-kit/ios/add-members) - Add new members to a group +- [Banned Members](/ui-kit/ios/banned-members) - View banned members +- [Transfer Ownership](/ui-kit/ios/transfer-ownership) - Transfer group ownership diff --git a/ui-kit/ios/groups.mdx b/ui-kit/ios/groups.mdx index 5db2c5ffb..02959af1d 100644 --- a/ui-kit/ios/groups.mdx +++ b/ui-kit/ios/groups.mdx @@ -1,597 +1,430 @@ --- title: "Groups" -description: "Display and manage group chats in your iOS app" +description: "Display and manage a list of groups with search functionality" --- -The `CometChatGroups` component displays a searchable list of groups, enabling users to browse, join, and interact with group conversations. +The `CometChatGroups` component displays a searchable list of all available groups. It shows group names, avatars, member counts, and group type indicators (public/private/password-protected). Users can browse, join, and interact with group conversations. -## Prerequisites - -Before using this component, ensure you have: - -- Completed [Getting Started](/ui-kit/ios/getting-started) setup -- User logged in with `CometChatUIKit.login()` -- At least one group created in your CometChat dashboard - -## Usage - -### Basic Implementation - -Display a groups list and open messages when a group is tapped: - -```swift -import UIKit -import CometChatUIKitSwift -import CometChatSDK - -class GroupsViewController: UIViewController { - - override func viewDidLoad() { - super.viewDidLoad() - setupGroups() + +```json +{ + "component": "CometChatGroups", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays a searchable list of all available groups with avatars, names, member counts, and group type indicators.", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onItemClick", + "type": "(Group, IndexPath) -> Void" + }, + "props": { + "data": { + "groupsRequestBuilder": { + "type": "GroupsRequest.GroupsRequestBuilder?", + "default": "nil", + "note": "Custom request builder for filtering groups" + }, + "searchRequestBuilder": { + "type": "GroupsRequest.GroupsRequestBuilder?", + "default": "nil", + "note": "Custom request builder for search" + } + }, + "callbacks": { + "onItemClick": "(Group, IndexPath) -> Void", + "onItemLongClick": "(Group, IndexPath) -> Void", + "onBack": "() -> Void", + "onSelection": "([Group]) -> Void", + "onError": "(CometChatException) -> Void", + "onEmpty": "() -> Void", + "onLoad": "([Group]) -> Void" + }, + "visibility": { + "hideSearch": { "type": "Bool", "default": false }, + "hideNavigationBar": { "type": "Bool", "default": false }, + "hideBackButton": { "type": "Bool", "default": false }, + "hideGroupType": { "type": "Bool", "default": false }, + "hideSectionHeader": { "type": "Bool", "default": false }, + "hideErrorView": { "type": "Bool", "default": false }, + "hideLoadingState": { "type": "Bool", "default": false } + }, + "selection": { + "selectionMode": { "type": "SelectionMode", "default": ".none" } + }, + "viewSlots": { + "listItemView": "(Group) -> UIView", + "leadingView": "(Group) -> UIView", + "titleView": "(Group?) -> UIView", + "subtitleView": "(Group?) -> UIView", + "trailingView": "(Group?) -> UIView", + "emptyStateView": "() -> UIView", + "errorStateView": "() -> UIView", + "loadingStateView": "() -> UIView" } - - private func setupGroups() { - let groups = CometChatGroups() - - // Handle group selection - groups.set(onItemClick: { [weak self] group, indexPath in - self?.openMessages(for: group) - }) - - let navController = UINavigationController(rootViewController: groups) - navController.modalPresentationStyle = .fullScreen - present(navController, animated: true) + }, + "events": [ + { + "name": "ccGroupCreated", + "payload": "Group", + "description": "Fires when a group is created" + }, + { + "name": "ccGroupDeleted", + "payload": "Group", + "description": "Fires when a group is deleted" + }, + { + "name": "ccGroupMemberJoined", + "payload": "{ user: User, group: Group }", + "description": "Fires when a user joins a group" + }, + { + "name": "ccGroupMemberLeft", + "payload": "{ user: User, group: Group }", + "description": "Fires when a user leaves a group" } - - private func openMessages(for group: Group) { - let messages = CometChatMessages() - messages.set(group: group) - - if let nav = presentedViewController as? UINavigationController { - nav.pushViewController(messages, animated: true) - } + ], + "sdkListeners": [ + "onGroupMemberJoined", + "onGroupMemberLeft", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onGroupMemberUnbanned", + "onGroupMemberScopeChanged", + "onMemberAddedToGroup" + ], + "compositionExample": { + "description": "Groups list for browsing and joining group conversations", + "components": ["CometChatGroups", "CometChatMessages"], + "flow": "User taps on a group → onItemClick fires → Navigate to CometChatMessages with selected group" + }, + "types": { + "Group": { + "guid": "String", + "name": "String", + "icon": "String?", + "membersCount": "Int", + "groupType": "GroupType", + "scope": "MemberScope?" + }, + "GroupType": { + "public": "Anyone can join", + "private": "Invite only", + "password": "Password protected" } + } } ``` + + +--- -### Production Implementation +## Where It Fits -Complete implementation with selection mode, error handling, and navigation: +`CometChatGroups` displays all available groups for browsing and joining. It's typically used as a standalone screen or within a tab view controller. ```swift import UIKit import CometChatUIKitSwift import CometChatSDK -class ProductionGroupsViewController: UIViewController { - - private var groups: CometChatGroups! +class GroupsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - view.backgroundColor = .systemBackground setupGroups() - setupEventListeners() } private func setupGroups() { - // Configure request builder for joined groups only - let requestBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) - .set(joinedOnly: true) + let groupsController = CometChatGroups() - groups = CometChatGroups(groupsRequestBuilder: requestBuilder) - - // Handle group tap - groups.set(onItemClick: { [weak self] group, indexPath in + // Handle group selection - open group chat + groupsController.set(onItemClick: { [weak self] group, indexPath in self?.openGroupChat(group) }) - // Handle long press for options - groups.set(onItemLongClick: { [weak self] group, indexPath in - self?.showGroupOptions(group) - }) - - // Handle back button - groups.set(onBack: { [weak self] in - self?.navigationController?.popViewController(animated: true) - }) - - // Handle errors - groups.set(onError: { [weak self] error in - self?.showError(error) - }) - - // Handle empty state - groups.set(onEmpty: { [weak self] in - print("No groups available") - }) - - // Handle loaded groups - groups.set(onLoad: { groups in - print("Loaded \(groups.count) groups") - }) - - navigationController?.pushViewController(groups, animated: true) - } - - private func setupEventListeners() { - CometChatGroupEvents.addListener("groups-vc-listener", self as CometChatGroupEventListener) + let navController = UINavigationController(rootViewController: groupsController) + present(navController, animated: true) } private func openGroupChat(_ group: Group) { - let messages = CometChatMessages() - messages.set(group: group) - navigationController?.pushViewController(messages, animated: true) - } - - private func showGroupOptions(_ group: Group) { - let alert = UIAlertController(title: group.name, message: nil, preferredStyle: .actionSheet) - - alert.addAction(UIAlertAction(title: "View Details", style: .default) { [weak self] _ in - self?.showGroupDetails(group) - }) - - alert.addAction(UIAlertAction(title: "Leave Group", style: .destructive) { [weak self] _ in - self?.leaveGroup(group) - }) - - alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) - - present(alert, animated: true) - } - - private func showGroupDetails(_ group: Group) { - let details = CometChatGroupDetails() - details.set(group: group) - navigationController?.pushViewController(details, animated: true) - } - - private func leaveGroup(_ group: Group) { - CometChat.leaveGroup(GUID: group.guid) { [weak self] _ in - DispatchQueue.main.async { - self?.groups.remove(group: group) - } - } onError: { error in - print("Leave group error: \(error?.errorDescription ?? "")") - } - } - - private func showError(_ error: CometChatException) { - let alert = UIAlertController( - title: "Error", - message: error.errorDescription, - preferredStyle: .alert - ) - alert.addAction(UIAlertAction(title: "OK", style: .default)) - present(alert, animated: true) - } - - deinit { - CometChatGroupEvents.removeListener("groups-vc-listener") - } -} - -// MARK: - Group Event Listener -extension ProductionGroupsViewController: CometChatGroupEventListener { - - func onGroupCreate(group: Group) { - groups.insert(group: group, at: 0) - } - - func onGroupDelete(group: Group) { - groups.remove(group: group) - } - - func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { - groups.update(group: joinedGroup) - } - - func onGroupMemberLeave(leftUser: User, leftGroup: Group) { - groups.update(group: leftGroup) - } - - func onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) { - groups.update(group: group) - } - - func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { - groups.update(group: bannedGroup) - } - - func onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group) { - groups.update(group: unbannedUserGroup) - } - - func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { - groups.update(group: kickedGroup) - } - - func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { - groups.update(group: group) - } - - func onOwnershipChange(group: Group?, member: GroupMember?) { - if let group = group { - groups.update(group: group) - } + let messagesVC = CometChatMessages() + messagesVC.set(group: group) + navigationController?.pushViewController(messagesVC, animated: true) } } ``` -## Actions + + + -Actions let you customize component behavior through callbacks. +--- -| Action | Description | -|--------|-------------| -| `set(onItemClick:)` | Triggered when a group is tapped | -| `set(onItemLongClick:)` | Triggered on long press | -| `set(onBack:)` | Triggered when back button is pressed | -| `set(onSelection:)` | Triggered when groups are selected (selection mode) | -| `set(onError:)` | Triggered when an error occurs | -| `set(onEmpty:)` | Triggered when the list is empty | -| `set(onLoad:)` | Triggered when groups are loaded | +## Minimal Render ```swift +import CometChatUIKitSwift + let groups = CometChatGroups() +let navController = UINavigationController(rootViewController: groups) +present(navController, animated: true) +``` -groups.set(onItemClick: { group, indexPath in - print("Tapped: \(group.name ?? "")") -}) + + + -groups.set(onItemLongClick: { group, indexPath in - print("Long pressed: \(group.name ?? "")") -}) +--- -groups.set(onBack: { - print("Back button pressed") -}) +## Filtering -groups.set(onSelection: { selectedGroups in - print("Selected \(selectedGroups.count) groups") -}) +Use `GroupsRequest.GroupsRequestBuilder` to filter which groups appear in the list. The builder pattern allows chaining multiple filter conditions. -groups.set(onError: { error in - print("Error: \(error.errorDescription)") -}) +```swift +import CometChatUIKitSwift +import CometChatSDK -groups.set(onEmpty: { - print("No groups found") -}) +// Create a custom request builder +let groupsRequestBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) + .set(joinedOnly: true) -groups.set(onLoad: { groups in - print("Loaded \(groups.count) groups") -}) +let groups = CometChatGroups(groupsRequestBuilder: groupsRequestBuilder) ``` -## Filters +### Filter Recipes -Filter the groups list using `GroupsRequestBuilder`. +| Recipe | Code | +|--------|------| +| Joined groups only | `.set(joinedOnly: true)` | +| Search by name | `.set(searchKeyword: "design")` | +| Filter by tags | `.set(tags: ["engineering", "marketing"])` | +| Include tag info | `.set(withTags: true)` | +| Limit results | `GroupsRequestBuilder(limit: 20)` | -| Method | Type | Description | -|--------|------|-------------| -| `setLimit` | Int | Maximum groups per request | -| `setSearchKeyword` | String | Filter by search term | -| `joinedOnly` | Bool | Show only joined groups | -| `setTags` | [String] | Filter by tags | -| `withTags` | Bool | Include tag information | +--- -### Show Only Joined Groups +## Actions and Events -```swift -let requestBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) - .set(joinedOnly: true) +### Callback Props -let groups = CometChatGroups(groupsRequestBuilder: requestBuilder) -``` +#### onItemClick -### Search Groups +Fires when a user taps on a group in the list. Use this to open the group chat. ```swift -let searchBuilder = GroupsRequest.GroupsRequestBuilder(limit: 20) - .set(searchKeyword: "design") - -let groups = CometChatGroups(groupsRequestBuilder: searchBuilder) -``` - -### Filter by Tags +import CometChatUIKitSwift +import CometChatSDK -```swift -let tagBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) - .set(tags: ["engineering", "marketing"]) - .set(withTags: true) +let groups = CometChatGroups() -let groups = CometChatGroups(groupsRequestBuilder: tagBuilder) +groups.set(onItemClick: { [weak self] group, indexPath in + guard let self = self else { return } + + let messagesVC = CometChatMessages() + messagesVC.set(group: group) + self.navigationController?.pushViewController(messagesVC, animated: true) +}) ``` -## Events - -Listen for group-related events across your app. - -| Event | Description | -|-------|-------------| -| `onGroupCreate` | Group was created | -| `onGroupDelete` | Group was deleted | -| `onGroupMemberJoin` | User joined a group | -| `onGroupMemberLeave` | User left a group | -| `onGroupMemberAdd` | Members were added | -| `onGroupMemberBan` | Member was banned | -| `onGroupMemberUnban` | Member was unbanned | -| `onGroupMemberKick` | Member was kicked | -| `onGroupMemberChangeScope` | Member scope changed | -| `onOwnershipChange` | Group ownership transferred | +#### onItemLongClick -### Add Event Listener +Fires when a user long-presses on a group. Use this to show additional options. ```swift -import UIKit import CometChatUIKitSwift import CometChatSDK -class GroupEventsViewController: UIViewController { - - private let listenerID = "group-events-listener" - - override func viewDidLoad() { - super.viewDidLoad() - CometChatGroupEvents.addListener(listenerID, self as CometChatGroupEventListener) - } - - deinit { - CometChatGroupEvents.removeListener(listenerID) - } -} +let groups = CometChatGroups() -extension GroupEventsViewController: CometChatGroupEventListener { - - func onGroupCreate(group: Group) { - print("Group created: \(group.name ?? "")") - } +groups.set(onItemLongClick: { [weak self] group, indexPath in + guard let self = self else { return } - func onGroupDelete(group: Group) { - print("Group deleted: \(group.name ?? "")") - } + let alert = UIAlertController(title: group.name, message: nil, preferredStyle: .actionSheet) - func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { - print("\(joinedUser.name ?? "") joined \(joinedGroup.name ?? "")") - } + alert.addAction(UIAlertAction(title: "View Details", style: .default) { _ in + // View group details + }) - func onGroupMemberLeave(leftUser: User, leftGroup: Group) { - print("\(leftUser.name ?? "") left \(leftGroup.name ?? "")") - } - - func onGroupMemberAdd(group: Group, members: [GroupMember], addedBy: User) { - print("\(members.count) members added to \(group.name ?? "")") - } - - func onGroupMemberBan(bannedUser: User, bannedGroup: Group) { - print("\(bannedUser.name ?? "") banned from \(bannedGroup.name ?? "")") - } + alert.addAction(UIAlertAction(title: "Leave Group", style: .destructive) { _ in + // Leave group + }) - func onGroupMemberUnban(unbannedUserUser: User, unbannedUserGroup: Group) { - print("\(unbannedUserUser.name ?? "") unbanned from \(unbannedUserGroup.name ?? "")") - } - - func onGroupMemberKick(kickedUser: User, kickedGroup: Group) { - print("\(kickedUser.name ?? "") kicked from \(kickedGroup.name ?? "")") - } - - func onGroupMemberChangeScope(updatedBy: User, updatedUser: User, scopeChangedTo: CometChat.MemberScope, scopeChangedFrom: CometChat.MemberScope, group: Group) { - print("\(updatedUser.name ?? "") scope changed to \(scopeChangedTo)") - } - - func onOwnershipChange(group: Group?, member: GroupMember?) { - print("Ownership transferred to \(member?.name ?? "")") - } -} + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + self.present(alert, animated: true) +}) ``` -### Emit Events +#### onBack + +Fires when the back button is pressed. ```swift -// Emit group created event -CometChatGroupEvents.emitOnGroupCreate(group: group) +import CometChatUIKitSwift -// Emit group deleted event -CometChatGroupEvents.emitOnGroupDelete(group: group) +let groups = CometChatGroups() -// Emit member joined event -CometChatGroupEvents.emitOnGroupMemberJoin(joinedUser: user, joinedGroup: group) +groups.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) +}) +``` -// Emit member left event -CometChatGroupEvents.emitOnGroupMemberLeave(leftUser: user, leftGroup: group) +#### onSelection -// Emit members added event -CometChatGroupEvents.emitOnGroupMemberAdd(group: group, members: members, addedBy: user) +Fires when groups are selected in selection mode. -// Emit member banned event -CometChatGroupEvents.emitOnGroupMemberBan(bannedUser: user, bannedGroup: group, bannedBy: admin) +```swift +import CometChatUIKitSwift +import CometChatSDK -// Emit member unbanned event -CometChatGroupEvents.emitOnGroupMemberUnban(unbannedUserUser: user, unbannedUserGroup: group, unbannedBy: admin) +let groups = CometChatGroups() +groups.selectionMode = .multiple -// Emit member kicked event -CometChatGroupEvents.emitOnGroupMemberKick(kickedUser: user, kickedGroup: group, kickedBy: admin) +groups.set(onSelection: { [weak self] selectedGroups in + print("Selected \(selectedGroups.count) groups") +}) ``` -## Styling - -Customize the appearance using `GroupsStyle`. - -### Global Styling +#### onError -Apply styles to all `CometChatGroups` instances: +Fires when an error occurs while loading groups. ```swift -// Configure avatar style -let avatarStyle = AvatarStyle() -avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) +import CometChatUIKitSwift -// Configure groups style -CometChatGroups.style.titleColor = UIColor(hex: "#F76808") -CometChatGroups.style.titleFont = UIFont.systemFont(ofSize: 34, weight: .bold) -CometChatGroups.avatarStyle = avatarStyle +let groups = CometChatGroups() + +groups.set(onError: { error in + print("Error loading groups: \(error.errorDescription)") +}) ``` -### Instance Styling +#### onEmpty -Apply styles to a specific instance: +Fires when the group list is empty. ```swift -let avatarStyle = AvatarStyle() -avatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) - -let groupsStyle = GroupsStyle() -groupsStyle.titleColor = UIColor(hex: "#F76808") -groupsStyle.titleFont = UIFont.systemFont(ofSize: 34, weight: .bold) -groupsStyle.backgroundColor = .systemBackground -groupsStyle.listItemTitleTextColor = .label -groupsStyle.listItemSubTitleTextColor = .secondaryLabel +import CometChatUIKitSwift let groups = CometChatGroups() -groups.style = groupsStyle -groups.avatarStyle = avatarStyle + +groups.set(onEmpty: { + print("No groups found") +}) ``` - - - +#### onLoad -### Style Properties - -| Property | Description | Code | -|----------|-------------|------| -| `listItemSelectedImage` | Check box image when a list item is selected | `listItemSelectedImage` | -| `listItemDeSelectedImage` | Check box image when a list item is deselected | `listItemDeSelectedImage` | -| `searchIconTintColor` | Tint color for the search icon | `searchIconTintColor` | -| `searchBarStyle` | Style of the search bar | `searchBarStyle` | -| `searchTintColor` | Tint color for the search bar | `searchTintColor` | -| `searchBarTintColor` | Background color of the search bar | `searchBarTintColor` | -| `searchBarPlaceholderTextColor` | Placeholder text color for the search bar | `searchBarPlaceholderTextColor` | -| `searchBarPlaceholderTextFont` | Font for the placeholder text in the search bar | `searchBarPlaceholderTextFont` | -| `searchBarTextColor` | Color of the text entered in the search bar | `searchBarTextColor` | -| `searchBarTextFont` | Font for the text in the search bar | `searchBarTextFont` | -| `searchBarBackgroundColor` | Background color of the search bar | `searchBarBackgroundColor` | -| `searchBarCancelIconTintColor` | Tint color for the cancel icon in the search bar | `searchBarCancelIconTintColor` | -| `searchBarCrossIconTintColor` | Tint color for the cross icon in the search bar | `searchBarCrossIconTintColor` | -| `backgroundColor` | Background color of the overall view | `backgroundColor` | -| `borderWidth` | Width of the border around the view | `borderWidth` | -| `borderColor` | Color of the border around the view | `borderColor` | -| `cornerRadius` | Corner radius settings for the view | `cornerRadius` | -| `titleColor` | Color for the title text | `titleColor` | -| `titleFont` | Font used for the title text | `titleFont` | -| `largeTitleColor` | Color for the large title text | `largeTitleColor` | -| `largeTitleFont` | Font used for the large title text | `largeTitleFont` | -| `navigationBarTintColor` | Background color of the navigation bar | `navigationBarTintColor` | -| `navigationBarItemsTintColor` | Tint color for items in the navigation bar | `navigationBarItemsTintColor` | -| `errorTitleTextFont` | Font used for the error title text | `errorTitleTextFont` | -| `errorTitleTextColor` | Color of the error title text | `errorTitleTextColor` | -| `errorSubTitleFont` | Font used for the error subtitle text | `errorSubTitleFont` | -| `errorSubTitleTextColor` | Color of the error subtitle text | `errorSubTitleTextColor` | -| `retryButtonTextColor` | Color for the retry button text | `retryButtonTextColor` | -| `retryButtonTextFont` | Font used for the retry button text | `retryButtonTextFont` | -| `retryButtonBackgroundColor` | Background color for the retry button | `retryButtonBackgroundColor` | -| `retryButtonBorderColor` | Border color for the retry button | `retryButtonBorderColor` | -| `retryButtonBorderWidth` | Width of the border around the retry button | `retryButtonBorderWidth` | -| `retryButtonCornerRadius` | Corner radius settings for the retry button | `retryButtonCornerRadius` | -| `emptyTitleTextFont` | Font used for the empty state title text | `emptyTitleTextFont` | -| `emptyTitleTextColor` | Color of the empty state title text | `emptyTitleTextColor` | -| `emptySubTitleFont` | Font used for the empty state subtitle text | `emptySubTitleFont` | -| `emptySubTitleTextColor` | Color of the empty state subtitle text | `emptySubTitleTextColor` | -| `tableViewSeparator` | Color of the table view separator | `tableViewSeparator` | -| `listItemTitleTextColor` | Color of the title text in list items | `listItemTitleTextColor` | -| `listItemTitleFont` | Font used for the title text in list items | `listItemTitleFont` | -| `listItemSubTitleTextColor` | Color of the subtitle text in list items | `listItemSubTitleTextColor` | -| `listItemSubTitleFont` | Font used for the subtitle text in list items | `listItemSubTitleFont` | -| `listItemBackground` | Background color for list items | `listItemBackground` | -| `listItemSelectedBackground` | Background color for list items if selected | `listItemSelectedBackground` | -| `listItemBorderWidth` | Width of the border around list items | `listItemBorderWidth` | -| `listItemBorderColor` | Color of the border around list items | `listItemBorderColor` | -| `listItemCornerRadius` | Corner radius settings for list items | `listItemCornerRadius` | -| `listItemSelectionImageTint` | Tint color for the selection image in list items | `listItemSelectionImageTint` | -| `listItemDeSelectedImageTint` | Tint color for the deselected image in list items | `listItemDeSelectedImageTint` | -| `passwordGroupImageTintColor` | Tint color for the password group image | `passwordGroupImageTintColor` | -| `passwordGroupImageBackgroundColor` | Background color for the password group image | `passwordGroupImageBackgroundColor` | -| `privateGroupImageTintColor` | Tint color for the private group image | `privateGroupImageTintColor` | -| `privateGroupImageBackgroundColor` | Background color for the private group image | `privateGroupImageBackgroundColor` | -| `privateGroupIcon` | Image for a private group icon | `privateGroupIcon` | -| `protectedGroupIcon` | Image for a protected group icon | `protectedGroupIcon` | - -## Functionality - -Configure component behavior with these properties and methods: - -| Method | Description | Code | -|--------|-------------|------| -| `set(groupsRequestBuilder:)` | Sets the request builder for fetching groups | `set(groupsRequestBuilder: requestBuilder)` | -| `set(searchRequestBuilder:)` | Sets the request builder for searching groups | `set(searchRequestBuilder: searchRequestBuilder)` | -| `set(searchKeyword:)` | Sets the search keyword to filter groups | `set(searchKeyword: "group_name")` | -| `hideErrorView` | Hides the error state view | `hideErrorView = true` | -| `hideNavigationBar` | Hides or shows the navigation bar | `hideNavigationBar = true` | -| `hideSearch` | Hides the search bar | `hideSearch = true` | -| `hideBackButton` | Hides the back button | `hideBackButton = true` | -| `hideLoadingState` | Hides the loading state indicator | `hideLoadingState = true` | -| `hideReceipts` | Hides message read/delivery receipts | `hideReceipts = true` | -| `hideDeleteConversationOption` | Hides the option to delete a conversation | `hideDeleteConversationOption = true` | -| `hideUserStatus` | Hides the online/offline status of users | `hideUserStatus = true` | -| `hideGroupType` | Hides the group type (private/public) | `hideGroupType = true` | +Fires when groups are successfully loaded. ```swift +import CometChatUIKitSwift +import CometChatSDK + let groups = CometChatGroups() -groups.hideSearch = true -groups.hideGroupType = false -groups.hideBackButton = true -groups.hideErrorView = false -groups.hideLoadingState = false + +groups.set(onLoad: { groups in + print("Loaded \(groups.count) groups") +}) ``` -## Custom Views +### Actions Reference + +| Method | Description | Example | +|--------|-------------|---------| +| `set(onItemClick:)` | Triggered when a group is tapped | Open group chat | +| `set(onItemLongClick:)` | Triggered on long press | Show options menu | +| `set(onBack:)` | Triggered when back button is pressed | Custom navigation | +| `set(onSelection:)` | Triggered in selection mode | Multi-select groups | +| `set(onError:)` | Triggered when an error occurs | Show error alert | +| `set(onEmpty:)` | Triggered when list is empty | Show empty state | +| `set(onLoad:)` | Triggered when groups load | Analytics tracking | -### SetOptions +### Global UI Events -You can define custom options for each group using `.set(options:)`. This method allows you to return an array of `CometChatGroupOption` based on the group object. +| Event | Fires when | Payload | +|-------|------------|---------| +| `ccGroupCreated` | A group is created | `Group` | +| `ccGroupDeleted` | A group is deleted | `Group` | +| `ccGroupMemberJoined` | A user joins a group | `User, Group` | +| `ccGroupMemberLeft` | A user leaves a group | `User, Group` | ```swift -cometChatGroups.set(options: { group in - return [CometChatGroupOptions] -}) -``` +import CometChatUIKitSwift +import CometChatSDK -### AddOptions +class MyViewController: UIViewController, CometChatGroupEventListener { + + override func viewDidLoad() { + super.viewDidLoad() + CometChatGroupEvents.addListener("my-listener", self) + } + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatGroupEvents.removeListener("my-listener") + } + + func onGroupCreate(group: Group) { + print("Group created: \(group.name ?? "")") + } + + func onGroupDelete(group: Group) { + print("Group deleted: \(group.name ?? "")") + } + + func onGroupMemberJoin(joinedUser: User, joinedGroup: Group) { + print("\(joinedUser.name ?? "") joined \(joinedGroup.name ?? "")") + } + + func onGroupMemberLeave(leftUser: User, leftGroup: Group) { + print("\(leftUser.name ?? "") left \(leftGroup.name ?? "")") + } +} +``` -You can dynamically add options to groups using `.add(options:)`. This method lets you return additional `CometChatGroupOption` elements. +### SDK Events (Real-Time, Automatic) -```swift -cometChatGroups.add(options: { group in - return [ArchiveOption()] -}) -``` +| SDK Listener | Internal behavior | +|--------------|-------------------| +| `onGroupMemberJoined` | Updates member count | +| `onGroupMemberLeft` | Updates member count | +| `onGroupMemberKicked` | Updates member count | +| `onGroupMemberBanned` | Updates member count | +| `onGroupMemberUnbanned` | Updates group info | +| `onGroupMemberScopeChanged` | Updates member scope | +| `onMemberAddedToGroup` | Updates member count | -### SetListItemView +--- -With this function, you can assign a custom ListItem to the groups Component. +## Custom View Slots -```swift -let cometChatGroups = CometChatGroups() -cometChatGroups.set(listItemView: { group in - let view = GroupCellView() - return view -}) -``` +| Slot | Signature | Replaces | +|------|-----------|----------| +| `listItemView` | `(Group) -> UIView` | Entire group row | +| `leadingView` | `(Group) -> UIView` | Avatar / left section | +| `titleView` | `(Group?) -> UIView` | Name / title text | +| `subtitleView` | `(Group?) -> UIView` | Member count / subtitle | +| `trailingView` | `(Group?) -> UIView` | Right side content | +| `emptyStateView` | `() -> UIView` | Empty state display | +| `errorStateView` | `() -> UIView` | Error state display | +| `loadingStateView` | `() -> UIView` | Loading state display | -### Custom List Item +### listItemView -Replace the default group cell with a custom view: +Replace the entire group row with a custom design. ```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + let groups = CometChatGroups() + groups.set(listItemView: { group in let customView = CustomGroupCell() customView.configure(with: group) @@ -603,6 +436,8 @@ groups.set(listItemView: { group in +You can create a `CustomGroupCell` as a custom `UIView`: + ```swift import UIKit import CometChatSDK @@ -705,22 +540,28 @@ class CustomGroupCell: UIView { } ``` -### SetLeadingView +### leadingView -You can modify the leading view of a group cell using `.set(leadingView:)`. +Customize the leading view (avatar area) of a group cell. ```swift -cometChatGroups.set(leadingView: { group in +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groups = CometChatGroups() + +groups.set(leadingView: { group in let view = CustomLeadingView() - return view -}) + return view +}) ``` -You can create a `CustomLeadingView` as a custom `UIView`. Which we will inflate in `setLeadingView()`: +You can create a `CustomLeadingView` as a custom `UIView`: ```swift import UIKit @@ -766,24 +607,32 @@ class CustomLeadingView: UIView { } ``` -### SetTitleView +### titleView -You can customize the title view of a group cell using `.set(titleView:)`. +Customize the title view of a group cell. ```swift -cometChatGroups.set(titleView: { group in +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groups = CometChatGroups() + +groups.set(titleView: { group in let view = CustomTitleView() return view -}) +}) ``` -You can create a `CustomTitleView` as a custom `UIView`. Which we will inflate in `setTitleView()`: +You can create a `CustomTitleView` as a custom `UIView`: ```swift +import UIKit + class CustomTitleView: UIView { private let titleLabel: UILabel = { @@ -852,22 +701,70 @@ class CustomTitleView: UIView { } ``` -### SetTrailView +### subtitleView + +Customize the subtitle area below the group name. + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groups = CometChatGroups() + +groups.set(subtitleView: { group in + let view = CustomSubtitleView(membersCount: group.membersCount) + return view +}) +``` + + + + + +You can create a `CustomSubtitleView` as a custom `UIView`: + +```swift +import UIKit + +class CustomSubtitleView: UILabel { + + init(membersCount: Int) { + super.init(frame: .zero) + self.text = "\(membersCount) members • Group description" + self.textColor = UIColor.gray + self.font = UIFont.systemFont(ofSize: 14) + self.numberOfLines = 1 + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} +``` + +### trailingView -You can modify the trailing view of a group cell using `.set(trailView:)`. +Customize the trailing view (right side) of a group cell. ```swift -cometChatGroups.set(trailView: { group in - let view = CustomTrailView() - return view -}) +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groups = CometChatGroups() + +groups.set(trailView: { group in + let view = CustomTrailView() + return view +}) ``` -You can create a `CustomTrailView` as a custom `UIView`. Which we will inflate in `setTrailView()`: +You can create a `CustomTrailView` as a custom `UIView`: ```swift import UIKit @@ -908,134 +805,285 @@ class CustomTrailView: UIView { } ``` -### SetSubTitleView +### loadingStateView -You can customize the subtitle view for each group item to meet your requirements: +Customize the loading state view displayed while data is being fetched. ```swift -cometChatGroup.set(subtitleView: { group in - let view = CustomSubtitleView() - return view -}) +import UIKit +import CometChatUIKitSwift + +let groups = CometChatGroups() + +let loadingIndicator = UIActivityIndicatorView(style: .medium) +loadingIndicator.startAnimating() +groups.set(loadingView: loadingIndicator) ``` - - - +### errorStateView -You can seamlessly integrate this `CustomSubtitleView` UIView file into the `.set(subtitleView:)` method within CometChatGroups: +Customize the error state view displayed when an error occurs. ```swift import UIKit +import CometChatUIKitSwift -class CustomSubtitleView: UILabel { - - init(membersCount: Int) { - super.init(frame: .zero) - self.text = "\(membersCount) members • \("group_description")" - self.textColor = UIColor.gray - self.font = UIFont.systemFont(ofSize: 14) - self.numberOfLines = 1 - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } -} +let groups = CometChatGroups() + +let errorLabel = UILabel() +errorLabel.text = "Something went wrong!" +errorLabel.textColor = .red +groups.set(errorView: errorLabel) ``` -### SetLoadingView +### emptyStateView -You can set a custom loading view using `.set(loadingView:)`. This method accepts a UIView to display while data is being fetched. +Customize the empty state view displayed when no groups are available. ```swift -let loadingIndicator = UIActivityIndicatorView(style: .medium) -loadingIndicator.startAnimating() -cometChatGroups.set(loadingView: loadingIndicator) +import UIKit +import CometChatUIKitSwift + +let groups = CometChatGroups() + +let emptyLabel = UILabel() +emptyLabel.text = "No groups found" +emptyLabel.textColor = .gray +emptyLabel.textAlignment = .center +groups.set(emptyView: emptyLabel) ``` -### SetErrorView +--- + +## Options + +### set(options:) -You can customize the error view using `.set(errorView:)`. This method accepts a UIView that appears when an error occurs. +Define custom options for each group. This method allows you to return an array of `CometChatGroupOption` based on the group object. ```swift -let errorLabel = UILabel() -errorLabel.text = "Something went wrong!" -errorLabel.textColor = .red -cometChatGroups.set(errorView: errorLabel) +import CometChatUIKitSwift +import CometChatSDK + +let groups = CometChatGroups() + +groups.set(options: { group in + return [CometChatGroupOption]() +}) ``` -### SetEmptyView +### add(options:) -You can customize the empty state view using `.set(emptyView:)`. This method accepts a UIView that appears when no groups are available. +Dynamically add options to groups. This method lets you return additional `CometChatGroupOption` elements. ```swift -let emptyLabel = UILabel() -emptyLabel.text = "No groups found" -emptyLabel.textColor = .gray -emptyLabel.textAlignment = .center -cometChatGroups.set(emptyView: emptyLabel) +import CometChatUIKitSwift +import CometChatSDK + +let groups = CometChatGroups() + +groups.add(options: { group in + return [ArchiveOption()] +}) ``` -## Group Options +--- + +## Styling -Add custom swipe actions to group cells. +### Style Hierarchy -### Set Options +1. Global styles (`CometChatGroups.style`) apply to all instances +2. Instance styles override global for specific instances -Replace default options: +### Global Level Styling ```swift -groups.set(options: { group in - let leaveOption = CometChatGroupOption( - id: "leave", - title: "Leave", - icon: UIImage(systemName: "arrow.right.square"), - backgroundColor: .systemRed - ) { group in - // Handle leave action - } - return [leaveOption] -}) -``` +import UIKit +import CometChatUIKitSwift -### Add Options +// Apply global styles that affect all CometChatGroups instances +CometChatGroups.style.backgroundColor = UIColor.systemBackground +CometChatGroups.style.titleColor = UIColor.label +CometChatGroups.style.titleFont = UIFont.systemFont(ofSize: 34, weight: .bold) +CometChatGroups.style.listItemTitleTextColor = UIColor.label +CometChatGroups.style.listItemSubTitleTextColor = UIColor.secondaryLabel -Add options to existing ones: +// Custom avatar style +let avatarStyle = AvatarStyle() +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) +CometChatGroups.avatarStyle = avatarStyle +``` + +### Instance Level Styling ```swift -groups.add(options: { group in - let archiveOption = CometChatGroupOption( - id: "archive", - title: "Archive", - icon: UIImage(systemName: "archivebox"), - backgroundColor: .systemOrange - ) { group in - // Handle archive action - } - return [archiveOption] -}) +import UIKit +import CometChatUIKitSwift + +// Create a custom style for a specific instance +var customStyle = GroupsStyle() +customStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +customStyle.titleColor = UIColor.darkGray +customStyle.listItemBackground = UIColor.white + +let groups = CometChatGroups() +groups.style = customStyle ``` -## Component Structure +### Key Style Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color | +| `titleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Navigation title color | +| `titleFont` | `UIFont` | `CometChatTypography.Heading4.medium` | Navigation title font | +| `listItemTitleTextColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Group name color | +| `listItemTitleFont` | `UIFont` | `CometChatTypography.Heading4.medium` | Group name font | +| `listItemSubTitleTextColor` | `UIColor` | `CometChatTheme.textColorSecondary` | Member count color | +| `listItemSubTitleFont` | `UIFont` | `CometChatTypography.Body.regular` | Member count font | +| `listItemBackground` | `UIColor` | `.clear` | List item background | +| `privateGroupBadgeColor` | `UIColor` | `CometChatTheme.iconColorSecondary` | Private group badge color | +| `passwordGroupBadgeColor` | `UIColor` | `CometChatTheme.iconColorSecondary` | Password group badge color | + +### Customization Matrix + +| What to change | Where | Property/API | Example | +|----------------|-------|--------------|---------| +| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | +| Title appearance | Style | `titleColor`, `titleFont` | Custom colors and fonts | +| List item look | Style | `listItemBackground` | `UIColor.white` | +| Avatar appearance | Style | `avatarStyle` | `AvatarStyle()` with custom radius | +| Group type badges | Style | `privateGroupBadgeColor` | Custom badge colors | +| Hide search | Property | `hideSearch` | `groups.hideSearch = true` | +| Hide group type | Property | `hideGroupType` | `groups.hideGroupType = true` | +| Custom row | View Slot | `set(listItemView:)` | See Custom View Slots | + +--- + +## Props + +All props are optional. Sorted alphabetically. + +### groupsRequestBuilder + +Custom request builder for filtering groups. + +| | | +|---|---| +| Type | `GroupsRequest.GroupsRequestBuilder?` | +| Default | `nil` | + +### hideBackButton + +Hides the back button in the navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideErrorView + +Hides the error state view. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideGroupType + +Hides the public/private/password group type icons. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | -| Component | Description | -|-----------|-------------| -| [CometChatListBase](/ui-kit/ios/list-base) | Container with navigation bar and search | -| [CometChatListItem](/ui-kit/ios/list-item) | Individual group cell | +### hideLoadingState + +Hides the loading state indicator. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideNavigationBar + +Hides the entire navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideSearch + +Hides the search bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideSectionHeader + +Hides the alphabetical section headers. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### searchRequestBuilder + +Custom request builder for search functionality. + +| | | +|---|---| +| Type | `GroupsRequest.GroupsRequestBuilder?` | +| Default | `nil` | + +### selectionMode + +Sets the selection mode for multi-select functionality. + +| | | +|---|---| +| Type | `SelectionMode` | +| Default | `.none` | + +--- + +## Events + +| Event | Payload | Fires when | +|-------|---------|------------| +| `ccGroupCreated` | `Group` | A group is created | +| `ccGroupDeleted` | `Group` | A group is deleted | +| `ccGroupMemberJoined` | `User, Group` | A user joins a group | +| `ccGroupMemberLeft` | `User, Group` | A user leaves a group | + +--- ## Troubleshooting | Issue | Solution | |-------|----------| -| Groups not loading | Verify user is logged in and has proper permissions | -| Search not working | Check `searchRequestBuilder` configuration | -| Events not firing | Ensure listener is added before actions occur | -| Styling not applied | Apply styles before presenting the component | -| Custom views not showing | Return non-nil UIView from closure | +| Empty group list | Ensure SDK is initialized and user is logged in | +| Groups not updating in real-time | Check SDK connection and group listeners | +| Search not working | Verify `hideSearch` is not set to true | +| Group type icons not showing | Check that `hideGroupType` is not set to true | +| Custom views not appearing | Ensure custom view has proper constraints | + +--- ## Related Components -- [Group Members](/ui-kit/ios/group-members) - Display group member list -- [Conversations](/ui-kit/ios/conversations) - Display conversation list -- [Users](/ui-kit/ios/users) - Display user list +- [Messages](/ui-kit/ios/messages) - Display messages in a group +- [Conversations](/ui-kit/ios/conversations) - List all conversations +- [Users](/ui-kit/ios/users) - List all users +- [Group Members](/ui-kit/ios/group-members) - Manage group members +- [Groups With Messages](/ui-kit/ios/groups-with-messages) - Combined groups and messages view diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index 3a07fdfcc..82df42aba 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -1,658 +1,632 @@ --- title: "Message Composer" -sidebarTitle: "Message Composer" -description: "Enable users to write and send text, media, and custom messages using CometChat UI Kit for iOS" +description: "Enable users to write and send text, media, and custom messages" --- -## Overview - -MessageComposer is a [Component](/ui-kit/ios/components-overview#components) that enables users to write and send a variety of messages, including text, image, video, and custom messages. +The `CometChatMessageComposer` component enables users to write and send messages including text, images, videos, audio, files, and custom messages. It supports attachments, voice recording, stickers, mentions, and AI-powered features. -MessageComposer is comprised of the following [Base Components](/ui-kit/ios/components-overview#base-components): - -| Base Components | Description | -|-----------------|-------------| -| [MessageInput](/ui-kit/ios/message-input) | Provides a basic layout for the contents of this component, such as the TextField and buttons | -| [ActionSheet](/ui-kit/ios/action-sheet) | Presents a list of options in either a list or grid mode, depending on the user's preference | + +```json +{ + "component": "CometChatMessageComposer", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Enables users to compose and send messages with support for text, media, attachments, voice recording, stickers, mentions, and AI features.", + "inherits": "UIView", + "primaryOutput": { + "callback": "onSendButtonClick", + "type": "(BaseMessage) -> Void" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "nil", + "note": "User for direct messaging" + }, + "group": { + "type": "Group?", + "default": "nil", + "note": "Group for group messaging" + }, + "parentMessageId": { + "type": "Int?", + "default": "nil", + "note": "Parent message ID for thread replies" + } + }, + "callbacks": { + "onSendButtonClick": "(BaseMessage) -> Void", + "onTextChanged": "(String) -> Void", + "onError": "(CometChatException) -> Void" + }, + "visibility": { + "hideAttachmentButton": { "type": "Bool", "default": false }, + "hideVoiceRecordingButton": { "type": "Bool", "default": false }, + "hideStickersButton": { "type": "Bool", "default": false }, + "hideSendButton": { "type": "Bool", "default": false }, + "hideImageAttachmentOption": { "type": "Bool", "default": false }, + "hideVideoAttachmentOption": { "type": "Bool", "default": false }, + "hideAudioAttachmentOption": { "type": "Bool", "default": false }, + "hideFileAttachmentOption": { "type": "Bool", "default": false }, + "hidePollsOption": { "type": "Bool", "default": false }, + "hideCollaborativeDocumentOption": { "type": "Bool", "default": false }, + "hideCollaborativeWhiteboardOption": { "type": "Bool", "default": false } + }, + "behavior": { + "disableTypingEvents": { "type": "Bool", "default": false }, + "disableMentions": { "type": "Bool", "default": false }, + "disableSoundForMessages": { "type": "Bool", "default": false }, + "maxLine": { "type": "Int", "default": 5 } + }, + "viewSlots": { + "headerView": "(User?, Group?) -> UIView", + "footerView": "(User?, Group?) -> UIView", + "sendButtonView": "(User?, Group?) -> UIView", + "attachmentOptions": "(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]" + }, + "formatting": { + "textFormatters": "[CometChatTextFormatter]" + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "MessageComposer is typically used within CometChatMessages alongside MessageHeader and MessageList", + "components": ["CometChatMessageHeader", "CometChatMessageList", "CometChatMessageComposer"], + "flow": "User types message → onTextChanged fires → User taps send → onSendButtonClick fires → Message sent" + }, + "types": { + "CometChatMessageComposerAction": { + "id": "String", + "text": "String", + "startIcon": "UIImage?", + "startIconTint": "UIColor?", + "textColor": "UIColor?", + "onActionClick": "() -> Void" + } + } +} +``` + --- -## Usage +## Where It Fits + +`CometChatMessageComposer` is the input component for sending messages. It's typically used within `CometChatMessages` alongside `CometChatMessageHeader` and `CometChatMessageList`. + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +class ChatViewController: UIViewController { + + private var messageComposer: CometChatMessageComposer! + + override func viewDidLoad() { + super.viewDidLoad() + setupMessageComposer() + } + + private func setupMessageComposer(for user: User) { + messageComposer = CometChatMessageComposer() + messageComposer.set(user: user) + + // Handle send button click + messageComposer.set(onSendButtonClick: { [weak self] message in + print("Message sent: \(message.id)") + }) + + // Handle text changes for typing indicators + messageComposer.set(onTextChanged: { [weak self] text in + print("User is typing: \(text)") + }) + + view.addSubview(messageComposer) + } +} +``` + + + + -### Integration +--- -The following code snippet illustrates how you can directly incorporate the MessageComposer component into your application: +## Minimal Render ```swift -// Create and configure the message composer +import CometChatUIKitSwift +import CometChatSDK + let messageComposer = CometChatMessageComposer() messageComposer.set(user: user) -messageComposer.set(parentMessageId: 20) ``` + + + + --- -### Actions +## Actions and Events -[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +### Callback Props -#### 1. onSendButtonClick +#### onSendButtonClick -The `set(onSendButtonClick:)` event gets activated when the send message button is clicked. The following code snippet overrides the action of the send button in CometChatMessageComposer. +Fires when the send button is clicked. Use this to handle custom send actions. - - ```swift -messageComposer.set(onSendButtonClick: { message in - // Handle custom send action here -}) -``` - - +import CometChatUIKitSwift +import CometChatSDK -#### 2. OnTextChanged - -The `set(onTextChanged:)` event gets activated when the user starts typing in the message composer. This returns the text entered by the user. +let messageComposer = CometChatMessageComposer() - - -```swift -messageComposer.set(onTextChanged: { text in - // Handle text change action +messageComposer.set(onSendButtonClick: { [weak self] message in + guard let self = self else { return } + print("Message sent with ID: \(message.id)") }) ``` - - - -#### 3. SetOnError +#### onTextChanged -This method proves helpful when a user needs to customize the action taken upon encountering an error in CometChatMessageComposer. +Fires when the user types in the composer. Use this for typing indicators or text validation. - - ```swift -messageComposer.set(onError { error in - // Handle error +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +messageComposer.set(onTextChanged: { [weak self] text in + guard let self = self else { return } + print("Current text: \(text)") }) ``` - - ---- +#### onError -### Filters +Fires when an error occurs while sending a message. -MessageComposer component does not have any available filters. +```swift +import CometChatUIKitSwift ---- +let messageComposer = CometChatMessageComposer() -### Events +messageComposer.set(onError: { error in + print("Error: \(error.errorDescription)") +}) +``` -[Events](/ui-kit/ios/components-overview#events) are emitted by a `Component`. By using events you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. +### Actions Reference -The MessageComposer Component does not emit any events of its own. +| Method | Description | Example | +|--------|-------------|---------| +| `set(onSendButtonClick:)` | Triggered when send button is clicked | Custom send handling | +| `set(onTextChanged:)` | Triggered when text changes | Typing indicators | +| `set(onError:)` | Triggered when an error occurs | Show error alert | +| `set(user:)` | Sets the user for direct messaging | Configure recipient | +| `set(group:)` | Sets the group for group messaging | Configure group | +| `set(parentMessageId:)` | Sets parent message for thread replies | Thread replies | +| `setInitialComposerText(_:)` | Sets initial text in composer | Pre-fill message | --- -## Customization - -To fit your app's design requirements, you can customize the appearance of the MessageComposer component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +## Custom View Slots -### Style +| Slot | Signature | Replaces | +|------|-----------|----------| +| `headerView` | `(User?, Group?) -> UIView` | Header above composer | +| `footerView` | `(User?, Group?) -> UIView` | Footer below composer | +| `sendButtonView` | `(User?, Group?) -> UIView` | Send button | +| `attachmentOptions` | `(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]` | Attachment menu options | -Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. +### headerView -#### 1. MessageComposer Style +Add a custom header above the composer. -To customize the styling, you can apply the `MessageComposerStyle` to the `MessageComposer` component. - -**Global level styling** - - - ```swift -CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = UIColor(hex: "#F76808") -CometChatMessageComposer.style.attachmentImageTint = UIColor(hex: "#F76808") -CometChatMessageComposer.style.voiceRecordingImageTint = UIColor(hex: "#F76808") -CometChatMessageComposer.style.stickerTint = UIColor(hex: "#F76808") -CometChatMessageComposer.style.aiImageTint = UIColor(hex: "#F76808") -``` - - - -**Instance level styling** +import UIKit +import CometChatUIKitSwift - - -```swift -// Create custom composer style -let customComposerStyle = MessageComposerStyle() -customComposerStyle.activeSendButtonImageBackgroundColor = UIColor(hex: "#F76808") -customComposerStyle.attachmentImageTint = UIColor(hex: "#F76808") -customComposerStyle.voiceRecordingImageTint = UIColor(hex: "#F76808") -customComposerStyle.stickerTint = UIColor(hex: "#F76808") -customComposerStyle.aiImageTint = UIColor(hex: "#F76808") - -// Apply to message composer instance let messageComposer = CometChatMessageComposer() -messageComposer.style = customComposerStyle + +messageComposer.set(headerView: { user, group in + let view = CustomHeaderView() + return view +}) ``` - - - + +You can create a `CustomHeaderView` as a custom `UIView`: -The following properties are exposed by MessageComposerStyle: - -| Property | Description | Code | -|----------|-------------|------| -| **Placeholder Text Font** | Font for the placeholder text in the input field | `CometChatMessageComposer.style.placeHolderTextFont = CometChatTypography.Body.regular` | -| **Placeholder Text Color** | Color for the placeholder text in the input field | `CometChatMessageComposer.style.placeHolderTextColor = CometChatTheme.textColorTertiary` | -| **Text Field Color** | Text color for the input field | `CometChatMessageComposer.style.textFiledColor = CometChatTheme.textColorPrimary` | -| **Text Field Font** | Font for the input field text | `CometChatMessageComposer.style.textFiledFont = CometChatTypography.Body.regular` | -| **Background Color** | Background color with dynamic support for light and dark mode | `CometChatMessageComposer.style.backgroundColor = UIColor.dynamicColor(lightModeColor: ..., darkModeColor: ...)` | -| **Corner Radius** | Corner radius for the composer | `CometChatMessageComposer.style.cornerRadius = CometChatCornerStyle?` | -| **Border Width** | Border width for the composer | `CometChatMessageComposer.style.borderWidth = 0` | -| **Border Color** | Border color for the composer | `CometChatMessageComposer.style.borderColor = .clear` | -| **Send Button Image** | Icon for the send button | `CometChatMessageComposer.style.sendButtonImage = UIImage(named: "custom-send")` | -| **Send Button Tint Color** | Tint color for the send button image | `CometChatMessageComposer.style.sendButtonImageTint = CometChatTheme.white` | -| **Active Send Button Background Color** | Background color for the send button when active | `CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = CometChatTheme.primaryColor` | -| **Inactive Send Button Background Color** | Background color for the send button when inactive | `CometChatMessageComposer.style.inactiveSendButtonImageBackgroundColor = CometChatTheme.neutralColor300` | -| **Compose Box Background Color** | Background color for the compose box | `CometChatMessageComposer.style.composeBoxBackgroundColor = CometChatTheme.backgroundColor01` | -| **Compose Box Border Color** | Border color for the compose box | `CometChatMessageComposer.style.composeBoxBorderColor = CometChatTheme.borderColorDefault` | -| **Compose Box Border Width** | Border width for the compose box | `CometChatMessageComposer.style.composeBoxBorderWidth = 1` | -| **Compose Box Corner Radius** | Corner radius for the compose box | `CometChatMessageComposer.style.composerBoxCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r2)` | -| **Compose Box Separator Color** | Color for the separator in the compose box | `CometChatMessageComposer.style.composerSeparatorColor = CometChatTheme.borderColorLight` | -| **Attachment Image** | Icon for the attachment button | `CometChatMessageComposer.style.attachmentImage = UIImage(systemName: "plus.circle")` | -| **Attachment Image Tint** | Tint color for the attachment image | `CometChatMessageComposer.style.attachmentImageTint = CometChatTheme.iconColorSecondary` | -| **Voice Recording Image** | Icon for the voice recording button | `CometChatMessageComposer.style.voiceRecordingImage = UIImage(systemName: "mic")?.withRenderingMode(.alwaysTemplate)` | -| **Voice Recording Image Tint** | Tint color for the voice recording image | `CometChatMessageComposer.style.voiceRecordingImageTint = CometChatTheme.iconColorSecondary` | -| **AI Image** | Icon for the AI button | `CometChatMessageComposer.style.aiImage = UIImage(named: "ai-image")` | -| **AI Image Tint** | Tint color for the AI image | `CometChatMessageComposer.style.aiImageTint = CometChatTheme.iconColorSecondary` | -| **Sticker Image** | Icon for the sticker button | `CometChatMessageComposer.style.stickerImage = UIImage(named: "sticker-image")` | -| **Sticker Image Tint** | Tint color for the sticker image | `CometChatMessageComposer.style.stickerTint = CometChatTheme.iconColorSecondary` | -| **Edit Preview Title Font** | Font for the title in the edit preview | `CometChatMessageComposer.style.editPreviewTitleTextFont = CometChatTypography.Body.regular` | -| **Edit Preview Message Font** | Font for the message text in the edit preview | `CometChatMessageComposer.style.editPreviewMessageTextFont = CometChatTypography.Caption1.regular` | -| **Edit Preview Title Color** | Text color for the title in the edit preview | `CometChatMessageComposer.style.editPreviewTitleTextColor = CometChatTheme.textColorPrimary` | -| **Edit Preview Message Color** | Text color for the message in the edit preview | `CometChatMessageComposer.style.editPreviewMessageTextColor = CometChatTheme.textColorSecondary` | -| **Edit Preview Background Color** | Background color for the edit preview | `CometChatMessageComposer.style.editPreviewBackgroundColor = CometChatTheme.backgroundColor03` | -| **Edit Preview Corner Radius** | Corner radius for the edit preview | `CometChatMessageComposer.style.editPreviewCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r1)` | -| **Edit Preview Border Color** | Border color for the edit preview | `CometChatMessageComposer.style.editPreviewBorderColor = .clear` | -| **Edit Preview Border Width** | Border width for the edit preview | `CometChatMessageComposer.style.editPreviewBorderWidth = 0` | -| **Edit Preview Close Icon** | Icon for closing the edit preview | `CometChatMessageComposer.style.editPreviewCloseIcon = UIImage(systemName: "xmark")?.withRenderingMode(.alwaysTemplate)` | -| **Edit Preview Close Icon Tint** | Tint color for the close icon in the edit preview | `CometChatMessageComposer.style.editPreviewCloseIconTint = CometChatTheme.iconColorPrimary` | -| **Info Icon** | Icon for the info button | `CometChatMessageComposer.style.infoIcon = UIImage(systemName: "info.circle")` | -| **Info Icon Tint** | Tint color for the info icon | `CometChatMessageComposer.style.infoIconTint = CometChatTheme.errorColor` | -| **Info Text Color** | Text color for the info text | `CometChatMessageComposer.style.infoTextColor = CometChatTheme.errorColor` | -| **Info Text Font** | Font for the info text | `CometChatMessageComposer.style.infoTextFont = CometChatTypography.Caption1.regular` | -| **Info Separator Color** | Color for the separator in the info section | `CometChatMessageComposer.style.infoSeparatorColor = CometChatTheme.borderColorLight` | -| **Info Background Color** | Background color for the info section | `CometChatMessageComposer.style.infoBackgroundColor = CometChatTheme.backgroundColor02` | -| **Info Corner Radius** | Corner radius for the info section | `CometChatMessageComposer.style.infoCornerRadius = .init(cornerRadius: CometChatSpacing.Radius.r1)` | -| **Info Border Color** | Border color for the info section | `CometChatMessageComposer.style.infoBorderColor = .clear` | -| **Info Border Width** | Border width for the info section | `CometChatMessageComposer.style.infoBorderWidth = 0` | - - -#### 2. MediaRecorder Style - -To customize the media recording styling, you can apply the `MediaRecorderStyle` to the `MessageComposer` component. For more details, please refer to [MediaRecorder](/ui-kit/ios/component-styling#media-recorder) styles. - -**Global level styling** - - - ```swift -CometChatMessageComposer.mediaRecorderStyle.deleteButtonCornerRadius = .init(cornerRadius: 8) -CometChatMessageComposer.mediaRecorderStyle.pauseButtonCornerRadius = .init(cornerRadius: 8) -CometChatMessageComposer.mediaRecorderStyle.stopButtonCornerRadius = .init(cornerRadius: 8) -CometChatMessageComposer.mediaRecorderStyle.recordingButtonCornerRadius = .init(cornerRadius: 8) -CometChatMessageComposer.mediaRecorderStyle.recordingButtonBackgroundColor = UIColor(hex: "#F44649") -``` - - +import UIKit -**Instance level styling** +class CustomHeaderView: UIView { - - -```swift -// Create custom media recorder style -var mediaRecorderStyle = MediaRecorderStyle() -mediaRecorderStyle.deleteButtonCornerRadius = .init(cornerRadius: 8) -mediaRecorderStyle.pauseButtonCornerRadius = .init(cornerRadius: 8) -mediaRecorderStyle.stopButtonCornerRadius = .init(cornerRadius: 8) -mediaRecorderStyle.recordingButtonCornerRadius = .init(cornerRadius: 8) -mediaRecorderStyle.recordingButtonBackgroundColor = UIColor(hex: "#F44649") - -// Apply to message composer instance -let messageComposer = CometChatMessageComposer() -messageComposer.mediaRecorderStyle = mediaRecorderStyle -``` - - + private let iconImageView: UIImageView = { + let imageView = UIImageView() + imageView.image = UIImage(systemName: "bell.slash.fill") + imageView.tintColor = .purple + imageView.contentMode = .scaleAspectFit + return imageView + }() - - - + private let messageLabel: UILabel = { + let label = UILabel() + label.text = "User has paused their notifications" + label.textColor = .black + label.font = UIFont.systemFont(ofSize: 14, weight: .medium) + return label + }() -The following properties are exposed by Media Recorder Style: + override init(frame: CGRect) { + super.init(frame: frame) + setupView() + } -| Property | Description | Code | -|----------|-------------|------| -| **backgroundColor** | Sets the background color of the media recorder | `mediaRecorderStyle.backgroundColor: UIColor = CometChatTheme.backgroundColor01` | -| **borderWidth** | Defines the width of the border for the media recorder | `mediaRecorderStyle.borderWidth: CGFloat = 1` | -| **borderColor** | Specifies the border color of the media recorder | `mediaRecorderStyle.borderColor: UIColor = CometChatTheme.borderColorLight` | -| **cornerRadius** | Configures the corner radius of the media recorder | `mediaRecorderStyle.cornerRadius: CometChatCornerStyle? = nil` | -| **recordingButtonBackgroundColor** | Sets the background color of the recording button | `mediaRecorderStyle.recordingButtonBackgroundColor: UIColor = CometChatTheme.iconColorHighlight` | -| **recordingButtonCornerRadius** | Configures the corner radius of the recording button | `mediaRecorderStyle.recordingButtonCornerRadius: CometChatCornerStyle? = nil` | -| **recordingButtonBorderWidth** | Sets the border width of the recording button | `mediaRecorderStyle.recordingButtonBorderWidth: CGFloat = 0` | -| **recordingButtonBorderColor** | Sets the border color of the recording button | `mediaRecorderStyle.recordingButtonBorderColor: UIColor = .clear` | -| **recordingButtonImageTintColor** | Specifies the tint color of the recording button image | `mediaRecorderStyle.recordingButtonImageTintColor: UIColor = CometChatTheme.white` | -| **recordingButtonImage** | The image displayed on the recording button | `mediaRecorderStyle.recordingButtonImage: UIImage = UIImage(systemName: "mic.fill") ?? UIImage()` | -| **deleteButtonBackgroundColor** | Sets the background color of the delete button | `mediaRecorderStyle.deleteButtonBackgroundColor: UIColor = CometChatTheme.backgroundColor01` | -| **deleteButtonImageTintColor** | Specifies the tint color of the delete button image | `mediaRecorderStyle.deleteButtonImageTintColor: UIColor = CometChatTheme.iconColorSecondary` | -| **deleteButtonImage** | The image displayed on the delete button | `mediaRecorderStyle.deleteButtonImage: UIImage = UIImage(systemName: "trash.fill") ?? UIImage()` | -| **deleteButtonCornerRadius** | Configures the corner radius of the delete button | `mediaRecorderStyle.deleteButtonCornerRadius: CometChatCornerStyle? = nil` | -| **deleteButtonBorderWidth** | Sets the border width of the delete button | `mediaRecorderStyle.deleteButtonBorderWidth: CGFloat = 1` | -| **deleteButtonBorderColor** | Specifies the border color of the delete button | `mediaRecorderStyle.deleteButtonBorderColor: UIColor = CometChatTheme.borderColorLight` | + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + private func setupView() { + backgroundColor = UIColor.purple.withAlphaComponent(0.1) + layer.cornerRadius = 12 -#### 3. AI Options Style + addSubview(iconImageView) + addSubview(messageLabel) -To customize the AI options styling, you can apply the `AIOptionsStyle` to the `MessageComposer` component. For more details, please refer to [AIOptions](/ui-kit/ios/component-styling#media-recorder) styles. + iconImageView.translatesAutoresizingMaskIntoConstraints = false + messageLabel.translatesAutoresizingMaskIntoConstraints = false -**Global level styling** + NSLayoutConstraint.activate([ + iconImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12), + iconImageView.centerYAnchor.constraint(equalTo: centerYAnchor), + iconImageView.widthAnchor.constraint(equalToConstant: 20), + iconImageView.heightAnchor.constraint(equalToConstant: 20), - - -```swift -CometChatMessageComposer.aiOptionsStyle.backgroundColor = UIColor(hex: "#FFF9F5") -CometChatMessageComposer.aiOptionsStyle.textColor = .black -CometChatMessageComposer.aiOptionsStyle.aiImageTintColor = UIColor(hex: "#F76808") + messageLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 8), + messageLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12), + messageLabel.centerYAnchor.constraint(equalTo: centerYAnchor) + ]) + } +} ``` - - -**Instance level styling** +### sendButtonView + +Replace the default send button with a custom view. - - ```swift -// Create custom AI options style -var aIOptionsStyle = AIOptionsStyle() -aIOptionsStyle.backgroundColor = UIColor(hex: "#FFF9F5") -aIOptionsStyle.textColor = .black -aIOptionsStyle.aiImageTintColor = UIColor(hex: "#F76808") +import UIKit +import CometChatUIKitSwift -// Apply to message composer instance let messageComposer = CometChatMessageComposer() -messageComposer.aiOptionsStyle = aIOptionsStyle -``` - - - - - - - -The following properties are exposed by AI Options Style: - -| Property | Description | Code | -|----------|-------------|------| -| **errorViewTextFont** | Specifies the font used for the text in the error view | `aIOptionsStyle.errorViewTextFont: UIFont?` | -| **errorViewTextColor** | Sets the color of the text in the error view | `aIOptionsStyle.errorViewTextColor: UIColor?` | -| **emptyViewTextFont** | Specifies the font used for the text in the empty view | `aIOptionsStyle.emptyViewTextFont: UIFont?` | -| **emptyViewTextColor** | Sets the color of the text in the empty view | `aIOptionsStyle.emptyViewTextColor: UIColor?` | -| **aiImageTintColor** | Configures the tint color for AI-related images | `aIOptionsStyle.aiImageTintColor: UIColor = CometChatTheme.iconColorHighlight` | -| **textColor** | Sets the color of the text | `aIOptionsStyle.textColor: UIColor = CometChatTheme.textColorPrimary` | -| **textFont** | Specifies the font for the text | `aIOptionsStyle.textFont: UIFont = CometChatTypography.Heading4.regular` | -| **backgroundColor** | Sets the background color | `aIOptionsStyle.backgroundColor: UIColor = CometChatTheme.backgroundColor01` | -| **borderWidth** | Sets the width of the border | `aIOptionsStyle.borderWidth: CGFloat = 0` | -| **borderColor** | Sets the color of the border | `aIOptionsStyle.borderColor: UIColor = .clear` | -| **cornerRadius** | Configures the corner radius of the view | `aIOptionsStyle.cornerRadius: CometChatCornerStyle? = nil` | ---- - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can set maximum lines the text area will show before scrolling in the composer, edit a message, add header view and footer view to the composer, and more. - -Below is a list of customizations along with corresponding code snippets that the message composer offers: - -| Property | Description | Code | -|----------|-------------|------| -| setInitialComposerText | Sets the initial text in the composer when it loads | `setInitialComposerText("Hello")` | -| disableTypingEvents | Disables sending typing indicators when the user types | `disableTypingEvents = true` | -| disableMentions | Disables the mention feature in the composer | `disableMentions = true` | -| hideImageAttachmentOption | Hides the option to attach images | `hideImageAttachmentOption = true` | -| hideVideoAttachmentOption | Hides the option to attach videos | `hideVideoAttachmentOption = true` | -| hideAudioAttachmentOption | Hides the option to attach audio files | `hideAudioAttachmentOption = true` | -| hideFileAttachmentOption | Hides the option to attach files | `hideFileAttachmentOption = true` | -| hidePollsOption | Hides the option to create polls | `hidePollsOption = true` | -| hideCollaborativeDocumentOption | Hides the option for collaborative documents | `hideCollaborativeDocumentOption = true` | -| hideCollaborativeWhiteboardOption | Hides the option for collaborative whiteboards | `hideCollaborativeWhiteboardOption = true` | -| hideAttachmentButton | Hides the attachment button in the composer | `hideAttachmentButton = true` | -| hideVoiceRecordingButton | Hides the voice recording button | `hideVoiceRecordingButton = true` | -| hideStickersButton | Hides the stickers button | `hideStickersButton = true` | -| hideSendButton | Hides the send button | `hideSendButton = true` | -| setUser | Sets the user for direct messaging | `set(user: User)` | -| setGroup | Sets the group for group messaging | `set(group: Group)` | -| setParentMessageId | Sets the parent message ID for replying in a thread | `set(parentMessageId: 12345)` | -| setMaxLine | Sets the maximum number of lines for the composer input | `set(maxLine: 3)` | -| setCustomSoundForMessages | Sets a custom sound for sending messages | `set(customSoundForMessages: URL?)` | -| disableSoundForMessages | Disables sound while sending messages | `disableSoundForMessages = true` | - - ---- - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. - -#### AttachmentOptions - -By using `set(attachmentOptions:)`, you can set a list of custom `MessageComposerActions` for the MessageComposer Component. This will override the existing list of `CometChatMessageComposerAction`. - - - -```swift -let messageComposer = CometChatMessageComposer() -messageComposer.set(attachmentOptions: { user, group, controller in - return [CometChatMessageComposerAction] +messageComposer.set(sendButtonView: { user, group in + let button = UIButton(type: .system) + button.setImage(UIImage(systemName: "paperplane.fill"), for: .normal) + button.tintColor = UIColor.systemBlue + button.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.1) + button.layer.cornerRadius = 20 + return button }) ``` - - -**Demonstration** - - - - +### attachmentOptions -In this example, we are overriding the existing MessageComposerActions List with custom actions: +Customize the attachment menu options. - - ```swift +import UIKit +import CometChatUIKitSwift + let messageComposer = CometChatMessageComposer() -messageComposer.setAttachmentOptions { user, group, controller in - // Create custom action 1 - let customComposerAction1 = CometChatMessageComposerAction( - id: "customAction1", - text: "Custom Option 1", - startIcon: UIImage(systemName: "play_circle"), - startIconTint: .black, - textColor: .black, + +messageComposer.set(attachmentOptions: { user, group, controller in + let photoAction = CometChatMessageComposerAction( + id: "photo", + text: "Photo", + startIcon: UIImage(systemName: "photo"), + startIconTint: UIColor.systemBlue, + textColor: UIColor.label, onActionClick: { - print("Custom Action 1 clicked!") + print("Photo selected") } ) - // Create custom action 2 - let customComposerAction2 = CometChatMessageComposerAction( - id: "customAction2", - text: "Custom Option 2", - startIcon: UIImage(systemName: "add_box"), - startIconTint: .black, - textColor: .black, + let cameraAction = CometChatMessageComposerAction( + id: "camera", + text: "Camera", + startIcon: UIImage(systemName: "camera"), + startIconTint: UIColor.systemGreen, + textColor: UIColor.label, onActionClick: { - print("Custom Action 2 clicked!") + print("Camera selected") } ) - // Create custom action 3 - let customComposerAction3 = CometChatMessageComposerAction( - id: "customAction3", - text: "Custom Option 3", - startIcon: UIImage(systemName: "change_circle"), - startIconTint: .black, - textColor: .black, + let locationAction = CometChatMessageComposerAction( + id: "location", + text: "Location", + startIcon: UIImage(systemName: "location"), + startIconTint: UIColor.systemRed, + textColor: UIColor.label, onActionClick: { - print("Custom Action 3 clicked!") + print("Location selected") } ) - // Create custom action 4 - let customComposerAction4 = CometChatMessageComposerAction( - id: "customAction4", - text: "Custom Option 4", - startIcon: UIImage(systemName: "sunny"), - startIconTint: .black, - textColor: .black, - onActionClick: { - print("Custom Action 4 clicked!") - } - ) - - return [customComposerAction1, customComposerAction2, customComposerAction3, customComposerAction4] -} + return [photoAction, cameraAction, locationAction] +}) ``` - - - --- -#### SendButtonView +## Styling -By using `set(sendButtonView:)`, you can set a custom send button for the MessageComposer Component. +### Style Hierarchy + +1. Global styles (`CometChatMessageComposer.style`) apply to all instances +2. Instance styles override global for specific instances + +### Global Level Styling - - ```swift -let messageComposer = CometChatMessageComposer() -messageComposer.set(sendButtonView: { user, group in - let view = CustomSendButton() - return view -}) +import UIKit +import CometChatUIKitSwift + +// Apply global styles that affect all CometChatMessageComposer instances +CometChatMessageComposer.style.backgroundColor = UIColor.systemBackground +CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = UIColor.systemBlue +CometChatMessageComposer.style.attachmentImageTint = UIColor.systemGray +CometChatMessageComposer.style.voiceRecordingImageTint = UIColor.systemGray +CometChatMessageComposer.style.stickerTint = UIColor.systemGray +CometChatMessageComposer.style.aiImageTint = UIColor.systemPurple ``` - - -**Demonstration** +### Instance Level Styling + +```swift +import UIKit +import CometChatUIKitSwift + +// Create a custom style for a specific instance +var customStyle = MessageComposerStyle() +customStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +customStyle.activeSendButtonImageBackgroundColor = UIColor.systemOrange +customStyle.composeBoxBackgroundColor = UIColor.white +customStyle.composeBoxBorderColor = UIColor.systemGray4 +customStyle.composeBoxBorderWidth = 1 + +let messageComposer = CometChatMessageComposer() +messageComposer.style = customStyle +``` - + - - -```swift -import UIKit +### Key Style Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color | +| `borderWidth` | `CGFloat` | `0` | Border width | +| `borderColor` | `UIColor` | `.clear` | Border color | +| `cornerRadius` | `CometChatCornerStyle?` | `nil` | Corner radius | +| `placeHolderTextFont` | `UIFont` | `CometChatTypography.Body.regular` | Placeholder font | +| `placeHolderTextColor` | `UIColor` | `CometChatTheme.textColorTertiary` | Placeholder color | +| `textFiledColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Input text color | +| `textFiledFont` | `UIFont` | `CometChatTypography.Body.regular` | Input text font | +| `sendButtonImage` | `UIImage?` | System send icon | Send button icon | +| `sendButtonImageTint` | `UIColor` | `CometChatTheme.white` | Send button tint | +| `activeSendButtonImageBackgroundColor` | `UIColor` | `CometChatTheme.primaryColor` | Active send button background | +| `inactiveSendButtonImageBackgroundColor` | `UIColor` | `CometChatTheme.neutralColor300` | Inactive send button background | +| `composeBoxBackgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Compose box background | +| `composeBoxBorderColor` | `UIColor` | `CometChatTheme.borderColorDefault` | Compose box border color | +| `composeBoxBorderWidth` | `CGFloat` | `1` | Compose box border width | +| `attachmentImage` | `UIImage?` | System plus icon | Attachment button icon | +| `attachmentImageTint` | `UIColor` | `CometChatTheme.iconColorSecondary` | Attachment icon tint | +| `voiceRecordingImage` | `UIImage?` | System mic icon | Voice recording icon | +| `voiceRecordingImageTint` | `UIColor` | `CometChatTheme.iconColorSecondary` | Voice recording tint | + +### Customization Matrix + +| What to change | Where | Property/API | Example | +|----------------|-------|--------------|---------| +| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | +| Send button color | Style | `activeSendButtonImageBackgroundColor` | `UIColor.systemBlue` | +| Input text style | Style | `textFiledColor`, `textFiledFont` | Custom colors and fonts | +| Compose box look | Style | `composeBoxBackgroundColor`, `composeBoxBorderColor` | Custom styling | +| Attachment icon | Style | `attachmentImage`, `attachmentImageTint` | Custom icon | +| Hide attachment | Property | `hideAttachmentButton` | `composer.hideAttachmentButton = true` | +| Hide voice recording | Property | `hideVoiceRecordingButton` | `composer.hideVoiceRecordingButton = true` | +| Custom send button | View Slot | `set(sendButtonView:)` | See Custom View Slots | -class CustomSendButton: UIView { +--- - private let playButton: UIButton = { - let button = UIButton(type: .system) - let playImage = UIImage(systemName: "play.fill")?.withRenderingMode(.alwaysTemplate) - button.setImage(playImage, for: .normal) - button.tintColor = .purple - button.backgroundColor = .clear - button.addTarget(self, action: #selector(playButtonTapped), for: .touchUpInside) - return button - }() +## Props - // Closure to handle button tap - var onPlayTapped: (() -> Void)? +All props are optional. Sorted alphabetically. - override init(frame: CGRect) { - super.init(frame: frame) - setupView() - } +### disableMentions - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } +Disables the @mention feature in the composer. - private func setupView() { - backgroundColor = UIColor.purple.withAlphaComponent(0.1) - layer.cornerRadius = 12 - addSubview(playButton) +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | - playButton.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - playButton.centerXAnchor.constraint(equalTo: centerXAnchor), - playButton.centerYAnchor.constraint(equalTo: centerYAnchor), - playButton.widthAnchor.constraint(equalToConstant: 30), - playButton.heightAnchor.constraint(equalToConstant: 30) - ]) - } +### disableSoundForMessages - @objc private func playButtonTapped() { - onPlayTapped?() - } -} -``` - - +Disables sound when sending messages. ---- +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | -#### HeaderView +### disableTypingEvents -By using `set(headerView:)`, you can set a custom header view for the MessageComposer Component. +Disables sending typing indicators when the user types. - - -```swift -let messageComposer = CometChatMessageComposer() -messageComposer.set(headerView: { user, group in - let view = CustomHeaderView() - return view -}) -``` - - +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | -**Demonstration** +### hideAttachmentButton - - - +Hides the attachment button. - - -```swift -import UIKit +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | -class CustomHeaderView: UIView { +### hideAudioAttachmentOption - private let iconImageView: UIImageView = { - let imageView = UIImageView() - imageView.image = UIImage(systemName: "bell.slash.fill") - imageView.tintColor = .purple - imageView.contentMode = .scaleAspectFit - return imageView - }() +Hides the audio attachment option. - private let messageLabel: UILabel = { - let label = UILabel() - label.text = "User has paused their notifications" - label.textColor = .black - label.font = UIFont.systemFont(ofSize: 14, weight: .medium) - return label - }() +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | - override init(frame: CGRect) { - super.init(frame: frame) - setupView() - } +### hideCollaborativeDocumentOption - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } +Hides the collaborative document option. - private func setupView() { - backgroundColor = UIColor.purple.withAlphaComponent(0.1) - layer.cornerRadius = 12 +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | - addSubview(iconImageView) - addSubview(messageLabel) +### hideCollaborativeWhiteboardOption - iconImageView.translatesAutoresizingMaskIntoConstraints = false - messageLabel.translatesAutoresizingMaskIntoConstraints = false +Hides the collaborative whiteboard option. - NSLayoutConstraint.activate([ - iconImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12), - iconImageView.centerYAnchor.constraint(equalTo: centerYAnchor), - iconImageView.widthAnchor.constraint(equalToConstant: 20), - iconImageView.heightAnchor.constraint(equalToConstant: 20), +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | - messageLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 8), - messageLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12), - messageLabel.centerYAnchor.constraint(equalTo: centerYAnchor) - ]) - } -} -``` - - +### hideFileAttachmentOption +Hides the file attachment option. ---- +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | -#### SetTextFormatters +### hideImageAttachmentOption -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel, check out [CometChatMentionsFormatter](/ui-kit/ios/mentions-formatter-guide). +Hides the image attachment option. - - -```swift -// Create custom composer text style for mentions -let composerTextStyle = MentionTextStyle() - .set(textBackgroundColor: .white) - .set(textColor: UIColor.black) - .set(textFont: UIFont.systemFont(ofSize: 18, weight: .heavy)) - .set(loggedInUserTextColor: UIColor.systemTeal) - .set(loggedInUserTextFont: UIFont.systemFont(ofSize: 18, weight: .bold)) - -// Create custom mention formatter with the style -let customMentionFormatter = CometChatMentionsFormatter() - .set(composerTextStyle: composerTextStyle) - -// Configure message composer with the formatter -let messageComposerConfiguration = MessageComposerConfiguration() - .set(textFormatter: [customMentionFormatter]) - -// Apply to CometChatMessages -let cometChatMessages = CometChatMessages() - .set(user: user) - .set(messageComposerConfiguration: messageComposerConfiguration) -``` - - +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | ---- +### hidePollsOption - -To ensure that the `MessageComposer` is properly configured, passing the controller is mandatory. +Hides the polls option. -```swift -let composerView = CometChatMessageComposer() -composerView.set(controller: UIViewController) // Passing the controller is required -``` - +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideSendButton + +Hides the send button. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideStickersButton + +Hides the stickers button. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideVideoAttachmentOption + +Hides the video attachment option. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideVoiceRecordingButton + +Hides the voice recording button. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### maxLine + +Sets the maximum number of lines for the composer input before scrolling. + +| | | +|---|---| +| Type | `Int` | +| Default | `5` | + +### textFormatters + +Array of text formatters for customizing text display (e.g., mentions). + +| | | +|---|---| +| Type | `[CometChatTextFormatter]` | +| Default | `[]` | --- - -Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - +## Events + +The MessageComposer component does not emit any global UI events. --- -## Next Steps +## Troubleshooting -- [Message List](/ui-kit/ios/message-list) — Display and customize the message list -- [Message Header](/ui-kit/ios/message-header) — Customize the conversation header -- [Mentions Formatter](/ui-kit/ios/mentions-formatter-guide) — Configure @mention formatting +| Issue | Solution | +|-------|----------| +| Send button not working | Ensure user or group is set on the composer | +| Attachments not showing | Check that attachment options are not hidden | +| Voice recording not working | Verify microphone permissions are granted | +| Mentions not working | Ensure `disableMentions` is not set to true | +| Typing indicators not sent | Check that `disableTypingEvents` is not set to true | --- + +## Related Components + +- [Message List](/ui-kit/ios/message-list) - Display messages in a conversation +- [Message Header](/ui-kit/ios/message-header) - Display user/group details +- [Messages](/ui-kit/ios/messages) - Parent component containing MessageComposer +- [Mentions Formatter](/ui-kit/ios/mentions-formatter-guide) - Configure @mention formatting diff --git a/ui-kit/ios/message-header.mdx b/ui-kit/ios/message-header.mdx index fab93ed10..611d7f976 100644 --- a/ui-kit/ios/message-header.mdx +++ b/ui-kit/ios/message-header.mdx @@ -1,401 +1,262 @@ --- title: "Message Header" -sidebarTitle: "Message Header" -description: "Display user or group details with typing indicators and navigation controls in CometChat UI Kit for iOS" +description: "Display user or group details with typing indicators and navigation controls" --- -## Overview - -`MessageHeader` is a [Component](/ui-kit/ios/components-overview#components) that showcases the [User](/sdk/ios/users-overview) or [Group](/sdk/ios/groups-overview) details in the toolbar. It also presents a typing indicator and a back navigation button for ease of use. +The `CometChatMessageHeader` component displays user or group details in the toolbar including avatar, name, status, and typing indicators. It also provides navigation controls and call buttons. -The `MessageHeader` is comprised of the following components: - -| Components | Description | -|------------|-------------| -| ListItem | This component's view consists of avatar, status indicator, title, and subtitle. The fields are mapped with the SDK's [User](/sdk/ios/users-overview) and [Group](/sdk/ios/groups-overview) class. | -| Back Button | Allows users to navigate back from the current activity or screen to the previous one | - ---- - -## Usage - -### Integration - -You can add the `MessageHeader` component directly by setting the user: - -```swift -// Set the user for the message header -messageHeader.set(user: user) -``` - ---- - -### Actions - -[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -The `MessageHeader` component does not have any exposed actions. - -#### 1. set(onBack:) - -The `set(onBack:)` method becomes valuable when you need to override the action triggered upon pressing the back button in CometChatMessageHeader. - - - -```swift -cometChatMessageHeader.set(onBack: { - // Handle back button action -}) -``` - - - ---- - -#### 2. set(onError:) - -This method proves helpful when you need to customize the action taken upon encountering an error in CometChatMessageHeader. - - - -```swift -cometChatMessageHeader.set(onError: { error in - // Handle error -}) + +```json +{ + "component": "CometChatMessageHeader", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays user or group details in the toolbar with avatar, name, status, typing indicators, and navigation controls.", + "inherits": "UIView", + "primaryOutput": { + "callback": "onBack", + "type": "() -> Void" + }, + "props": { + "data": { + "user": { + "type": "User?", + "default": "nil", + "note": "User to display in header" + }, + "group": { + "type": "Group?", + "default": "nil", + "note": "Group to display in header" + } + }, + "callbacks": { + "onBack": "() -> Void", + "onError": "(CometChatException) -> Void" + }, + "visibility": { + "hideBackButton": { "type": "Bool", "default": false }, + "hideUserStatus": { "type": "Bool", "default": false }, + "hideVideoCallButton": { "type": "Bool", "default": false }, + "hideVoiceCallButton": { "type": "Bool", "default": false } + }, + "viewSlots": { + "listItemView": "(User?, Group?) -> UIView", + "leadingView": "(User?, Group?) -> UIView", + "titleView": "(User?, Group?) -> UIView", + "subtitleView": "(User?, Group?) -> UIView", + "trailView": "(User?, Group?) -> UIView" + } + }, + "events": [], + "sdkListeners": [ + "onUserOnline", + "onUserOffline", + "onTypingStarted", + "onTypingEnded" + ], + "compositionExample": { + "description": "MessageHeader is typically used within CometChatMessages at the top of the chat screen", + "components": ["CometChatMessageHeader", "CometChatMessageList", "CometChatMessageComposer"], + "flow": "User views header → sees recipient info → taps back to return to conversations" + }, + "types": {} +} ``` - - + --- -### Filters +## Where It Fits -Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for more customization. Filters can be applied using `RequestBuilders` of the Chat SDK. +`CometChatMessageHeader` displays the recipient's information at the top of the chat screen. It's typically used within `CometChatMessages` alongside `CometChatMessageList` and `CometChatMessageComposer`. -The `MessageHeader` component does not have any exposed filters. - ---- - -### Events - -[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. - -The `MessageHeader` component does not produce any events. - ---- - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. - -#### 1. MessageHeader Style - -To customize the appearance, you can assign a `MessageHeaderStyle` object to the `MessageHeader` component. - -**Global level styling** - - - ```swift -// Create custom avatar style -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.textFont = UIFont(name: "Times-New-Roman", size: 18) - -// Apply global message header styling -CometChatMessageHeader.style.titleTextColor = UIColor(hex: "#F76808") -CometChatMessageHeader.style.titleTextFont = UIFont(name: "Times-New-Roman", size: 16) -CometChatMessageHeader.style.subtitleTextFont = UIFont(name: "Times-New-Roman", size: 12) -CometChatMessageHeader.style.avatarStyle = customAvatarStyle -``` - - - -**Instance level styling** +import UIKit +import CometChatUIKitSwift +import CometChatSDK - - -```swift -// Create custom avatar style -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.textFont = UIFont(name: "Times-New-Roman", size: 18) - -// Create custom message header style -let messageHeaderStyle = MessageHeaderStyle() -messageHeaderStyle.titleTextColor = UIColor(hex: "#F76808") -messageHeaderStyle.titleTextFont = UIFont(name: "Times-New-Roman", size: 16) -messageHeaderStyle.subtitleTextFont = UIFont(name: "Times-New-Roman", size: 12) - -// Apply styles to instance -let messageHeader = CometChatMessageHeader() -messageHeader.style = messageHeaderStyle -messageHeader.avatarStyle = customAvatarStyle +class ChatViewController: UIViewController { + + private var messageHeader: CometChatMessageHeader! + + override func viewDidLoad() { + super.viewDidLoad() + setupMessageHeader() + } + + private func setupMessageHeader(for user: User) { + messageHeader = CometChatMessageHeader() + messageHeader.set(user: user) + + // Handle back button + messageHeader.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) + }) + + view.addSubview(messageHeader) + } +} ``` - - - + +--- -The properties exposed by `MessageHeaderStyle` are as follows: - -| Property | Description | Code | -|----------|-------------|------| -| **Title Text Color** | Sets the text color of the header title | `CometChatMessageHeader.style.titleTextColor = UIColor.black` | -| **Title Text Font** | Sets the font style of the header title | `CometChatMessageHeader.style.titleTextFont = UIFont.boldSystemFont(ofSize: 18)` | -| **Subtitle Text Color** | Sets the text color of the subtitle in the header | `CometChatMessageHeader.style.subtitleTextColor = UIColor.gray` | -| **Subtitle Text Font** | Sets the font style of the subtitle in the header | `CometChatMessageHeader.style.subtitleTextFont = UIFont.systemFont(ofSize: 14)` | -| **Back Button Image Tint Color** | Sets the tint color of the back button image | `CometChatMessageHeader.style.backButtonImageTintColor = UIColor.blue` | -| **Private Group Badge Tint Color** | Sets the tint color of the private group badge | `CometChatMessageHeader.style.privateGroupBadgeImageTintColor = UIColor.green` | -| **Password-Protected Badge Tint Color** | Sets the tint color of the password-protected group badge | `CometChatMessageHeader.style.passwordProtectedGroupBadgeImageTintColor = UIColor.orange` | -| **Private Group Background Color** | Sets the background color of the private group badge | `CometChatMessageHeader.style.privateGroupImageBackgroundColor = UIColor.lightGray` | -| **Password-Protected Background Color** | Sets the background color of the password-protected group badge | `CometChatMessageHeader.style.passwordGroupImageBackgroundColor = UIColor.red` | -| **Group Image Background Color** | Sets the background color for group icons in the header | `CometChatMessageHeader.style.groupImageBackgroundColor = UIColor.clear` | -| **Avatar Style** | Customizes the appearance of the avatar in the header | `CometChatMessageHeader.style.avatarStyle = customAvatarStyle` | -| **Background Color** | Sets the background color of the header | `CometChatMessageHeader.style.backgroundColor = UIColor.white` | -| **Corner Radius** | Sets the corner radius of the header | `CometChatMessageHeader.style.cornerRadius = CometChatCornerStyle(cornerRadius: 8)` | -| **Border Width** | Sets the border width of the header | `CometChatMessageHeader.style.borderWidth = 2` | -| **Border Color** | Sets the border color of the header | `CometChatMessageHeader.style.borderColor = UIColor.gray` | -| **Back Button Icon** | Sets a custom icon for the back button | `CometChatMessageHeader.style.backButtonIcon = UIImage(named: "customBackIcon")` | -| **Private Group Icon** | Sets a custom icon for private groups | `CometChatMessageHeader.style.privateGroupIcon = UIImage(named: "privateIcon")` | -| **Protected Group Icon** | Sets a custom icon for password-protected groups | `CometChatMessageHeader.style.protectedGroupIcon = UIImage(named: "protectedIcon")` | -| **Background Image** | Sets a background image for the header | `CometChatMessageHeader.style.backgroundImage = UIImage(named: "headerBackground")` | -| **New Chat Icon** | Sets a custom icon for the new chat button (AI agent) | `CometChatAIAssistantChatHistory.newChatIcon = UIImage(named: "iconName")` | -| **Chat History Icon** | Sets a custom icon for the chat history button (AI agent) | `CometChatAIAssistantChatHistory.chatHistoryIcon = UIImage(named: "iconName")` | - -#### 2. Avatar Style - -If you want to apply customized styles to the `Avatar` component within the `MessageHeader` Component, you can use the following code snippet. For more information, refer to [Avatar Styles](/ui-kit/ios/component-styling#avatar#methods). - -**Global level styling** - - - -```swift -// Create custom avatar style with rounded corners -let customAvatarStyle = AvatarStyle() -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) - -// Apply globally -CometChatMessageHeader.style.avatarStyle = customAvatarStyle -``` - - - -**Instance level styling** +## Minimal Render - - ```swift -// Create custom avatar style -let customAvatarStyle = AvatarStyle() -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) +import CometChatUIKitSwift +import CometChatSDK -// Apply to instance let messageHeader = CometChatMessageHeader() -messageHeader.avatarStyle = customAvatarStyle +messageHeader.set(user: user) ``` - - - + --- -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets: +## Actions and Events -| Method | Description | Code | -|--------|-------------|------| -| set(user:User) | Sets message header for CometChat user | `.set(user:User)` | -| set(group:Group) | Sets message header for CometChat group | `.set(group:Group)` | -| hideBackButton | Hides the back button of message header | `hideBackButton = true` | -| hideUserStatus | Hides or shows the user status (online/offline/last active at) | `hideUserStatus = true` | -| hideVideoCallButton | Hides the video call button | `hideVideoCallButton = true` | -| hideVoiceCallButton | Hides the voice call button | `hideVoiceCallButton = true` | -| hideChatHistoryButton | Hides the chat history button in the component | `CometChatAIAssistantChatHistory.hideChatHistoryButton = true` | -| hideNewChatButton | Hides the new chat button in the component (AI agent) | `CometChatAIAssistantChatHistory.hideNewChatButton = true` | -| onNewChatButtonClicked | Handles actions when the "New Chat" button is clicked | `CometChatAIAssistantChatHistory.set(onNewChatButtonClicked: { user in })` | -| onMessageClicked | Handles actions when a message is clicked | `CometChatAIAssistantChatHistory.set(onMessageClicked: { message in })` | +### Callback Props ---- +#### onBack -### Advanced +Fires when the back button is pressed. Use this for custom navigation handling. -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. +```swift +import CometChatUIKitSwift -#### Date Time Formatter +let messageHeader = CometChatMessageHeader() -The `CometChatMessageHeader` component supports full customization of how date and time are displayed using the [CometChatDateTimeFormatter](/ui-kit/ios/localize#datetimeformatter). +messageHeader.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) +}) +``` -This enables developers to localize, format, or personalize the date and time strings shown next to the message header such as "Today", "Yesterday", "12:45 PM", etc. +#### onError -**1. Component-Level (Global)** +Fires when an error occurs. - - ```swift -// Customize time format -CometChatMessageHeader.dateTimeFormatter.time = { timestamp in - return "Last seen at " + DateFormatter.localizedString(from: Date(timeIntervalSince1970: TimeInterval(timestamp)), dateStyle: .none, timeStyle: .short) -} +import CometChatUIKitSwift -// Customize today format -CometChatMessageHeader.dateTimeFormatter.today = { timestamp in - return "Last seen: Today • \(formattedTime(from: timestamp))" -} +let messageHeader = CometChatMessageHeader() -// Customize older dates format -CometChatMessageHeader.dateTimeFormatter.otherDay = { timestamp in - let formatter = DateFormatter() - formatter.dateFormat = "dd MMM yyyy" - return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) -} +messageHeader.set(onError: { error in + print("Error: \(error.errorDescription)") +}) ``` - - -**2. Instance-Level (Local)** +### Actions Reference - - -```swift -let messageHeader = CometChatMessageHeader() -messageHeader.dateTimeFormatter.yesterday = { timestamp in - return "Yesterday at " + formattedTime(from: timestamp) -} -``` - - +| Method | Description | Example | +|--------|-------------|---------| +| `set(onBack:)` | Triggered when back button is pressed | Custom navigation | +| `set(onError:)` | Triggered when an error occurs | Show error alert | +| `set(user:)` | Sets the user to display | Configure header for user | +| `set(group:)` | Sets the group to display | Configure header for group | -##### Available Closures +### SDK Events (Real-Time, Automatic) -| Property | Description | Code | -|----------|-------------|------| -| time | Called to format a timestamp as a standard time (e.g., "12:30 PM") | `CometChatMessageHeader.dateTimeFormatter.time = { ... }` | -| today | Called when rendering messages sent today | `CometChatMessageHeader.dateTimeFormatter.today = { ... }` | -| yesterday | Called for yesterday's messages | `CometChatMessageHeader.dateTimeFormatter.yesterday = { ... }` | -| lastweek | Called for messages within the last week | `CometChatMessageHeader.dateTimeFormatter.lastweek = { ... }` | -| otherDay | Called for dates older than last week | `CometChatMessageHeader.dateTimeFormatter.otherDay = { ... }` | -| minute | Called when referring to "a minute ago" | `CometChatMessageHeader.dateTimeFormatter.minute = { ... }` | -| minutes | Called for "x minutes ago" | `CometChatMessageHeader.dateTimeFormatter.minutes = { ... }` | -| hour | Called for "an hour ago" | `CometChatMessageHeader.dateTimeFormatter.hour = { ... }` | -| hours | Called for "x hours ago" | `CometChatMessageHeader.dateTimeFormatter.hours = { ... }` | - -Each closure receives a timestamp (Int, representing UNIX time) and must return a String representing the formatted time. +| SDK Listener | Internal behavior | +|--------------|-------------------| +| `onUserOnline` | Updates status indicator to online | +| `onUserOffline` | Updates status indicator to offline | +| `onTypingStarted` | Shows typing indicator in subtitle | +| `onTypingEnded` | Hides typing indicator | --- -#### SetListItemView +## Custom View Slots + +| Slot | Signature | Replaces | +|------|-----------|----------| +| `listItemView` | `(User?, Group?) -> UIView` | Entire header content | +| `leadingView` | `(User?, Group?) -> UIView` | Avatar / left section | +| `titleView` | `(User?, Group?) -> UIView` | Name / title text | +| `subtitleView` | `(User?, Group?) -> UIView` | Status / subtitle text | +| `trailView` | `(User?, Group?) -> UIView` | Right side (call buttons) | -With this function, you can assign a custom ListItem to the message header Component. +### listItemView + +Replace the entire header content with a custom view. - - ```swift -let cometChatMessageHeader = CometChatMessageHeader() -cometChatMessageHeader.set(listItemView: { user, group in - let view = CustomListItemView() - return view -}) -``` - - +import UIKit +import CometChatUIKitSwift +import CometChatSDK -**Demonstration** +let messageHeader = CometChatMessageHeader() - - - +messageHeader.set(listItemView: { user, group in + let customView = CustomHeaderView() + customView.configure(user: user, group: group) + return customView +}) +``` -You can create a `CustomListItemView` as a custom `UIView` which will be inflated in `setListItemView()`: +You can create a `CustomHeaderView` as a custom `UIView`: - - ```swift import UIKit +import CometChatSDK -class CustomListItemView: UIView { - +class CustomHeaderView: UIView { + private let backButton: UIButton = { let button = UIButton(type: .system) - let image = UIImage(systemName: "chevron.left")?.withRenderingMode(.alwaysTemplate) - button.setImage(image, for: .normal) + button.setImage(UIImage(systemName: "chevron.left"), for: .normal) button.tintColor = .black return button }() - - private let profileImageView: UIView = { - let view = UIView() - view.backgroundColor = UIColor.systemPurple - view.layer.cornerRadius = 18 - view.clipsToBounds = true - - let label = UILabel() - label.text = "GA" - label.font = UIFont.systemFont(ofSize: 16, weight: .bold) - label.textColor = .white - label.textAlignment = .center - label.translatesAutoresizingMaskIntoConstraints = false - - view.addSubview(label) - - NSLayoutConstraint.activate([ - label.centerXAnchor.constraint(equalTo: view.centerXAnchor), - label.centerYAnchor.constraint(equalTo: view.centerYAnchor) - ]) - - return view + + private let profileImageView: UIImageView = { + let imageView = UIImageView() + imageView.contentMode = .scaleAspectFill + imageView.layer.cornerRadius = 18 + imageView.clipsToBounds = true + imageView.backgroundColor = .lightGray + return imageView }() - + private let nameLabel: UILabel = { let label = UILabel() - label.text = "George Alan" - label.font = UIFont.systemFont(ofSize: 16, weight: .bold) + label.font = UIFont.systemFont(ofSize: 16, weight: .semibold) label.textColor = .black return label }() - + private let statusLabel: UILabel = { let label = UILabel() - label.text = "Online" - label.font = UIFont.systemFont(ofSize: 12, weight: .regular) + label.font = UIFont.systemFont(ofSize: 12) label.textColor = .gray return label }() - + private let videoCallButton: UIButton = { let button = UIButton(type: .system) - let image = UIImage(systemName: "video.fill")?.withRenderingMode(.alwaysTemplate) - button.setImage(image, for: .normal) + button.setImage(UIImage(systemName: "video.fill"), for: .normal) button.tintColor = .black return button }() - + private let callButton: UIButton = { let button = UIButton(type: .system) - let image = UIImage(systemName: "phone.fill")?.withRenderingMode(.alwaysTemplate) - button.setImage(image, for: .normal) + button.setImage(UIImage(systemName: "phone.fill"), for: .normal) button.tintColor = .black return button }() - + override init(frame: CGRect) { super.init(frame: frame) setupView() @@ -445,39 +306,41 @@ class CustomListItemView: UIView { rightButtonsStack.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } + + func configure(user: User?, group: Group?) { + nameLabel.text = user?.name ?? group?.name ?? "Chat" + if let user = user { + statusLabel.text = user.status == .online ? "Online" : "Offline" + } else if let group = group { + statusLabel.text = "\(group.membersCount) members" + } + } } ``` - - +### leadingView ---- +Customize the leading view (avatar area) of the header. -#### SetLeadingView +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK -You can modify the leading view of a group cell using `.set(leadingView:)`. +let messageHeader = CometChatMessageHeader() - - -```swift -cometChatMessageHeader.set(leadingView: { user, group in +messageHeader.set(leadingView: { user, group in let view = CustomLeadingView() - return view + return view }) ``` - - - -**Demonstration** -You can create a `CustomLeadingView` as a custom `UIView` which will be inflated in `setLeadingView()`: +You can create a `CustomLeadingView` as a custom `UIView`: - - ```swift import UIKit @@ -493,17 +356,16 @@ class CustomLeadingView: UIView { return imageView }() - private let joinButton: UIButton = { - let button = UIButton() - button.setTitle("Join", for: .normal) - button.setTitleColor(.white, for: .normal) - button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .bold) - button.backgroundColor = .orange - button.layer.cornerRadius = 6 - button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16) - button.setImage(UIImage(systemName: "star.circle"), for: .normal) - button.setTitle("Admin", for: .normal) - return button + private let badgeLabel: UILabel = { + let label = UILabel() + label.text = "Admin" + label.font = UIFont.systemFont(ofSize: 10, weight: .bold) + label.textColor = .white + label.backgroundColor = .orange + label.textAlignment = .center + label.layer.cornerRadius = 6 + label.clipsToBounds = true + return label }() override init(frame: CGRect) { @@ -517,10 +379,10 @@ class CustomLeadingView: UIView { private func setupView() { addSubview(profileImageView) - addSubview(joinButton) + addSubview(badgeLabel) profileImageView.translatesAutoresizingMaskIntoConstraints = false - joinButton.translatesAutoresizingMaskIntoConstraints = false + badgeLabel.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ profileImageView.leadingAnchor.constraint(equalTo: leadingAnchor), @@ -530,45 +392,41 @@ class CustomLeadingView: UIView { profileImageView.heightAnchor.constraint(equalToConstant: 40), profileImageView.widthAnchor.constraint(equalToConstant: 40), - joinButton.trailingAnchor.constraint(equalTo: profileImageView.trailingAnchor), - joinButton.leadingAnchor.constraint(equalTo: profileImageView.leadingAnchor), - joinButton.bottomAnchor.constraint(equalTo: profileImageView.bottomAnchor), - joinButton.heightAnchor.constraint(equalToConstant: 12) + badgeLabel.trailingAnchor.constraint(equalTo: profileImageView.trailingAnchor), + badgeLabel.bottomAnchor.constraint(equalTo: profileImageView.bottomAnchor), + badgeLabel.widthAnchor.constraint(equalToConstant: 40), + badgeLabel.heightAnchor.constraint(equalToConstant: 12) ]) } } ``` - - ---- +### titleView -#### SetTitleView +Customize the title view of the header. -You can customize the title view of a group cell using `.set(titleView:)`. - - - ```swift -cometChatMessageHeader.set(titleView: { user, group in +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let messageHeader = CometChatMessageHeader() + +messageHeader.set(titleView: { user, group in let view = CustomTitleView() return view }) ``` - - - -**Demonstration** -You can create a `CustomTitleView` as a custom `UIView` which will be inflated in `setTitleView()`: +You can create a `CustomTitleView` as a custom `UIView`: - - ```swift +import UIKit + class CustomTitleView: UIView { private let titleLabel: UILabel = { @@ -636,36 +494,56 @@ class CustomTitleView: UIView { } } ``` - - - ---- -#### SetTrailView +### subtitleView -You can modify the trailing view of a message header using `.set(trailView:)`. +Customize the subtitle area (status, typing indicator). - - ```swift -cometChatMessageHeader.set(trailView: { user, group in - let view = CustomTrailView() - return view +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let messageHeader = CometChatMessageHeader() + +messageHeader.set(subtitleView: { user, group in + let label = UILabel() + label.font = UIFont.systemFont(ofSize: 13) + label.textColor = UIColor.secondaryLabel + + if let user = user { + label.text = user.status == .online ? "🟢 Online" : "⚫ Offline" + } else if let group = group { + label.text = "\(group.membersCount) members" + } + + return label }) ``` - - -**Demonstration** +### trailView + +Customize the right side of the header (call buttons, etc.). + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let messageHeader = CometChatMessageHeader() + +messageHeader.set(trailView: { user, group in + let view = CustomTrailView() + return view +}) +``` - + -You can create a `CustomTrailView` as a custom `UIView` which will be inflated in `setTrailView()`: +You can create a `CustomTrailView` as a custom `UIView`: - - ```swift import UIKit @@ -689,7 +567,7 @@ class CustomTrailView: UIView { private let bookMarkButton: UIButton = { let button = UIButton(type: .system) - let image = UIImage(systemName: "phone.fill")?.withRenderingMode(.alwaysTemplate) + let image = UIImage(systemName: "bookmark.fill")?.withRenderingMode(.alwaysTemplate) button.setImage(image, for: .normal) button.tintColor = .black return button @@ -705,15 +583,12 @@ class CustomTrailView: UIView { } private func setupView() { - let buttonsStack = UIStackView(arrangedSubviews: [videoCallButton, callButton]) + let buttonsStack = UIStackView(arrangedSubviews: [videoCallButton, callButton, bookMarkButton]) buttonsStack.axis = .horizontal buttonsStack.spacing = 16 buttonsStack.distribution = .fillEqually - buttonsStack.addArrangedSubview(videoCallButton) - buttonsStack.addArrangedSubview(callButton) - buttonsStack.addArrangedSubview(bookMarkButton) - + addSubview(buttonsStack) buttonsStack.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ @@ -725,74 +600,214 @@ class CustomTrailView: UIView { } } ``` - - --- -#### SetSubTitleView +## Styling + +### Style Hierarchy -You can customize the subtitle view for each group item to meet your requirements. +1. Global styles (`CometChatMessageHeader.style`) apply to all instances +2. Instance styles override global for specific instances + +### Global Level Styling - - ```swift -cometChatMessageHeader.set(subtitleView: { user, group in - let view = CustomSubtitleView() - return view -}) +import UIKit +import CometChatUIKitSwift + +// Apply global styles that affect all CometChatMessageHeader instances +CometChatMessageHeader.style.backgroundColor = UIColor.systemBackground +CometChatMessageHeader.style.titleTextColor = UIColor.label +CometChatMessageHeader.style.titleTextFont = UIFont.systemFont(ofSize: 17, weight: .semibold) +CometChatMessageHeader.style.subtitleTextColor = UIColor.secondaryLabel +CometChatMessageHeader.style.subtitleTextFont = UIFont.systemFont(ofSize: 13) +CometChatMessageHeader.style.backButtonImageTintColor = UIColor.systemBlue + +// Custom avatar style +let avatarStyle = AvatarStyle() +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) +CometChatMessageHeader.style.avatarStyle = avatarStyle ``` - - -**Demonstration** +### Instance Level Styling + +```swift +import UIKit +import CometChatUIKitSwift + +// Create a custom style for a specific instance +var customStyle = MessageHeaderStyle() +customStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +customStyle.titleTextColor = UIColor.darkGray +customStyle.titleTextFont = UIFont.systemFont(ofSize: 18, weight: .bold) +customStyle.subtitleTextColor = UIColor.gray + +let messageHeader = CometChatMessageHeader() +messageHeader.style = customStyle +``` - + -You can seamlessly integrate this `CustomSubtitleView` UIView file into the `.set(subtitleView:)` method within CometChatMessageHeader: +### Key Style Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color | +| `borderWidth` | `CGFloat` | `0` | Border width | +| `borderColor` | `UIColor` | `.clear` | Border color | +| `cornerRadius` | `CometChatCornerStyle?` | `nil` | Corner radius | +| `titleTextColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Title text color | +| `titleTextFont` | `UIFont` | `CometChatTypography.Heading4.medium` | Title font | +| `subtitleTextColor` | `UIColor` | `CometChatTheme.textColorSecondary` | Subtitle text color | +| `subtitleTextFont` | `UIFont` | `CometChatTypography.Body.regular` | Subtitle font | +| `backButtonImageTintColor` | `UIColor` | `CometChatTheme.iconColorPrimary` | Back button tint | +| `backButtonIcon` | `UIImage?` | System chevron | Back button icon | +| `privateGroupBadgeImageTintColor` | `UIColor` | `CometChatTheme.iconColorSecondary` | Private group badge tint | +| `passwordProtectedGroupBadgeImageTintColor` | `UIColor` | `CometChatTheme.iconColorSecondary` | Password group badge tint | +| `avatarStyle` | `AvatarStyle` | Default avatar style | Avatar customization | + +### Customization Matrix + +| What to change | Where | Property/API | Example | +|----------------|-------|--------------|---------| +| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | +| Title appearance | Style | `titleTextColor`, `titleTextFont` | Custom colors and fonts | +| Subtitle appearance | Style | `subtitleTextColor`, `subtitleTextFont` | Custom colors and fonts | +| Back button | Style | `backButtonIcon`, `backButtonImageTintColor` | Custom icon and color | +| Avatar look | Style | `avatarStyle` | `AvatarStyle()` with custom radius | +| Hide back button | Property | `hideBackButton` | `header.hideBackButton = true` | +| Hide status | Property | `hideUserStatus` | `header.hideUserStatus = true` | +| Custom subtitle | View Slot | `set(subtitleView:)` | See Custom View Slots | + +--- + +## Props + +All props are optional. Sorted alphabetically. + +### hideBackButton + +Hides the back button in the header. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideUserStatus + +Hides the user status (online/offline/last active). + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideVideoCallButton + +Hides the video call button. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideVoiceCallButton + +Hides the voice call button. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +## Events + +The MessageHeader component does not emit any global UI events. + +--- + +## Date Time Formatter + +Customize how timestamps appear in the message header (e.g., "Last seen at...") using the `CometChatDateTimeFormatter`. + +### Global Level Formatting - - ```swift -import UIKit +import CometChatUIKitSwift -class CustomSubtitleView: UILabel { - - init(membersCount: Int) { - super.init(frame: .zero) - self.text = "\(membersCount) members • \("group_description")" - self.textColor = UIColor.gray - self.font = UIFont.systemFont(ofSize: 14) - self.numberOfLines = 1 - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } +// Customize time format for last seen +CometChatMessageHeader.dateTimeFormatter.time = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "h:mm a" + return "Last seen at " + formatter.string(from: date) } -``` - - ---- +// Customize today format +CometChatMessageHeader.dateTimeFormatter.today = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "h:mm a" + return "Last seen today at " + formatter.string(from: date) +} + +// Customize yesterday format +CometChatMessageHeader.dateTimeFormatter.yesterday = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "h:mm a" + return "Last seen yesterday at " + formatter.string(from: date) +} +``` - -To ensure that the `MessageHeader` is properly configured, passing the controller is mandatory. +### Instance Level Formatting ```swift -let headerView = CometChatMessageHeader() -headerView.set(controller: UIViewController) // Passing the controller is required +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() + +messageHeader.dateTimeFormatter.otherDay = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "MMM d, yyyy" + return "Last seen on " + formatter.string(from: date) +} ``` - + +### Available Formatters + +| Formatter | Purpose | Default Format | +|-----------|---------|----------------| +| `time` | Standard time display | `h:mm a` | +| `today` | Last seen today | `Today at h:mm a` | +| `yesterday` | Last seen yesterday | `Yesterday at h:mm a` | +| `lastweek` | Last seen within last week | Day name | +| `otherDay` | Last seen older dates | `MMM d, yyyy` | --- -## Next Steps +## Troubleshooting -- [Message List](/ui-kit/ios/message-list) — Display and customize the message list -- [Message Composer](/ui-kit/ios/message-composer) — Customize the message input component -- [Conversations](/ui-kit/ios/conversations) — Manage conversation lists +| Issue | Solution | +|-------|----------| +| Header not showing user info | Ensure user or group is set on the header | +| Status not updating | Check SDK connection and user presence listeners | +| Back button not working | Verify `onBack` callback is set and `hideBackButton` is false | +| Typing indicator not showing | Ensure typing events are enabled in SDK | +| Call buttons not appearing | Check that `hideVideoCallButton` and `hideVoiceCallButton` are false | --- + +## Related Components + +- [Messages](/ui-kit/ios/messages) - Parent component containing MessageHeader +- [Message List](/ui-kit/ios/message-list) - Display messages in a conversation +- [Message Composer](/ui-kit/ios/message-composer) - Send messages in a conversation +- [Conversations](/ui-kit/ios/conversations) - Navigate back to conversation list diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index d39830cef..e20864a09 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -1,778 +1,542 @@ --- title: "Message List" -sidebarTitle: "Message List" -description: "Display and manage real-time chat messages with various message types using CometChat UI Kit for iOS" +description: "Display and manage real-time chat messages with various message types" --- -## Overview - -`MessageList` is a [Composite Component](/ui-kit/ios/components-overview#composite-components) that displays a list of messages and effectively manages real-time operations. It includes various types of messages such as Text Messages, Media Messages, Stickers, and more. - -`MessageList` is primarily a list of the base component [MessageBubble](/ui-kit/ios/message-bubble-styling). The MessageBubble Component is utilized to create different types of chat bubbles depending on the message type. +The `CometChatMessageList` component displays a scrollable list of messages in a conversation. It supports text messages, media messages, reactions, threads, and real-time updates for new messages, edits, and deletions. ---- + +```json +{ + "component": "CometChatMessageList", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays a scrollable list of messages in a conversation with real-time updates for new messages, edits, deletions, reactions, and typing indicators.", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onMessageClick", + "type": "(BaseMessage) -> Void" + }, + "props": { + "data": { + "messagesRequestBuilder": { + "type": "MessagesRequest.MessageRequestBuilder?", + "default": "nil", + "note": "Custom request builder for filtering messages" + }, + "reactionsRequestBuilder": { + "type": "ReactionsRequest.ReactionsRequestBuilder?", + "default": "nil", + "note": "Custom request builder for fetching reactions" + } + }, + "callbacks": { + "onThreadRepliesClick": "(BaseMessage, MessageTemplate) -> Void", + "onReactionClick": "(ReactionCount, BaseMessage) -> Void", + "onReactionListItemClick": "(MessageReaction, BaseMessage) -> Void", + "onError": "(CometChatException) -> Void", + "onEmpty": "() -> Void", + "onLoad": "([BaseMessage]) -> Void" + }, + "visibility": { + "hideAvatar": { "type": "Bool", "default": false }, + "hideReceipts": { "type": "Bool", "default": false }, + "hideDateSeparator": { "type": "Bool", "default": false }, + "hideHeaderView": { "type": "Bool", "default": false }, + "hideFooterView": { "type": "Bool", "default": false }, + "hideReactionOption": { "type": "Bool", "default": false }, + "hideReplyInThreadOption": { "type": "Bool", "default": false }, + "hideEditMessageOption": { "type": "Bool", "default": false }, + "hideDeleteMessageOption": { "type": "Bool", "default": false }, + "hideCopyMessageOption": { "type": "Bool", "default": false }, + "hideMessageInfoOption": { "type": "Bool", "default": false }, + "hideTranslateMessageOption": { "type": "Bool", "default": false }, + "hideMessagePrivatelyOption": { "type": "Bool", "default": false }, + "hideGroupActionMessages": { "type": "Bool", "default": false }, + "hideNewMessageIndicator": { "type": "Bool", "default": false }, + "hideEmptyView": { "type": "Bool", "default": false }, + "hideErrorView": { "type": "Bool", "default": false }, + "hideLoadingView": { "type": "Bool", "default": false } + }, + "sound": { + "disableSoundForMessages": { "type": "Bool", "default": false } + }, + "behavior": { + "scrollToBottomOnNewMessages": { "type": "Bool", "default": true }, + "startFromUnreadMessages": { "type": "Bool", "default": false }, + "showMarkAsUnreadOption": { "type": "Bool", "default": false }, + "messageAlignment": { "type": "MessageAlignment", "default": ".standard" } + }, + "viewSlots": { + "headerView": "() -> UIView", + "footerView": "() -> UIView", + "emptyStateView": "() -> UIView", + "errorStateView": "() -> UIView", + "loadingStateView": "() -> UIView", + "newMessageIndicatorView": "() -> UIView" + }, + "formatting": { + "datePattern": "(Int?) -> String", + "timePattern": "(Int) -> String", + "dateSeparatorPattern": "(Int?) -> String", + "textFormatters": "[CometChatTextFormatter]" + } + }, + "events": [], + "sdkListeners": [ + "onMessageReceived", + "onMessageEdited", + "onMessageDeleted", + "onTypingStarted", + "onTypingEnded", + "onMessageReactionAdded", + "onMessageReactionRemoved" + ], + "compositionExample": { + "description": "MessageList is typically used within CometChatMessages alongside MessageHeader and MessageComposer", + "components": ["CometChatMessageHeader", "CometChatMessageList", "CometChatMessageComposer"], + "flow": "User views messages → types in composer → sends message → MessageList updates" + }, + "types": { + "BaseMessage": { + "id": "Int", + "sender": "User?", + "receiver": "AppEntity?", + "sentAt": "Int", + "type": "String", + "category": "String" + }, + "MessageAlignment": { + "standard": "Outgoing messages on right, incoming on left", + "left": "All messages aligned to left" + } + } +} +``` + -## Usage +--- -### Integration +## Where It Fits -The following code snippet illustrates how you can directly incorporate the MessageList component: +`CometChatMessageList` is the core component for displaying messages in a chat. It's typically used within `CometChatMessages` alongside `CometChatMessageHeader` and `CometChatMessageComposer`. - - ```swift -// Set user for the message list -messageList.set(user: user) +import UIKit +import CometChatUIKitSwift +import CometChatSDK -// Set user with parent message for threaded conversations -messageList.set(user: user, parentMessage: textMessage) +class ChatViewController: UIViewController { + + private var messageList: CometChatMessageList! + + override func viewDidLoad() { + super.viewDidLoad() + setupMessageList() + } + + private func setupMessageList(for user: User) { + messageList = CometChatMessageList() + messageList.set(user: user) + + // Handle thread replies + messageList.set(onThreadRepliesClick: { [weak self] message, template in + self?.openThreadView(for: message) + }) + + // Handle reactions + messageList.set(onReactionClick: { [weak self] reactionCount, message in + self?.showReactionDetails(reactionCount, for: message) + }) + + addChild(messageList) + view.addSubview(messageList.view) + messageList.didMove(toParent: self) + } + + private func openThreadView(for message: BaseMessage) { + let threadMessages = CometChatMessages() + threadMessages.set(user: message.sender as? User) + threadMessages.set(parentMessage: message) + navigationController?.pushViewController(threadMessages, animated: true) + } + + private func showReactionDetails(_ reactionCount: ReactionCount, for message: BaseMessage) { + // Show reaction details + } +} ``` - - - -To retrieve messages for a specific entity, you must associate it with either a `User` or `Group` object. - + + + --- -### Actions - -[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -#### 1. onThreadRepliesClick - -`onThreadRepliesClick` is triggered when you click on the thread indicator of a message bubble. The `onThreadRepliesClick` action doesn't have a predefined behavior. You can override this action using the following code snippet: +## Minimal Render - - ```swift -let messageListView = CometChatMessageList() -messageListView.set(onThreadRepliesClick: { message, template in - // Handle thread replies click -}) -``` - - - ---- - -#### 2. onReactionClick - -`onReactionClick` is triggered when you click on a reaction on a message bubble. +import CometChatUIKitSwift +import CometChatSDK - - -```swift -let messageListView = CometChatMessageList() -messageListView.set(onReactionClick: { reactionCount, baseMessage in - // Handle reaction click -}) +let messageList = CometChatMessageList() +messageList.set(user: user) ``` - - + + + + --- -#### 3. onReactionListItemClick +## Filtering -`onReactionListItemClick` is triggered when you click on the list item of CometChatReactionList on a message bubble. +Use `MessagesRequest.MessageRequestBuilder` to filter which messages appear in the list. The builder pattern allows chaining multiple filter conditions. - - ```swift -let messageListView = CometChatMessageList() -messageListView.set(onReactionListItemClick: { messageReaction, baseMessage in - // Handle reaction list item click -}) -``` - - +import CometChatUIKitSwift +import CometChatSDK ---- +// Create a custom request builder +let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() + .set(uid: "user-id") + .set(limit: 30) + .set(types: ["text", "image", "video"]) -#### 4. set(onError:) +let messageList = CometChatMessageList() +messageList.set(user: user) +messageList.set(messagesRequestBuilder: messageRequestBuilder) +``` -This method proves helpful when you need to customize the action taken upon encountering an error in CometChatMessageList. +### Filter Recipes - - -```swift -cometChatGroupMembers.set(onError: { error in - // Handle error -}) -``` - - +| Recipe | Code | +|--------|------| +| Text messages only | `.set(types: ["text"])` | +| Media messages only | `.set(types: ["image", "video", "audio", "file"])` | +| Search by keyword | `.set(searchKeyword: "hello")` | +| Limit results | `.set(limit: 50)` | +| Messages after timestamp | `.set(timestamp: 1234567890)` | +| Hide deleted messages | `.hideDeletedMessages(true)` | +| Specific categories | `.set(categories: ["message", "custom"])` | --- -#### 5. set(onEmpty:) +## Actions and Events -The `set(onEmpty:)` method is triggered when the message list is empty in CometChatMessageList. +### Callback Props - - -```swift -cometChatMessageList.set(onEmpty: { - // Handle empty state -}) -``` - - +#### onThreadRepliesClick ---- +Fires when a user taps on the thread indicator of a message bubble. -#### 6. setOnLoad +```swift +import CometChatUIKitSwift +import CometChatSDK -The `set(onLoad:)` method is triggered when messages are successfully loaded in CometChatMessageList. +let messageList = CometChatMessageList() - - -```swift -cometChatMessageList.set(onLoad: { messages in - // Handle loaded messages +messageList.set(onThreadRepliesClick: { [weak self] message, template in + guard let self = self else { return } + + let threadMessages = CometChatMessages() + if let user = message.sender as? User { + threadMessages.set(user: user) + } + threadMessages.set(parentMessage: message) + self.navigationController?.pushViewController(threadMessages, animated: true) }) ``` - - - ---- - -### Filters -You can adjust the `MessagesRequestBuilder` in the MessageList Component to customize your message list. Numerous options are available to alter the builder to meet your specific needs. For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/ios/additional-message-filtering). +#### onReactionClick -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed: +Fires when a user taps on a reaction on a message bubble. - - ```swift -// Create message request builder with filters -let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() - .set(uid: "YOUR_UID") - .set(types: ["Text"]) - .set(searchKeyword: "sure") +import CometChatUIKitSwift +import CometChatSDK -// Apply to CometChatMessages -let cometChatMessages = CometChatMessages() -cometChatMessages.set(user: user) -cometChatMessages.set(messagesRequestBuilder: messageRequestBuilder) +let messageList = CometChatMessageList() + +messageList.set(onReactionClick: { [weak self] reactionCount, message in + guard let self = self else { return } + print("Reaction \(reactionCount.reaction) tapped on message \(message.id)") +}) ``` - - - -The following parameters in messageRequestBuilder will always be altered inside the message list: -1. UID -2. GUID -3. types -4. categories - +#### onReactionListItemClick - -Ensure to include the `uid` and `name` of the User in the implementation. - +Fires when a user taps on a specific reaction in the reaction list. ---- +```swift +import CometChatUIKitSwift +import CometChatSDK -### Events +let messageList = CometChatMessageList() -[Events](/ui-kit/ios/components-overview#events) are emitted by a Component. By using events you can extend existing functionality. Being global events, they can be applied in multiple locations and are capable of being added or removed. +messageList.set(onReactionListItemClick: { [weak self] messageReaction, message in + guard let self = self else { return } + print("User \(messageReaction.reactedBy?.name ?? "") reacted with \(messageReaction.reaction)") +}) +``` -The MessageList Component does not emit any events of its own. +#### onError ---- +Fires when an error occurs while loading messages. -## Customization +```swift +import CometChatUIKitSwift -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +let messageList = CometChatMessageList() -### Style +messageList.set(onError: { error in + print("Error loading messages: \(error.errorDescription)") +}) +``` -Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. +#### onEmpty -#### 1. MessageList Style +Fires when the message list is empty. -To customize the appearance, you can assign a `MessageListStyle` object to the `MessageList` component. +```swift +import CometChatUIKitSwift -**Global level styling** +let messageList = CometChatMessageList() - - -```swift -CometChatMessageList.style.backgroundColor = UIColor(hex: "#FBAA75") -CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor(hex: "#F76808") +messageList.set(onEmpty: { + print("No messages found") +}) ``` - - -**Instance level styling** +#### onLoad + +Fires when messages are successfully loaded. - - ```swift -// Create custom message list style -let messageListStyle = MessageListStyle() -messageListStyle.backgroundColor = UIColor(hex: "#FBAA75") +import CometChatUIKitSwift +import CometChatSDK -// Apply to instance let messageList = CometChatMessageList() -messageList.messageBubbleStyle.outgoing.backgroundColor = UIColor(hex: "#F76808") -messageList.style = messageListStyle + +messageList.set(onLoad: { messages in + print("Loaded \(messages.count) messages") +}) ``` - - - - - +### Actions Reference + +| Method | Description | Example | +|--------|-------------|---------| +| `set(onThreadRepliesClick:)` | Triggered when thread indicator is tapped | Open thread view | +| `set(onReactionClick:)` | Triggered when a reaction is tapped | Show reaction details | +| `set(onReactionListItemClick:)` | Triggered when reaction list item is tapped | Show who reacted | +| `set(onError:)` | Triggered when an error occurs | Show error alert | +| `set(onEmpty:)` | Triggered when list is empty | Show empty state | +| `set(onLoad:)` | Triggered when messages load | Analytics tracking | +| `scrollToBottom(isAnimated:)` | Scrolls to the bottom of the list | Navigate to latest | +| `goToMessage(withId:)` | Scrolls to a specific message | Jump to message | + +### SDK Events (Real-Time, Automatic) + +| SDK Listener | Internal behavior | +|--------------|-------------------| +| `onMessageReceived` | Adds new message to the list | +| `onMessageEdited` | Updates the edited message in place | +| `onMessageDeleted` | Removes or marks message as deleted | +| `onTypingStarted` | Shows typing indicator | +| `onTypingEnded` | Hides typing indicator | +| `onMessageReactionAdded` | Updates reaction count on message | +| `onMessageReactionRemoved` | Updates reaction count on message | +--- -List of properties exposed by MessageListStyle: - -| Property | Description | Code | -|----------|-------------|------| -| **Background Color** | Background color with dynamic support for light and dark mode | `CometChatMessageList.style.backgroundColor = UIColor.dynamicColor(lightModeColor: ..., darkModeColor: ...)` | -| **Border Width** | Border width for the component | `CometChatMessageList.style.borderWidth = 0` | -| **Border Color** | Border color for the component | `CometChatMessageList.style.borderColor = .clear` | -| **Corner Radius** | Corner radius for the component | `CometChatMessageList.style.cornerRadius = CometChatCornerStyle?` | -| **Shimmer Gradient Color 1** | First color of the shimmer gradient | `CometChatMessageList.style.shimmerGradientColor1 = CometChatTheme.backgroundColor04` | -| **Shimmer Gradient Color 2** | Second color of the shimmer gradient | `CometChatMessageList.style.shimmerGradientColor2 = CometChatTheme.backgroundColor03` | -| **Empty State Title Color** | Text color for the title in the empty state | `CometChatMessageList.style.emptyStateTitleColor = CometChatTheme.textColorPrimary` | -| **Empty State Title Font** | Font for the title in the empty state | `CometChatMessageList.style.emptyStateTitleFont = CometChatTypography.Heading3.bold` | -| **Empty State Subtitle Color** | Text color for the subtitle in the empty state | `CometChatMessageList.style.emptyStateSubtitleColor = CometChatTheme.textColorSecondary` | -| **Empty State Subtitle Font** | Font for the subtitle in the empty state | `CometChatMessageList.style.emptyStateSubtitleFont = CometChatTypography.Body.regular` | -| **Error State Title Color** | Text color for the title in the error state | `CometChatMessageList.style.errorStateTitleColor = CometChatTheme.textColorPrimary` | -| **Error State Title Font** | Font for the title in the error state | `CometChatMessageList.style.errorStateTitleFont = CometChatTypography.Heading3.bold` | -| **Error State Subtitle Color** | Text color for the subtitle in the error state | `CometChatMessageList.style.errorStateSubtitleColor = CometChatTheme.textColorSecondary` | -| **Error State Subtitle Font** | Font for the subtitle in the error state | `CometChatMessageList.style.errorStateSubtitleFont = CometChatTypography.Body.regular` | -| **Threaded Message Image** | Icon image for threaded messages | `CometChatMessageList.style.threadedMessageImage = UIImage(systemName: "arrow.turn.down.right")` | -| **Error Image** | Icon image for error state | `CometChatMessageList.style.errorImage = UIImage(named: "error-icon")` | -| **Empty Image** | Icon image for empty state | `CometChatMessageList.style.emptyImage = UIImage(named: "empty-icon")` | -| **New Message Indicator Image** | Icon image for new message indicator | `CometChatMessageList.style.newMessageIndicatorImage = UIImage?` | -| **New Message Indicator Text Color** | Text color for unread messages indicator | `CometChatMessageList.style.newMessageIndicatorTextColor = UIColor?` | -| **New Message Indicator Text Font** | Text font for unread messages indicator | `CometChatMessageList.style.newMessageIndicatorTextFont = UIFont?` | -| **New Message Indicator Background Color** | Background color for unread messages indicator | `CometChatMessageList.style.newMessageIndicatorBackgroundColor = UIColor?` | +## Custom View Slots ---- +| Slot | Signature | Replaces | +|------|-----------|----------| +| `headerView` | `() -> UIView` | Header above message list | +| `footerView` | `() -> UIView` | Footer below message list | +| `emptyStateView` | `() -> UIView` | Empty state display | +| `errorStateView` | `() -> UIView` | Error state display | +| `loadingStateView` | `() -> UIView` | Loading state display | +| `newMessageIndicatorView` | `() -> UIView` | New message indicator | -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets: - -| Property | Description | Code | -|----------|-------------|------| -| hideAvatar | Hides the avatar of the sender | `hideAvatar = true` | -| hideGroupActionMessages | Hides group action messages (like join/leave notifications) | `hideGroupActionMessages = true` | -| hideReplyInThreadOption | Hides the reply in thread option | `hideReplyInThreadOption = true` | -| hideTranslateMessageOption | Hides the message translation option | `hideTranslateMessageOption = true` | -| hideEditMessageOption | Hides the edit message option | `hideEditMessageOption = true` | -| hideDeleteMessageOption | Hides the delete message option | `hideDeleteMessageOption = true` | -| hideReactionOption | Hides the reaction option on messages | `hideReactionOption = true` | -| hideMessagePrivatelyOption | Hides the option to message privately | `hideMessagePrivatelyOption = true` | -| hideCopyMessageOption | Hides the option to copy a message | `hideCopyMessageOption = true` | -| hideMessageInfoOption | Hides the message info option | `hideMessageInfoOption = true` | -| hideHeaderView | Hides the header view of the message list | `hideHeaderView = true` | -| hideFooterView | Hides the footer view of the message list | `hideFooterView = true` | -| hideDateSeparator | Hides the date separator between messages | `hideDateSeparator = true` | -| scrollToBottomOnNewMessages | Scrolls to the bottom when new messages arrive | `scrollToBottomOnNewMessages = true` | -| hideReceipts | Hides the message read receipts (ticks) | `hideReceipts = true` | -| disableSoundForMessages | Disables the sound when a new message arrives | `disableSoundForMessages = true` | -| hideEmptyView | Hides the empty state view when no messages are available | `hideEmptyView = true` | -| hideErrorView | Hides the error view when an error occurs | `hideErrorView = true` | -| hideLoadingView | Hides the loading view when fetching messages | `hideLoadingView = true` | -| hideNewMessageIndicator | Hides the "new message" indicator | `hideNewMessageIndicator = true` | -| scrollToBottom(isAnimated:) | Scrolls to the bottom of the message list | `scrollToBottom(isAnimated: true)` | -| set(messageAlignment:) | Sets the alignment of messages in the list | `set(messageAlignment: .left)` | -| set(smartRepliesKeywords:) | Sets keywords for smart replies | `set(smartRepliesKeywords: ["Hi", "Bye"])` | -| set(smartRepliesDelayDuration:) | Sets the delay duration for smart replies | `set(smartRepliesDelayDuration: 2)` | -| set(user:parentMessage:) | Sets the user and an optional parent message | `set(user: user, parentMessage: message)` | -| set(group:parentMessage:) | Sets the group and an optional parent message | `set(group: group, parentMessage: message)` | -| set(messagesRequestBuilder:) | Sets the message request builder | `set(messagesRequestBuilder: builder)` | -| set(reactionsRequestBuilder:) | Sets the reactions request builder | `set(reactionsRequestBuilder: builder)` | -| set(parentMessageId:) | Sets the parent message ID | `set(parentMessageId: 12345)` | -| hideModerationView | Hides the moderation view in the AI assistant chat | `hideModerationView = true` | -| hideThreadView | Hides the thread view in the AI assistant chat | `hideThreadView = true` | -| set(suggestedMessages:) | List of predefined replies shown in the AI assistant | `suggestedMessages = ["Hello", "Hi"]` | -| hideSuggestedMessages | Hides the suggested message replies | `hideSuggestedMessages = true` | -| set(emptyChatGreetingView:) | Custom view displayed when the AI assistant chat is empty | `emptyChatGreetingView = { /* custom view */ }` | -| set(streamingSpeed:) | Sets the speed of streaming for AI assistant messages | `streamingSpeed = 50` | -| goToMessage(withId:) | Scrolls the message list to a specific message based on the provided message ID | `goToMessage(messageId: Int)` | -| startFromUnreadMessages | Starts the message list from the first unread message | `startFromUnreadMessages = true` | -| showMarkAsUnreadOption | Sets the visibility of the "Mark as unread" option in the message actions menu | `showMarkAsUnreadOption = true` | +### headerView ---- +Add a custom header above the message list. -### Advanced +```swift +import UIKit +import CometChatUIKitSwift + +let messageList = CometChatMessageList() -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. +let headerView = UIView() +headerView.backgroundColor = UIColor.systemGray6 -#### Date Time Formatter +let label = UILabel() +label.text = "Pinned Messages" +label.font = UIFont.systemFont(ofSize: 14, weight: .medium) +label.textColor = UIColor.secondaryLabel +headerView.addSubview(label) -The `CometChatMessageList` component supports full customization of how date and time are displayed using the [CometChatDateTimeFormatter](/ui-kit/ios/localize#datetimeformatter). +messageList.set(headerView: headerView) +``` -This enables developers to localize, format, or personalize the date and time strings shown next to each message such as "Today", "Yesterday", "12:45 PM", etc. +### footerView -**1. Component-Level (Global)** +Add a custom footer below the message list. - - ```swift -// Customize time format -CometChatMessageList.dateTimeFormatter.time = { timestamp in - return "at " + DateFormatter.localizedString(from: Date(timeIntervalSince1970: TimeInterval(timestamp)), dateStyle: .none, timeStyle: .short) -} +import UIKit +import CometChatUIKitSwift -// Customize today format -CometChatMessageList.dateTimeFormatter.today = { timestamp in - return "Today • \(formattedTime(from: timestamp))" -} +let messageList = CometChatMessageList() -// Customize older dates format -CometChatMessageList.dateTimeFormatter.otherDay = { timestamp in - let formatter = DateFormatter() - formatter.dateFormat = "dd MMM yyyy" - return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) -} -``` - - +let footerView = UIView() +footerView.backgroundColor = UIColor.systemGray6 -**2. Instance-Level (Local)** +let quickRepliesStack = UIStackView() +quickRepliesStack.axis = .horizontal +quickRepliesStack.spacing = 8 - - -```swift -let messageList = CometChatMessageList() -messageList.dateTimeFormatter.yesterday = { timestamp in - return "Yesterday at " + formattedTime(from: timestamp) +let replies = ["👍", "Thanks!", "Got it"] +for reply in replies { + let button = UIButton(type: .system) + button.setTitle(reply, for: .normal) + button.backgroundColor = UIColor.systemBackground + button.layer.cornerRadius = 16 + quickRepliesStack.addArrangedSubview(button) } + +footerView.addSubview(quickRepliesStack) +messageList.set(footerView: footerView) ``` - - -##### Available Closures +### emptyStateView -| Property | Description | Code | -|----------|-------------|------| -| time | Called to format a timestamp as a standard time (e.g., "12:30 PM") | `CometChatMessageList.dateTimeFormatter.time = { ... }` | -| today | Called when rendering messages sent today | `CometChatMessageList.dateTimeFormatter.today = { ... }` | -| yesterday | Called for yesterday's messages | `CometChatMessageList.dateTimeFormatter.yesterday = { ... }` | -| lastweek | Called for messages within the last week | `CometChatMessageList.dateTimeFormatter.lastweek = { ... }` | -| otherDay | Called for dates older than last week | `CometChatMessageList.dateTimeFormatter.otherDay = { ... }` | -| minute | Called when referring to "a minute ago" | `CometChatMessageList.dateTimeFormatter.minute = { ... }` | -| minutes | Called for "x minutes ago" | `CometChatMessageList.dateTimeFormatter.minutes = { ... }` | -| hour | Called for "an hour ago" | `CometChatMessageList.dateTimeFormatter.hour = { ... }` | -| hours | Called for "x hours ago" | `CometChatMessageList.dateTimeFormatter.hours = { ... }` | +Customize the view shown when there are no messages. -Each closure receives a timestamp (Int, representing UNIX time) and must return a String representing the formatted time. +```swift +import UIKit +import CometChatUIKitSwift ---- +let messageList = CometChatMessageList() -#### SetHeaderView +let emptyView = UIView() +let imageView = UIImageView(image: UIImage(systemName: "bubble.left.and.bubble.right")) +imageView.tintColor = UIColor.tertiaryLabel -You can set a custom headerView to the Message List component using the following method: +let label = UILabel() +label.text = "No messages yet. Start the conversation!" +label.textColor = UIColor.secondaryLabel +label.textAlignment = .center - - -```swift -let messageListView = CometChatMessageList() -messageListView.set(headerView: CustomHeaderView) +emptyView.addSubview(imageView) +emptyView.addSubview(label) + +messageList.set(emptyView: emptyView) ``` - - - - - +### loadingStateView -Following is the code of CustomHeaderView - UIView Class: +Customize the loading indicator. - - ```swift import UIKit +import CometChatUIKitSwift -class CustomHeaderView: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { - - private var collectionData: [CollectionItem] = [ - CollectionItem(title: "Notes", icon: UIImage(systemName: "doc.text.fill")), - CollectionItem(title: "Pinned Messages", icon: UIImage(systemName: "bookmark.fill")), - CollectionItem(title: "Saved Links", icon: UIImage(systemName: "link")) - ] - - private lazy var collectionView: UICollectionView = { - let layout = UICollectionViewFlowLayout() - layout.scrollDirection = .horizontal - layout.minimumInteritemSpacing = 10 - layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) - - let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) - collectionView.register(CustomHeaderViewCell.self, forCellWithReuseIdentifier: CustomHeaderViewCell.identifier) - collectionView.backgroundColor = .clear - collectionView.showsHorizontalScrollIndicator = false - collectionView.delegate = self - collectionView.dataSource = self - collectionView.tag = 1 - return collectionView - }() - - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = UIColor(white: 0.95, alpha: 1) - setupUI() - } - - private func setupUI() { - view.addSubview(collectionView) - - collectionView.translatesAutoresizingMaskIntoConstraints = false - - NSLayoutConstraint.activate([ - collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10), - collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), - collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 10) - ]) - } - - // MARK: - UICollectionView DataSource & Delegate - - func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - return collectionData.count - } - - func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomHeaderViewCell.identifier, for: indexPath) as? CustomHeaderViewCell else { - return UICollectionViewCell() - } - - cell.configure(with: collectionData[indexPath.row]) - return cell - } - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: 150, height: 40) - } -} +let messageList = CometChatMessageList() -struct CollectionItem { - let title: String - let icon: UIImage? -} +let loadingView = UIActivityIndicatorView(style: .large) +loadingView.color = UIColor.systemBlue +loadingView.startAnimating() -class CustomHeaderViewCell: UICollectionViewCell { - - static let identifier = "CustomCollectionViewCell" - - private let iconImageView: UIImageView = { - let imageView = UIImageView() - imageView.contentMode = .scaleAspectFit - imageView.translatesAutoresizingMaskIntoConstraints = false - return imageView - }() - - private let titleLabel: UILabel = { - let label = UILabel() - label.font = UIFont.systemFont(ofSize: 14, weight: .medium) - label.textColor = UIColor.purple - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() - - override init(frame: CGRect) { - super.init(frame: frame) - setupUI() - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setupUI() { - backgroundColor = UIColor(white: 0.95, alpha: 1) - layer.cornerRadius = 18 - clipsToBounds = true - - addSubview(iconImageView) - addSubview(titleLabel) - - NSLayoutConstraint.activate([ - iconImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), - iconImageView.centerYAnchor.constraint(equalTo: centerYAnchor), - iconImageView.widthAnchor.constraint(equalToConstant: 20), - iconImageView.heightAnchor.constraint(equalToConstant: 20), - - titleLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 5), - titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), - titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor) - ]) - } - - func configure(with model: CollectionItem) { - iconImageView.image = model.icon - titleLabel.text = model.title - } -} +messageList.set(loadingView: loadingView) ``` - - +### errorStateView ---- +Customize the error state view. -#### SetFooterView +```swift +import UIKit +import CometChatUIKitSwift -You can set a custom footerView to the Message List component using the following method: +let messageList = CometChatMessageList() - - -```swift -let messageListView = CometChatMessageList(frame: .null) -messageListView.set(footerView: CustomFooterView) +let errorLabel = UILabel() +errorLabel.text = "Something went wrong!" +errorLabel.textColor = .red +messageList.set(errorView: errorLabel) ``` - - - - - +### newMessageIndicatorView -Following is the code of CustomFooterView UIView Class: +Set a custom view for the unread message indicator. - - ```swift import UIKit +import CometChatUIKitSwift -class CustomFooterView: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { - - private var collectionData: [CollectionItem] = [ - CollectionItem(title: "Ice Breakers", icon: UIImage(systemName: "sun.max.fill")), - CollectionItem(title: "+1-212-456-7890", icon: UIImage(systemName: "phone.fill")), - CollectionItem(title: "+ Instagram", icon: UIImage(systemName: "camera.fill")) - ] - - private lazy var collectionView: UICollectionView = { - let layout = UICollectionViewFlowLayout() - layout.scrollDirection = .horizontal - layout.minimumInteritemSpacing = 10 - layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) - - let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) - collectionView.register(CustomFooterViewCell.self, forCellWithReuseIdentifier: CustomFooterViewCell.identifier) - collectionView.backgroundColor = .clear - collectionView.showsHorizontalScrollIndicator = false - collectionView.delegate = self - collectionView.dataSource = self - collectionView.tag = 1 - return collectionView - }() - - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = UIColor(white: 0.95, alpha: 1) - setupUI() - } - - private func setupUI() { - view.addSubview(collectionView) - - collectionView.translatesAutoresizingMaskIntoConstraints = false - - NSLayoutConstraint.activate([ - collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10), - collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), - collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), - collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 10) - ]) - } - - // MARK: - UICollectionView DataSource & Delegate - - func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { - return collectionData.count - } - - func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { - guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomFooterViewCell.identifier, for: indexPath) as? CustomFooterViewCell else { - return UICollectionViewCell() - } - - cell.configure(with: collectionData[indexPath.row]) - return cell - } - - func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { - return CGSize(width: 150, height: 40) - } -} +let messageList = CometChatMessageList() -struct CollectionItem { - let title: String - let icon: UIImage? -} +let newMessageIndicatorView = NewUnreadMessageIndicator() +messageList.set(newMessageIndicatorView: newMessageIndicatorView) -class CustomFooterViewCell: UICollectionViewCell { - - static let identifier = "CustomCollectionViewCell" - - private let iconImageView: UIImageView = { - let imageView = UIImageView() - imageView.contentMode = .scaleAspectFit - imageView.translatesAutoresizingMaskIntoConstraints = false - return imageView - }() +class NewUnreadMessageIndicator: UIView { - private let titleLabel: UILabel = { + private let label: UILabel = { let label = UILabel() + label.text = "New Messages ↓" + label.textColor = .white label.font = UIFont.systemFont(ofSize: 14, weight: .medium) - label.textColor = UIColor.purple - label.translatesAutoresizingMaskIntoConstraints = false + label.textAlignment = .center return label }() override init(frame: CGRect) { super.init(frame: frame) - setupUI() - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setupUI() { - backgroundColor = UIColor(white: 0.95, alpha: 1) - layer.cornerRadius = 18 - clipsToBounds = true - - addSubview(iconImageView) - addSubview(titleLabel) + backgroundColor = UIColor.systemBlue + layer.cornerRadius = 16 + addSubview(label) + label.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ - iconImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), - iconImageView.centerYAnchor.constraint(equalTo: centerYAnchor), - iconImageView.widthAnchor.constraint(equalToConstant: 20), - iconImageView.heightAnchor.constraint(equalToConstant: 20), - - titleLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 5), - titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), - titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor) + label.centerXAnchor.constraint(equalTo: centerXAnchor), + label.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } - func configure(with model: CollectionItem) { - iconImageView.image = model.icon - titleLabel.text = model.title + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") } } ``` - - --- -#### SetDateSeparatorPattern +## Text Formatters -You can modify the date pattern of the message list date separator to your requirement using `setDateSeparatorPattern()`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. +Customize how text is displayed in messages using text formatters. - - ```swift -let messageListView = CometChatMessageList() - .set(user: user) - -messageListView.set(dateSeparatorPattern: { timestamp in - guard let timestamp = timestamp else { - return "" - } - let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) - let formatter = DateFormatter() - formatter.dateFormat = "hh:mm MM/yyyy" - return formatter.string(from: date) -}) -``` - - - - -Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - - ---- - -#### SetDatePattern - -You can modify the date pattern to your requirement using `.set(datePattern:)`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - - - -```swift -let messageListView = CometChatMessageList() -messageListView.set(datePattern: { timestamp in - guard let timestamp = timestamp else { - return "" - } - let date = Date(timeIntervalSince1970: TimeInterval(timestamp/1000)) - let formatter = DateFormatter() - formatter.dateFormat = "dd-MM-yyyy" - return formatter.string(from: date) -}) -``` - - - ---- - -#### SetTimePattern - -You can modify the date pattern to your requirement using `.set(timePattern:)`. This method accepts a function with a return type String. Inside the function, you can create your own pattern and return it as a String. - - - -```swift -let messageListView = CometChatMessageList() -messageListView.set(timePattern: { timestamp in - let time = Date(timeIntervalSince1970: TimeInterval(timestamp)) - let formatter = DateFormatter() - formatter.dateFormat = "HH:mm" - return formatter.string(from: time) -}) -``` - - - ---- - -#### SetTextFormatters - -This functionality dynamically assigns a list of text formatters. If a custom list is provided, it uses that list. Otherwise, it gracefully falls back to the default text formatters retrieved from the data source for seamless integration. - -This code customizes a CometChat text formatter to identify and style the word "sure", with handling options for interactions like string search, scrolling, and item clicks. The custom formatter is then applied to CometChat messages: +import CometChatUIKitSwift +import CometChatSDK - - -```swift let myCustomTextFormatter = MyCustomTextFormatter(trackingCharacter: "#") let cometChatMessages = CometChatMessages() .set(user: user) .set(textFormatter: [myCustomTextFormatter]) ``` - - -**Demonstration:** +You can create a custom text formatter: - - ```swift import Foundation import CometChatSDK @@ -827,108 +591,446 @@ class MyCustomTextFormatter: CometChatTextFormatter { } } ``` - - --- -#### SetTemplate and AddTemplate +## Styling -[CometChatMessageTemplate](/ui-kit/ios/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/ios/message-template). +### Style Hierarchy ---- +1. Global styles (`CometChatMessageList.style`) apply to all instances +2. Instance styles override global for specific instances -#### SetLoadingView +### Global Level Styling -You can set a custom loading view using `.set(loadingView:)`. This method accepts a UIView to display while data is being fetched. - - - ```swift -let loadingIndicator = UIActivityIndicatorView(style: .medium) -loadingIndicator.startAnimating() -cometChatMessageList.set(loadingView: loadingIndicator) -``` - - +import UIKit +import CometChatUIKitSwift ---- +// Apply global styles that affect all CometChatMessageList instances +CometChatMessageList.style.backgroundColor = UIColor.systemBackground +CometChatMessageList.style.emptyStateTitleColor = UIColor.label +CometChatMessageList.style.emptyStateTitleFont = UIFont.systemFont(ofSize: 20, weight: .bold) +CometChatMessageList.style.emptyStateSubtitleColor = UIColor.secondaryLabel -#### SetErrorView +// Customize message bubble styles +CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor.systemBlue +CometChatMessageList.messageBubbleStyle.incoming.backgroundColor = UIColor.systemGray5 +``` -You can customize the error view using `.set(errorView:)`. This method accepts a UIView that appears when an error occurs. +### Instance Level Styling - - ```swift -let errorLabel = UILabel() -errorLabel.text = "Something went wrong!" -errorLabel.textColor = .red -cometChatMessageList.set(errorView: errorLabel) +import UIKit +import CometChatUIKitSwift + +// Create a custom style for a specific instance +let messageListStyle = MessageListStyle() +messageListStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +messageListStyle.borderWidth = 0 +messageListStyle.borderColor = .clear + +let messageList = CometChatMessageList() +messageList.style = messageListStyle ``` - - + + + + + +### Key Style Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color of the list | +| `borderWidth` | `CGFloat` | `0` | Border width for the component | +| `borderColor` | `UIColor` | `.clear` | Border color for the component | +| `cornerRadius` | `CometChatCornerStyle?` | `nil` | Corner radius for the component | +| `shimmerGradientColor1` | `UIColor` | `CometChatTheme.backgroundColor04` | First shimmer gradient color | +| `shimmerGradientColor2` | `UIColor` | `CometChatTheme.backgroundColor03` | Second shimmer gradient color | +| `emptyStateTitleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Empty state title color | +| `emptyStateTitleFont` | `UIFont` | `CometChatTypography.Heading3.bold` | Empty state title font | +| `emptyStateSubtitleColor` | `UIColor` | `CometChatTheme.textColorSecondary` | Empty state subtitle color | +| `emptyStateSubtitleFont` | `UIFont` | `CometChatTypography.Body.regular` | Empty state subtitle font | +| `errorStateTitleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Error state title color | +| `errorStateTitleFont` | `UIFont` | `CometChatTypography.Heading3.bold` | Error state title font | +| `newMessageIndicatorTextColor` | `UIColor?` | `nil` | New message indicator text color | +| `newMessageIndicatorBackgroundColor` | `UIColor?` | `nil` | New message indicator background | + +### Customization Matrix + +| What to change | Where | Property/API | Example | +|----------------|-------|--------------|---------| +| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | +| Empty state text | Style | `emptyStateTitleColor`, `emptyStateTitleFont` | Custom colors and fonts | +| Error state text | Style | `errorStateTitleColor`, `errorStateTitleFont` | Custom colors and fonts | +| Loading shimmer | Style | `shimmerGradientColor1`, `shimmerGradientColor2` | Custom gradient colors | +| Outgoing bubble | Style | `messageBubbleStyle.outgoing` | `UIColor.systemBlue` | +| Incoming bubble | Style | `messageBubbleStyle.incoming` | `UIColor.systemGray5` | +| Hide avatars | Property | `hideAvatar` | `messageList.hideAvatar = true` | +| Hide receipts | Property | `hideReceipts` | `messageList.hideReceipts = true` | +| Custom header | View Slot | `set(headerView:)` | See Custom View Slots section | --- -#### SetEmptyView +## Props -You can customize the empty state view using `.set(emptyView:)`. This method accepts a UIView that appears when no conversations are available. +All props are optional. Sorted alphabetically. - - -```swift -let emptyLabel = UILabel() -emptyLabel.text = "No conversations found" -emptyLabel.textColor = .gray -emptyLabel.textAlignment = .center -cometChatMessageList.set(emptyView: emptyLabel) -``` - - +### disableSoundForMessages + +Disables notification sounds for new messages. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideAvatar + +Hides the sender's avatar in message bubbles. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideCopyMessageOption + +Hides the copy message option in message actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideDateSeparator + +Hides the date separator between messages. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideDeleteMessageOption + +Hides the delete message option in message actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideEditMessageOption + +Hides the edit message option in message actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideEmptyView + +Hides the empty state view when no messages are available. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideErrorView + +Hides the error view when an error occurs. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideFooterView + +Hides the footer view of the message list. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideGroupActionMessages + +Hides group action messages (join/leave notifications). + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideHeaderView + +Hides the header view of the message list. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideLoadingView + +Hides the loading view when fetching messages. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideMessageInfoOption + +Hides the message info option in message actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideMessagePrivatelyOption + +Hides the option to message privately. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideNewMessageIndicator + +Hides the new message indicator. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideReactionOption + +Hides the reaction option on messages. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideReceipts + +Hides message read receipts (ticks). + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideReplyInThreadOption + +Hides the reply in thread option. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideTranslateMessageOption + +Hides the message translation option. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### messageAlignment + +Sets the alignment of messages in the list. + +| | | +|---|---| +| Type | `MessageAlignment` | +| Default | `.standard` | + +### messagesRequestBuilder + +Custom request builder for filtering messages. + +| | | +|---|---| +| Type | `MessagesRequest.MessageRequestBuilder?` | +| Default | `nil` | + +### reactionsRequestBuilder + +Custom request builder for fetching reactions. + +| | | +|---|---| +| Type | `ReactionsRequest.ReactionsRequestBuilder?` | +| Default | `nil` | + +### scrollToBottomOnNewMessages + +Automatically scrolls to bottom when new messages arrive. + +| | | +|---|---| +| Type | `Bool` | +| Default | `true` | + +### showMarkAsUnreadOption + +Shows the "Mark as unread" option in message actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### startFromUnreadMessages + +Starts the message list from the first unread message. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### textFormatters + +Array of text formatters for customizing message text display. + +| | | +|---|---| +| Type | `[CometChatTextFormatter]` | +| Default | `[]` | --- -#### SetNewMessageIndicatorView +## Events -Set a custom view for the unread message indicator. +The MessageList component does not emit any global UI events. It relies on SDK listeners for real-time updates. + +--- + +## Date Time Formatter + +Customize how timestamps appear in the message list using the `CometChatDateTimeFormatter`. + +### Global Level Formatting - - ```swift -let newMessageIndicatorView = NewUnreadMessageIndicator() -cometChatMessageList.set(newMessageIndicatorView: newMessageIndicatorView) +import CometChatUIKitSwift -class NewUnreadMessageIndicator: UIView { - // Your custom view implementation +// Customize time format +CometChatMessageList.dateTimeFormatter.time = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + return formatter.string(from: date) +} + +// Customize today format +CometChatMessageList.dateTimeFormatter.today = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "h:mm a" + return "Today • " + formatter.string(from: date) +} + +// Customize older dates format +CometChatMessageList.dateTimeFormatter.otherDay = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "dd MMM yyyy" + return formatter.string(from: date) } ``` - - ---- +### Instance Level Formatting - -To ensure that the `MessageList` is properly configured, passing the controller is mandatory. +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +messageList.set(datePattern: { timestamp in + guard let timestamp = timestamp else { return "" } + let date = Date(timeIntervalSince1970: TimeInterval(timestamp / 1000)) + let formatter = DateFormatter() + formatter.dateFormat = "dd-MM-yyyy" + return formatter.string(from: date) +}) + +messageList.set(timePattern: { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + return formatter.string(from: date) +}) +``` + +### Date Separator Pattern ```swift -let messageListView = CometChatMessageList() -messageListView.set(controller: UIViewController) // Passing the controller is required +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +messageList.set(dateSeparatorPattern: { timestamp in + guard let timestamp = timestamp else { return "" } + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + + if Calendar.current.isDateInToday(date) { + return "Today" + } else if Calendar.current.isDateInYesterday(date) { + return "Yesterday" + } else { + let formatter = DateFormatter() + formatter.dateFormat = "EEEE, MMM d" + return formatter.string(from: date) + } +}) ``` - ---- +### Available Formatters - -Ensure to pass and present `cometChatMessages`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. - +| Formatter | Purpose | Default Format | +|-----------|---------|----------------| +| `time` | Standard time display | `h:mm a` | +| `today` | Messages sent today | `Today` | +| `yesterday` | Messages from yesterday | `Yesterday` | +| `lastweek` | Messages within last week | Day name | +| `otherDay` | Older messages | `MMM d, yyyy` | +| `datePattern` | Custom date pattern | Configurable | +| `timePattern` | Custom time pattern | Configurable | +| `dateSeparatorPattern` | Date separator between messages | Configurable | --- -## Next Steps +## Troubleshooting -- [Message Composer](/ui-kit/ios/message-composer) — Customize the message input component -- [Message Header](/ui-kit/ios/message-header) — Display user/group details in the header -- [Message Template](/ui-kit/ios/message-template) — Create custom message bubble templates +| Issue | Solution | +|-------|----------| +| Messages not loading | Ensure user/group is set and SDK is initialized | +| Real-time updates not working | Check SDK connection status and listeners | +| Reactions not showing | Verify reactions are enabled in dashboard | +| Thread replies not working | Ensure `hideReplyInThreadOption` is not set to true | +| Custom views not appearing | Ensure custom view has proper constraints and non-zero frame | +| Scroll position issues | Check `scrollToBottomOnNewMessages` setting | --- + +## Related Components + +- [Messages](/ui-kit/ios/messages) - Parent component containing MessageList +- [Message Composer](/ui-kit/ios/message-composer) - Send messages in a conversation +- [Message Header](/ui-kit/ios/message-header) - Display user/group details +- [Message Template](/ui-kit/ios/message-template) - Create custom message bubble templates +- [Threaded Messages](/ui-kit/ios/threaded-messages) - Display threaded conversations diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index a23b4a856..9f4c12553 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -121,6 +121,42 @@ search.set(onEmpty: { Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria using RequestBuilders of the Chat SDK. +#### SearchScope + +The `SearchScope` enum defines what types of content to search: + +| Value | Description | +|-------|-------------| +| `.conversations` | Search in conversations | +| `.messages` | Search in messages | + +```swift +// Search only in messages +search.set(searchIn: [.messages]) + +// Search in both conversations and messages (default) +search.set(searchIn: [.conversations, .messages]) +``` + +#### SearchFilter + +The `SearchFilter` enum defines available filter options: + +| Value | Description | +|-------|-------------| +| `.unread` | Filter by unread items | +| `.groups` | Filter by group conversations | +| `.photos` | Filter by photo messages | +| `.videos` | Filter by video messages | +| `.links` | Filter by link messages | +| `.documents` | Filter by document messages | +| `.audio` | Filter by audio messages | + +```swift +// Set available filters with an initial selection +search.set(searchFilters: [.unread, .groups, .photos, .videos], initialFilter: .photos) +``` + #### 1. ConversationsRequestBuilder Set the `ConversationsRequestBuilder` in the Search Component to filter the search results. For more options, refer to [ConversationRequestBuilder](/sdk/ios/retrieve-conversations). @@ -213,12 +249,15 @@ These are small functional customizations that allow you to fine-tune the overal | group | Restrict search to a group | `search.group = group` | | hideUserStatus | Hide online/offline indicator | `search.hideUserStatus = true` | | hideGroupType | Hide group type icon | `search.hideGroupType = true` | -| searchFilters | Filters like "Messages", "Media" | `search.set(searchFilters: [.unread, .groups, .photos])` | -| initialSearchFilter | Default tab/filter | `search.initialSearchFilter = .messages` | -| searchIn | Restrict search: messages / conversations / both | `search.set(searchIn: [.messages])` | -| loadingStateView | Custom loader | `search.set(loadingStateView: spinner)` | -| emptyStateView | Custom empty result view | `search.set(emptyStateView: emptyView)` | -| errorStateView | Custom error UI | `search.set(errorStateView: errorView)` | +| searchFilters | Filters like "Unread", "Groups", "Photos", etc. | `search.set(searchFilters: [.unread, .groups, .photos])` | +| initialSearchFilter | Default filter to apply on load | `search.set(searchFilters: [...], initialFilter: .photos)` | +| searchIn (searchScopes) | Restrict search: messages / conversations / both | `search.set(searchIn: [.messages, .conversations])` | +| loadingView | Custom loader view | `search.set(loadingView: spinner)` | +| emptyView | Custom empty result view | `search.set(emptyView: emptyView)` | +| errorView | Custom error UI | `search.set(errorView: errorView)` | +| disableTyping | Disable typing indicators | `search.disableTyping = true` | +| disableSoundForMessages | Disable message sounds | `search.disableSoundForMessages = true` | +| customSoundForMessages | Custom sound URL for messages | `search.customSoundForMessages = URL(string: "...")` | --- @@ -228,13 +267,27 @@ For advanced-level customization, you can set custom views to the component. Thi #### Conversation View Customization -| Function | Description | -|-------------------------------|-------------------------------------------------------------| -| conversationListItemView | Assign a custom list item view to a conversation. | -| conversationLeadingView | Assign a custom leading view to a conversation. | -| conversationTitleView | Assign a custom title view to a conversation. | -| conversationSubtitleView | Assign a custom subtitle view to a conversation. | -| conversationTrailingView | Assign a custom trailing view to a conversation. | +| Function | Description | +|---------------------------------|-------------------------------------------------------------| +| listItemViewForConversation | Assign a custom list item view to a conversation. | +| leadingViewForConversation | Assign a custom leading view to a conversation. | +| titleViewForConversation | Assign a custom title view to a conversation. | +| subtitleViewForConversation | Assign a custom subtitle view to a conversation. | +| tailViewForConversation | Assign a custom trailing view to a conversation. | + + + +```swift +let searchVC = CometChatSearch() + +searchVC.set(listItemViewForConversation: { conversation in + let customView = UIView() + // Configure custom conversation view + return customView +}) +``` + + #### Message View Customization @@ -374,12 +427,73 @@ Available message item view functions for customization: | Function | Message Type | |-----------------------------|----------------------| +| listItemViewForMessage | Text Message | | listItemViewForImage | Image Message | | listItemViewForVideo | Video Message | | listItemViewForAudio | Audio Message | | listItemViewForDocument | Document Message | | listItemViewForLink | Link Message | + + +```swift +let searchVC = CometChatSearch() + +// Custom view for image messages +searchVC.set(listItemViewForImage: { mediaMessage in + let customView = UIView() + // Configure custom image message view + return customView +}) + +// Custom view for video messages +searchVC.set(listItemViewForVideo: { mediaMessage in + let customView = UIView() + // Configure custom video message view + return customView +}) + +// Custom view for audio messages +searchVC.set(listItemViewForAudio: { mediaMessage in + let customView = UIView() + // Configure custom audio message view + return customView +}) + +// Custom view for document messages +searchVC.set(listItemViewForDocument: { mediaMessage in + let customView = UIView() + // Configure custom document message view + return customView +}) + +// Custom view for link messages +searchVC.set(listItemViewForLink: { mediaMessage in + let customView = UIView() + // Configure custom link message view + return customView +}) +``` + + + +--- + +#### Mention Configuration + +Configure how @all mentions appear in search results using the `setMentionAllLabel` method. + + + +```swift +let searchVC = CometChatSearch() + +// Set a custom label for @all mentions +searchVC.setMentionAllLabel("all", "Everyone") +``` + + + --- #### DateTime Formatters diff --git a/ui-kit/ios/users.mdx b/ui-kit/ios/users.mdx index fa6b661cf..be6db7d30 100644 --- a/ui-kit/ios/users.mdx +++ b/ui-kit/ios/users.mdx @@ -1,560 +1,449 @@ --- title: "Users" -sidebarTitle: "Users" -description: "Display and manage a list of users with search functionality in CometChat UI Kit for iOS" +description: "Display and manage a list of users with search functionality" --- -## Overview - -The Users component is a [Component](/ui-kit/ios/components-overview#components) that displays an accessible list of all available users. It provides built-in search functionality, allowing you to locate any specific user quickly. For each user listed, the component displays the user's name by default, along with their avatar when available. It also includes a status indicator that visually shows whether a user is currently online or offline. +The `CometChatUsers` component displays a searchable list of all available users. It shows user names, avatars, and online/offline status indicators. Users can be filtered, searched, and selected for starting conversations. -The Users component is composed of the following base components: - -| Components | Description | -| ---------- | ----------------------------------------------------------------------------------------------------------------------- | -| ListBase | A reusable container component with a title, search box, customizable background, and a list view. | -| ListItem | A component that renders data from a User object on a tile with a title, subtitle, leading view, and trailing view. | + +```json +{ + "component": "CometChatUsers", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays a searchable list of all available users with avatars, names, and online/offline status indicators.", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onItemClick", + "type": "(User, IndexPath) -> Void" + }, + "props": { + "data": { + "usersRequestBuilder": { + "type": "UsersRequest.UsersRequestBuilder?", + "default": "nil", + "note": "Custom request builder for filtering users" + }, + "searchRequestBuilder": { + "type": "UsersRequest.UsersRequestBuilder?", + "default": "nil", + "note": "Custom request builder for search" + } + }, + "callbacks": { + "onItemClick": "(User, IndexPath) -> Void", + "onItemLongClick": "(User, IndexPath) -> Void", + "onBack": "() -> Void", + "onSelection": "([User]) -> Void", + "onError": "(CometChatException) -> Void", + "onEmpty": "() -> Void", + "onLoad": "([[User]]) -> Void" + }, + "visibility": { + "hideSearch": { "type": "Bool", "default": false }, + "hideNavigationBar": { "type": "Bool", "default": false }, + "hideBackButton": { "type": "Bool", "default": false }, + "hideUserStatus": { "type": "Bool", "default": false }, + "hideSectionHeader": { "type": "Bool", "default": false }, + "hideErrorView": { "type": "Bool", "default": false }, + "hideLoadingState": { "type": "Bool", "default": false } + }, + "selection": { + "selectionMode": { "type": "SelectionMode", "default": ".none" } + }, + "viewSlots": { + "listItemView": "(User) -> UIView", + "leadingView": "(User) -> UIView", + "titleView": "(User?) -> UIView", + "subtitleView": "(User?) -> UIView", + "trailingView": "(User?) -> UIView", + "emptyStateView": "() -> UIView", + "errorStateView": "() -> UIView", + "loadingStateView": "() -> UIView" + } + }, + "events": [ + { + "name": "ccUserBlocked", + "payload": "User", + "description": "Fires when a user is blocked" + }, + { + "name": "ccUserUnblocked", + "payload": "User", + "description": "Fires when a user is unblocked" + } + ], + "sdkListeners": [ + "onUserOnline", + "onUserOffline" + ], + "compositionExample": { + "description": "Users list for starting new conversations", + "components": ["CometChatUsers", "CometChatMessages"], + "flow": "User taps on a user → onItemClick fires → Navigate to CometChatMessages with selected user" + }, + "types": { + "User": { + "uid": "String", + "name": "String", + "avatar": "String?", + "status": "UserStatus", + "role": "String?" + }, + "UserStatus": { + "online": "User is currently online", + "offline": "User is currently offline" + } + } +} +``` + --- -## Usage +## Where It Fits -### Integration +`CometChatUsers` displays all available users for starting new conversations. It's typically used as a standalone screen or within a tab view controller. -Since `CometChatUsers` is a custom view controller, you can launch it directly through user actions such as button clicks or other interactions. You can also integrate it into a tab view controller. `CometChatUsers` offers several parameters and methods for UI customization. - - - ```swift -let cometChatUsers = CometChatUsers() -let naviVC = UINavigationController(rootViewController: cometChatUsers) -self.present(naviVC, animated: true) -``` - - - ---- +import UIKit +import CometChatUIKitSwift +import CometChatSDK -### Actions +class UsersViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + setupUsers() + } + + private func setupUsers() { + let usersController = CometChatUsers() + + // Handle user selection - start a conversation + usersController.set(onItemClick: { [weak self] user, indexPath in + self?.startConversation(with: user) + }) + + let navController = UINavigationController(rootViewController: usersController) + present(navController, animated: true) + } + + private func startConversation(with user: User) { + let messagesVC = CometChatMessages() + messagesVC.set(user: user) + navigationController?.pushViewController(messagesVC, animated: true) + } +} +``` -[Actions](/ui-kit/ios/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type to tailor the behavior of the component to fit your specific needs. + + + -#### 1. set(onItemClick:) +--- -The `set(onItemClick:)` method is triggered when you click on a ListItem in the Users component. This method is useful when you want to customize the click behavior. +## Minimal Render - - ```swift -cometChatUsers.set(onItemClick: { user, indexPath in - // Override on item click -}) +import CometChatUIKitSwift + +let users = CometChatUsers() +let navController = UINavigationController(rootViewController: users) +present(navController, animated: true) ``` - - + + + + --- -#### 2. set(onItemLongClick:) +## Filtering -The `set(onItemLongClick:)` method is triggered when you long press on a ListItem in the Users component. This method is useful when you want to add additional functionality on long press. +Use `UsersRequest.UsersRequestBuilder` to filter which users appear in the list. The builder pattern allows chaining multiple filter conditions. - - ```swift -cometChatUsers.set(onItemLongClick: { user, indexPath in - // Override on item long click -}) -``` - - +import CometChatUIKitSwift +import CometChatSDK ---- +// Create a custom request builder +let usersRequestBuilder = UsersRequest.UsersRequestBuilder(limit: 30) + .friendsOnly(true) -#### 3. set(onBack:) +let users = CometChatUsers(usersRequestBuilder: usersRequestBuilder) +``` -The `set(onBack:)` method is useful when you need to override the action triggered upon pressing the back button. +### Filter Recipes - - -```swift -cometChatUsers.set(onBack: { - // Override on back -}) -``` - - +| Recipe | Code | +|--------|------| +| Friends only | `.friendsOnly(true)` | +| Online users only | `.set(status: .online)` | +| Search by name | `.set(searchKeyword: "John")` | +| Filter by role | `.set(roles: ["admin", "moderator"])` | +| Filter by tags | `.set(tags: ["premium"])` | +| Hide blocked users | `.hideBlockedUsers(true)` | +| Limit results | `UsersRequestBuilder(limit: 20)` | +| Specific UIDs | `.set(UIDs: ["user1", "user2"])` | --- -#### 4. set(onSelection:) +## Actions and Events -The `set(onSelection:)` method is triggered only when the selection mode is set to multiple or single. It fires on every selection and returns the list of selected users. +### Callback Props - - -```swift -cometChatUsers.set(onSelection: { users in - // Handle action -}) -``` - - +#### onItemClick ---- +Fires when a user taps on a user in the list. Use this to start a conversation. -#### 5. set(onError:) +```swift +import CometChatUIKitSwift +import CometChatSDK -The `set(onError:)` method is useful when you need to customize the action taken upon encountering an error. +let users = CometChatUsers() - - -```swift -cometChatUsers.set(onError: { error in - // Override on error +users.set(onItemClick: { [weak self] user, indexPath in + guard let self = self else { return } + + let messagesVC = CometChatMessages() + messagesVC.set(user: user) + self.navigationController?.pushViewController(messagesVC, animated: true) }) ``` - - - ---- -#### 6. set(onEmpty:) +#### onItemLongClick -The `set(onEmpty:)` method is triggered when the users list is empty. +Fires when a user long-presses on a user. Use this to show additional options. - - ```swift -cometChatUsers.set(onEmpty: { - // Handle empty state +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +users.set(onItemLongClick: { [weak self] user, indexPath in + guard let self = self else { return } + + let alert = UIAlertController(title: user.name, message: nil, preferredStyle: .actionSheet) + + alert.addAction(UIAlertAction(title: "View Profile", style: .default) { _ in + // View profile + }) + + alert.addAction(UIAlertAction(title: "Block User", style: .destructive) { _ in + // Block user + }) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + self.present(alert, animated: true) }) ``` - - - ---- -#### 7. set(onLoad:) +#### onBack -The `set(onLoad:)` method is triggered when the user list is fully fetched and about to be displayed on the screen. It returns the list of users to be displayed. +Fires when the back button is pressed. - - ```swift -cometChatUsers.set(onLoad: { users in - // Handle loaded users +import CometChatUIKitSwift + +let users = CometChatUsers() + +users.set(onBack: { [weak self] in + self?.navigationController?.popViewController(animated: true) }) ``` - - ---- +#### onSelection -### Filters +Fires when users are selected in selection mode. -Filters allow you to customize the data displayed in a list within a component. You can filter the list based on your specific criteria for a more customized view. Filters can be applied using RequestBuilders from the Chat SDK. - -#### 1. UserRequestBuilder +```swift +import CometChatUIKitSwift +import CometChatSDK -The [UserRequestBuilder](/sdk/ios/retrieve-users) enables you to filter and customize the user list based on available parameters. This feature allows you to create more specific and targeted queries when fetching users. +let users = CometChatUsers() +users.selectionMode = .multiple -| Methods | Type | Description | -| -------------------- | -------------------- | -------------------------------------------------------------------------------------- | -| **setLimit** | int | Sets the number of users that can be fetched in a single request, suitable for pagination. | -| **setSearchKeyword** | String | Fetches users matching the passed string. | -| **hideBlockedUsers** | bool | Fetches all users who are not blocked by the logged-in user. | -| **friendsOnly** | bool | Fetches only users who are friends with the logged-in user. | -| **setRoles** | \[String] | Fetches users with the specified roles. | -| **setTags** | \[String] | Fetches users containing the specified tags. | -| **withTags** | bool | Fetches tag data along with the list of users. | -| **setStatus** | CometChat.UserStatus | Fetches users by their status (online or offline). | -| **setUIDs** | \[String] | Fetches users with the specified UIDs. | +users.set(onSelection: { [weak self] selectedUsers in + print("Selected \(selectedUsers.count) users") +}) +``` -**Example** +#### onError -In the example below, we apply a filter to the UserList to show only friends: +Fires when an error occurs while loading users. - - ```swift -let usersRequestBuilder = UsersRequest.UsersRequestBuilder(limit: 20).friendsOnly(true) - -let usersWithMessages = CometChatUsersWithMessages(usersRequestBuilder: usersRequestBuilder) -let naviVC = UINavigationController(rootViewController: usersWithMessages) -self.present(naviVC, animated: true) -``` - - +import CometChatUIKitSwift -#### 2. SearchRequestBuilder +let users = CometChatUsers() -The SearchRequestBuilder uses [UserRequestBuilder](/sdk/ios/retrieve-users) to filter and customize the search list based on available parameters. This feature allows you to maintain uniformity between the displayed UserList and the searched UserList. +users.set(onError: { error in + print("Error loading users: \(error.errorDescription)") +}) +``` -**Example** +#### onEmpty -In the example below, we apply a filter to the UserList based on a search keyword: +Fires when the user list is empty. - - ```swift -let usersRequestBuilder = UsersRequest.UsersRequestBuilder(limit: 20) - .set(searchKeyword: "**") +import CometChatUIKitSwift + +let users = CometChatUsers() -let usersWithMessages = CometChatUsers(usersRequestBuilder: usersRequestBuilder) -let naviVC = UINavigationController(rootViewController: usersWithMessages) -self.present(naviVC, animated: true) +users.set(onEmpty: { + print("No users found") +}) ``` - - ---- +#### onLoad + +Fires when users are successfully loaded. The callback receives a nested array where each inner array represents a section of users (grouped alphabetically). -### Events +```swift +import CometChatUIKitSwift +import CometChatSDK -[Events](/ui-kit/ios/components-overview#events) are emitted by a component. By using events, you can extend existing functionality. Being global events, they can be applied in multiple locations and can be added or removed as needed. +let users = CometChatUsers() -To handle events supported by Users, add the corresponding listeners using `CometChatUserEvents`: +users.set(onLoad: { userSections in + let totalUsers = userSections.flatMap { $0 }.count + print("Loaded \(totalUsers) users across \(userSections.count) sections") +}) +``` -| Events | Description | -| ----------------- | --------------------------------------------------------------------- | -| emitOnUserBlock | Triggered when the logged-in user blocks another user. | -| emitOnUserUnblock | Triggered when the logged-in user unblocks another user. | +### Actions Reference - - -```swift -// Pass the User object of the user who has been blocked by the logged-in user -CometChatUserEvents.emitOnUserBlock(user: User) +| Method | Description | Example | +|--------|-------------|---------| +| `set(onItemClick:)` | Triggered when a user is tapped | Start conversation | +| `set(onItemLongClick:)` | Triggered on long press | Show options menu | +| `set(onBack:)` | Triggered when back button is pressed | Custom navigation | +| `set(onSelection:)` | Triggered in selection mode | Multi-select users | +| `set(onError:)` | Triggered when an error occurs | Show error alert | +| `set(onEmpty:)` | Triggered when list is empty | Show empty state | +| `set(onLoad:)` | Triggered when users load | Analytics tracking | -// Pass the User object of the user who has been unblocked by the logged-in user -CometChatUserEvents.emitOnUserUnblock(user: User) -``` - - +### Global UI Events -**Usage** +| Event | Fires when | Payload | +|-------|------------|---------| +| `ccUserBlocked` | A user is blocked | `User` | +| `ccUserUnblocked` | A user is unblocked | `User` | ```swift -// View controller from your project where you want to listen to events -public class ViewController: UIViewController { +import CometChatUIKitSwift +import CometChatSDK - public override func viewDidLoad() { +class MyViewController: UIViewController, CometChatUserEventListener { + + override func viewDidLoad() { super.viewDidLoad() - // Subscribe to the listener for user module events - CometChatUserEvents.addListener("UNIQUE_ID", self as CometChatUserEventListener) + CometChatUserEvents.addListener("my-listener", self) } - - public override func viewWillDisappear(_ animated: Bool) { - // Unsubscribe from the listener - CometChatUserEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + CometChatUserEvents.removeListener("my-listener") } -} - -// Listener events from user module -extension ViewController: CometChatUserEventListener { - + func onUserBlock(user: User) { - // Handle user block event + print("User blocked: \(user.name ?? "")") } - + func onUserUnblock(user: User) { - // Handle user unblock event + print("User unblocked: \(user.name ?? "")") } } ``` ---- - -## Customization - -To fit your app's design requirements, you can customize the appearance of the Users component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style, you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. - -#### 1. Users Style - -You can set the `UsersStyle` to the Users component to customize the styling. - -**Global Level Styling** - - - -```swift -// Create custom avatar style -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) - -// Apply global styling -CometChatUsers.style.titleColor = UIColor(hex: "#F76808") -CometChatUsers.style.titleFont = UIFont(name: "Times-New-Roman", size: 34) -CometChatUsers.avatarStyle = customAvatarStyle -``` - - - -**Instance Level Styling** +### SDK Events (Real-Time, Automatic) - - -```swift -// Create custom avatar style -let customAvatarStyle = AvatarStyle() -customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") -customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) - -// Create custom user style -let userStyle = UsersStyle() -userStyle.titleColor = UIColor(hex: "#F76808") -userStyle.titleFont = UIFont(name: "Times-New-Roman", size: 34) - -// Apply instance-level styling -let customUser = CometChatUsers() -customUser.style = userStyle -customUser.avatarStyle = customAvatarStyle -``` - - - - - - - - -List of properties exposed by UsersStyle: - -| **Property** | **Description** | **Code** | -| ----------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| **List Item Selected Image** | Image shown when a list item is selected. | `CometChatUsers.style.listItemSelectedImage = UIImage()` | -| **List Item Deselected Image** | Image shown when a list item is deselected. | `CometChatUsers.style.listItemDeSelectedImage = UIImage()` | -| **Search Icon Tint Color** | Tint color for the search icon in the search bar. | `CometChatUsers.style.searchIconTintColor = UIColor()` | -| **Search Bar Style** | Style of the search bar (e.g., default, prominent). | `CometChatUsers.style.searchBarStyle = .default` | -| **Search Tint Color** | Tint color for the search bar elements. | `CometChatUsers.style.searchTintColor = UIColor?` | -| **Search Bar Tint Color** | Background color for the search bar (excluding text input). | `CometChatUsers.style.searchBarTintColor = UIColor?` | -| **Placeholder Text Color** | Color of the placeholder text in the search bar. | `CometChatUsers.style.searchBarPlaceholderTextColor = UIColor?` | -| **Placeholder Text Font** | Font of the placeholder text in the search bar. | `CometChatUsers.style.searchBarPlaceholderTextFont = UIFont?` | -| **Search Bar Text Color** | Color of the entered text in the search bar. | `CometChatUsers.style.searchBarTextColor = UIColor?` | -| **Search Bar Text Font** | Font of the entered text in the search bar. | `CometChatUsers.style.searchBarTextFont = UIFont?` | -| **Search Bar Background Color** | Background color of the search bar's text input area. | `CometChatUsers.style.searchBarBackgroundColor = UIColor?` | -| **Cancel Icon Tint Color** | Tint color for the cancel button in the search bar. | `CometChatUsers.style.searchBarCancelIconTintColor = UIColor?` | -| **Cross Icon Tint Color** | Tint color for the clear (cross) button in the search bar. | `CometChatUsers.style.searchBarCrossIconTintColor = UIColor?` | -| **Background Color** | Background color for the entire screen or view. | `.backgroundColor = CometChatTheme.backgroundColor01` | -| **Border Width** | Border width for the search bar or container. | `CometChatUsers.style.borderWidth = 0` | -| **Border Color** | Color of the border, default is clear. | `CometChatUsers.style.borderColor = .clear` | -| **Corner Radius** | Corner radius for search bar or other elements. | `CometChatUsers.style.cornerRadius = CometChatCornerStyle.init(cornerRadius: 0)` | -| **Title Text Color** | Text color for title elements within the list or navigation bar. | `CometChatUsers.style.titleColor = CometChatTheme.textColorPrimary` | -| **Title Font** | Font for title text. | `CometChatUsers.style.titleFont = CometChatTypography.Heading4.medium` | -| **Large Title Text Color** | Text color for large titles. | `CometChatUsers.style.largeTitleColor = CometChatTheme.textColorPrimary` | -| **Large Title Font** | Font for large titles. | `CometChatUsers.style.largeTitleFont = UIFont?` | -| **Navigation Bar Tint Color** | Tint color for the navigation bar background. | `CometChatUsers.style.navigationBarTintColor = CometChatTheme.backgroundColor01` | -| **Navigation Bar Items Tint Color** | Tint color for navigation bar items (buttons, icons). | `CometChatUsers.style.navigationBarItemsTintColor = CometChatTheme.iconColorHighlight` | -| **Error Title Font** | Font for the error title displayed in UI. | `CometChatUsers.style.errorTitleTextFont = CometChatTypography.Heading3.bold` | -| **Error Title Text Color** | Text color for the error title. | `CometChatUsers.style.errorTitleTextColor = CometChatTheme.textColorPrimary` | -| **Error Subtitle Font** | Font for the subtitle of error messages. | `CometChatUsers.style.errorSubTitleFont = CometChatTypography.Body.regular` | -| **Error Subtitle Text Color** | Text color for the subtitle of error messages. | `CometChatUsers.style.errorSubTitleTextColor = CometChatTheme.textColorSecondary` | -| **Retry Button Text Color** | Text color for the retry button in error states. | `CometChatUsers.style.retryButtonTextColor = CometChatTheme.buttonTextColor` | -| **Retry Button Text Font** | Font for the retry button text. | `CometChatUsers.style.retryButtonTextFont = CometChatTypography.Button.medium` | -| **Retry Button Background Color** | Background color for the retry button. | `CometChatUsers.style.retryButtonBackgroundColor = CometChatTheme.primaryColor` | -| **Retry Button Border Color** | Border color for the retry button. | `CometChatUsers.style.retryButtonBorderColor = .clear` | -| **Retry Button Border Width** | Border width for the retry button. | `CometChatUsers.style.retryButtonBorderWidth = 0` | -| **Retry Button Corner Radius** | Corner radius for the retry button. | `CometChatUsers.style.retryButtonCornerRadius = CometChatCornerStyle?` | -| **Empty State Title Font** | Font for the empty state title (when no users are present). | `CometChatUsers.style.emptyTitleTextFont = CometChatTypography.Heading3.bold` | -| **Empty State Title Color** | Text color for the empty state title. | `CometChatUsers.style.emptyTitleTextColor = CometChatTheme.textColorPrimary` | -| **Empty Subtitle Font** | Font for the subtitle in the empty state. | `CometChatUsers.style.emptySubTitleFont = CometChatTypography.Body.regular` | -| **Empty Subtitle Text Color** | Text color for the subtitle in the empty state. | `CometChatUsers.style.emptySubTitleTextColor = CometChatTheme.textColorSecondary` | -| **Table View Separator Color** | Color for the table view separator. | `CometChatUsers.style.tableViewSeparator = .clear` | -| **List Item Title Text Color** | Text color for list item titles. | `CometChatUsers.style.listItemTitleTextColor = CometChatTheme.textColorPrimary` | -| **List Item Title Font** | Font for list item titles. | `CometChatUsers.style.listItemTitleFont = CometChatTypography.Heading4.medium` | -| **List Item Subtitle Text Color** | Text color for list item subtitles. | `CometChatUsers.style.listItemSubTitleTextColor = CometChatTheme.textColorSecondary` | -| **List Item Subtitle Font** | Font for list item subtitles. | `CometChatUsers.style.listItemSubTitleFont = CometChatTypography.Body.regular` | -| **List Item Background** | Background color for individual list items. | `CometChatUsers.style.listItemBackground = .clear` | -| **List Item Border Width** | Border width for individual list items. | `CometChatUsers.style.listItemBorderWidth = 0` | -| **List Item Border Color** | Border color for individual list items. | `CometChatUsers.style.listItemBorderColor = CometChatTheme.borderColorLight` | -| **List Item Corner Radius** | Corner radius for list items. | `CometChatUsers.style.listItemCornerRadius = CometChatCornerStyle.init(cornerRadius: 0)` | -| **Selection Image Tint Color** | Tint color for selection indicator in list items. | `CometChatUsers.style.listItemSelectionImageTint = CometChatTheme.iconColorHighlight` | -| **Selected Background Color** | Background color for selected list items. | `CometChatUsers.style.listItemSelectedBackground = .clear` | -| **Deselected Image Tint Color** | Tint color for the deselected state image. | `CometChatUsers.style.listItemDeSelectedImageTint = CometChatTheme.borderColorDefault` | -| **Header Title Color** | Text color for section header titles in the list. | `CometChatUsers.style.headerTitleColor = CometChatTheme.textColorHighlight` | -| **Header Title Font** | Font for section header titles. | `CometChatUsers.style.headerTitleFont = CometChatTypography.Heading4.medium` | - ---- - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -| Method | Description | Code | -| -------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------- | -| set(userRequestBuilder:) | Sets a custom request builder for fetching users. | `.set(userRequestBuilder: UsersRequest.UsersRequestBuilder())` | -| set(searchRequestBuilder:) | Sets a custom request builder for searching users. | `.set(searchRequestBuilder: UsersRequest.UsersRequestBuilder())` | -| set(searchKeyword:) | Sets a search keyword for filtering users. | `.set(searchKeyword: "John")` | -| hideErrorView | Hides the error state view. | `hideErrorView = true` | -| hideNavigationBar | Hides or shows the navigation bar. | `hideNavigationBar = true` | -| hideSearch | Hides the search bar. | `hideSearch = true` | -| hideBackButton | Hides the back button. | `hideBackButton = true` | -| hideLoadingState | Hides the loading state indicator. | `hideLoadingState = true` | -| hideUserStatus | Hides the online/offline status of users. | `hideUserStatus = true` | -| hideSectionHeader | Hides the section header for table view indicating initials of users. | `hideSectionHeader = true` | - ---- - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. +| SDK Listener | Internal behavior | +|--------------|-------------------| +| `onUserOnline` | Updates status indicator to online | +| `onUserOffline` | Updates status indicator to offline | --- -#### set(options:) - -You can define custom options for each user using `set(options:)`. This method allows you to return an array of `CometChatUserOption` based on the user object. - - - -```swift -cometChatUsers.set(options: { user in - return [CometChatUserOption]() -}) -``` - - +## Custom View Slots ---- +| Slot | Signature | Replaces | +|------|-----------|----------| +| `listItemView` | `(User) -> UIView` | Entire user row | +| `leadingView` | `(User) -> UIView` | Avatar / left section | +| `titleView` | `(User?) -> UIView` | Name / title text | +| `subtitleView` | `(User?) -> UIView` | Status / subtitle text | +| `trailingView` | `(User?) -> UIView` | Right side content | +| `emptyStateView` | `() -> UIView` | Empty state display | +| `errorStateView` | `() -> UIView` | Error state display | +| `loadingStateView` | `() -> UIView` | Loading state display | -#### add(options:) +### listItemView -You can dynamically add options to users using `add(options:)`. This method lets you return additional `CometChatUserOption` elements. +Replace the entire user row with a custom design. - - ```swift -cometChatUsers.add(options: { user in - return [ArchiveOption()] -}) -``` - - - ---- - -#### set(listItemView:) +import UIKit +import CometChatUIKitSwift +import CometChatSDK -With this method, you can assign a custom ListItem view to the Users component. +let users = CometChatUsers() - - -```swift -let cometChatUser = CometChatUsers() -cometChatUser.set(listItemView: { user in - // Return your custom view +users.set(listItemView: { user in + let customView = UIView() + customView.backgroundColor = UIColor.systemBackground + + let avatar = CometChatAvatar(image: UIImage()) + avatar.setAvatar(avatarUrl: user.avatar, with: user.name ?? "") + + let nameLabel = UILabel() + nameLabel.text = user.name + nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .semibold) + + let statusLabel = UILabel() + statusLabel.text = user.status == .online ? "🟢 Online" : "⚫ Offline" + statusLabel.font = UIFont.systemFont(ofSize: 12) + statusLabel.textColor = UIColor.secondaryLabel + + customView.addSubview(avatar) + customView.addSubview(nameLabel) + customView.addSubview(statusLabel) + + return customView }) ``` - - - - - +### leadingView -You can create a custom `UIView` file named `CustomListItemView` for more complex or unique list items. Then integrate this custom view into the `set(listItemView:)` method within `CometChatUsers()`. +Customize the leading view (avatar area) of a user cell. ```swift import UIKit import CometChatUIKitSwift +import CometChatSDK -class CustomListItem: UIView { - - // MARK: - UI Components - private var profileImageView: CometChatAvatar = { - let imageView = CometChatAvatar(image: UIImage()) - imageView.translatesAutoresizingMaskIntoConstraints = false - return imageView - }() - - private var nameLabel: UILabel = { - let label = UILabel() - label.translatesAutoresizingMaskIntoConstraints = false - return label - }() +let users = CometChatUsers() - // MARK: - Initialization - override init(frame: CGRect) { - super.init(frame: frame) - setupUI() - } - - required init?(coder aDecoder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - // MARK: - Setup - private func setupUI() { - addSubview(profileImageView) - addSubview(nameLabel) - - NSLayoutConstraint.activate([ - // Profile image constraints - profileImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), - profileImageView.centerYAnchor.constraint(equalTo: centerYAnchor), - profileImageView.widthAnchor.constraint(equalToConstant: 40), - profileImageView.heightAnchor.constraint(equalToConstant: 40), - - // Name label constraints - nameLabel.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 8), - nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), - nameLabel.centerYAnchor.constraint(equalTo: centerYAnchor) - ]) - } - - // MARK: - Configuration - func set(user: User) { - var avatarURL: String? - if let group = conversation.conversationWith as? Group { - nameLabel.text = group.name - avatarURL = group.icon - } - - if let user = conversation.conversationWith as? User { - nameLabel.text = user.name - avatarURL = user.avatar - } - - self.profileImageView.setAvatar(avatarUrl: avatarURL, with: nameLabel.text) - } -} -``` - ---- - -#### set(leadingView:) - -You can modify the leading view of a user cell using `set(leadingView:)`. - - - -```swift -cometChatUsers.set(leadingView: { user in - let view = CustomLeadingView() +users.set(leadingView: { user in + let view = CustomLeadingView(image: UIImage(named: "avatar")) return view }) ``` - - -You can create a `CustomLeadingView` as a custom `UIView` to use in `set(leadingView:)`: +You can create a `CustomLeadingView` as a custom `UIView`: - - ```swift import UIKit @@ -620,34 +509,30 @@ class CustomLeadingView: UIView { } } ``` - - ---- +### titleView -#### set(titleView:) +Customize the title view of a user cell. -You can customize the title view of a user cell using `set(titleView:)`. - - - ```swift -cometChatUsers.set(titleView: { user in - let view = CustomTitleView() +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +users.set(titleView: { user in + let view = CustomTitleView(name: user.name ?? "", role: "Teacher") return view }) ``` - - -You can create a `CustomTitleView` as a custom `UIView` to use in `set(titleView:)`: +You can create a `CustomTitleView` as a custom `UIView`: - - ```swift import UIKit @@ -700,34 +585,72 @@ class CustomTitleView: UIView { } } ``` - - ---- +### subtitleView + +Customize the subtitle area below the user name. + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +users.set(subtitleView: { user in + let view = CustomSubtitleView(lastActiveDate: "2 hours ago") + return view +}) +``` + + + + + +You can create a `CustomSubtitleView` as a custom `UIView`: + +```swift +import UIKit + +class CustomSubtitleView: UILabel { + + init(lastActiveDate: String) { + super.init(frame: .zero) + self.text = "Last Active at: \(lastActiveDate)" + self.textColor = UIColor.gray + self.font = UIFont.systemFont(ofSize: 14) + self.numberOfLines = 1 + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} +``` -#### set(trailView:) +### trailingView -You can modify the trailing view of a user cell using `set(trailView:)`. +Customize the trailing view (right side) of a user cell. - - ```swift -cometChatUsers.set(trailView: { user in +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +users.set(trailView: { user in let view = CustomTrailView() return view }) ``` - - -You can create a `CustomTrailView` as a custom `UIView` to use in `set(trailView:)`: +You can create a `CustomTrailView` as a custom `UIView`: - - ```swift import UIKit @@ -788,103 +711,371 @@ class CustomTrailView: UIView { } } ``` - - + +### loadingStateView + +Customize the loading state view displayed while data is being fetched. + +```swift +import UIKit +import CometChatUIKitSwift + +let users = CometChatUsers() + +let loadingIndicator = UIActivityIndicatorView(style: .medium) +loadingIndicator.startAnimating() +users.set(loadingView: loadingIndicator) +``` + +### errorStateView + +Customize the error state view displayed when an error occurs. + +```swift +import UIKit +import CometChatUIKitSwift + +let users = CometChatUsers() + +let errorLabel = UILabel() +errorLabel.text = "Something went wrong!" +errorLabel.textColor = .red +users.set(errorView: errorLabel) +``` + +### emptyStateView + +Customize the empty state view displayed when no users are available. + +```swift +import UIKit +import CometChatUIKitSwift + +let users = CometChatUsers() + +let emptyLabel = UILabel() +emptyLabel.text = "No users found" +emptyLabel.textColor = .gray +emptyLabel.textAlignment = .center +users.set(emptyView: emptyLabel) +``` --- -#### set(subtitleView:) +## Options + +### set(options:) -You can customize the subtitle view for each user item to meet your requirements. +Define custom options for each user. This method allows you to return an array of `CometChatUserOption` based on the user object. - - ```swift -let cometChatUser = CometChatUsers() -cometChatUser.set(subtitleView: { user in - let view = CustomSubtitleView() - return view +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +users.set(options: { user in + return [CometChatUserOption]() +}) +``` + +### add(options:) + +Dynamically add options to users. This method lets you return additional `CometChatUserOption` elements. + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +users.add(options: { user in + return [ArchiveOption()] }) ``` - - + +--- + +## Custom ListItem + +For more complex or unique list items, you can create a custom `UIView` file named `CustomListItem` and integrate it into the `set(listItemView:)` method. - + -You can create a `CustomSubtitleView` as a custom `UIView` to use in `set(subtitleView:)`: - - - ```swift import UIKit +import CometChatUIKitSwift +import CometChatSDK -class CustomSubtitleView: UILabel { +class CustomListItem: UIView { - init(lastActiveDate: String) { - super.init(frame: .zero) - self.text = "Last Active at: \(lastActiveDate)" - self.textColor = UIColor.gray - self.font = UIFont.systemFont(ofSize: 14) - self.numberOfLines = 1 + // MARK: - UI Components + private var profileImageView: CometChatAvatar = { + let imageView = CometChatAvatar(image: UIImage()) + imageView.translatesAutoresizingMaskIntoConstraints = false + return imageView + }() + + private var nameLabel: UILabel = { + let label = UILabel() + label.translatesAutoresizingMaskIntoConstraints = false + return label + }() + + // MARK: - Initialization + override init(frame: CGRect) { + super.init(frame: frame) + setupUI() } - - required init?(coder: NSCoder) { + + required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + // MARK: - Setup + private func setupUI() { + addSubview(profileImageView) + addSubview(nameLabel) + + NSLayoutConstraint.activate([ + // Profile image constraints + profileImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), + profileImageView.centerYAnchor.constraint(equalTo: centerYAnchor), + profileImageView.widthAnchor.constraint(equalToConstant: 40), + profileImageView.heightAnchor.constraint(equalToConstant: 40), + + // Name label constraints + nameLabel.leadingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: 8), + nameLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), + nameLabel.centerYAnchor.constraint(equalTo: centerYAnchor) + ]) + } + + // MARK: - Configuration + func set(user: User) { + nameLabel.text = user.name + profileImageView.setAvatar(avatarUrl: user.avatar, with: user.name) + } } ``` - - ---- +Usage: -#### set(loadingView:) +```swift +import CometChatUIKitSwift +import CometChatSDK -You can set a custom loading view using `set(loadingView:)`. This method accepts a `UIView` to display while data is being fetched. +let users = CometChatUsers() - - -```swift -let loadingIndicator = UIActivityIndicatorView(style: .medium) -loadingIndicator.startAnimating() -cometChatUsers.set(loadingView: loadingIndicator) +users.set(listItemView: { user in + let customItem = CustomListItem() + customItem.set(user: user) + return customItem +}) ``` - - --- -#### set(errorView:) +## Styling + +### Style Hierarchy -You can customize the error view using `set(errorView:)`. This method accepts a `UIView` that appears when an error occurs. +1. Global styles (`CometChatUsers.style`) apply to all instances +2. Instance styles override global for specific instances + +### Global Level Styling - - ```swift -let errorLabel = UILabel() -errorLabel.text = "Something went wrong!" -errorLabel.textColor = .red -cometChatUsers.set(errorView: errorLabel) +import UIKit +import CometChatUIKitSwift + +// Apply global styles that affect all CometChatUsers instances +CometChatUsers.style.backgroundColor = UIColor.systemBackground +CometChatUsers.style.titleColor = UIColor.label +CometChatUsers.style.titleFont = UIFont.systemFont(ofSize: 34, weight: .bold) +CometChatUsers.style.listItemTitleTextColor = UIColor.label +CometChatUsers.style.listItemSubTitleTextColor = UIColor.secondaryLabel + +// Custom avatar style +let avatarStyle = AvatarStyle() +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) +CometChatUsers.avatarStyle = avatarStyle ``` - - ---- +### Instance Level Styling -#### set(emptyView:) +```swift +import UIKit +import CometChatUIKitSwift -You can customize the empty state view using `set(emptyView:)`. This method accepts a `UIView` that appears when no users are available. +// Create a custom style for a specific instance +var customStyle = UsersStyle() +customStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +customStyle.titleColor = UIColor.darkGray +customStyle.listItemBackground = UIColor.white - - -```swift -let emptyLabel = UILabel() -emptyLabel.text = "No users found" -emptyLabel.textColor = .gray -emptyLabel.textAlignment = .center -cometChatUsers.set(emptyView: emptyLabel) +let users = CometChatUsers() +users.style = customStyle ``` - - + + + + + +### Key Style Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color | +| `titleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Navigation title color | +| `titleFont` | `UIFont` | `CometChatTypography.Heading4.medium` | Navigation title font | +| `listItemTitleTextColor` | `UIColor` | `CometChatTheme.textColorPrimary` | User name color | +| `listItemTitleFont` | `UIFont` | `CometChatTypography.Heading4.medium` | User name font | +| `listItemSubTitleTextColor` | `UIColor` | `CometChatTheme.textColorSecondary` | Status text color | +| `listItemSubTitleFont` | `UIFont` | `CometChatTypography.Body.regular` | Status text font | +| `listItemBackground` | `UIColor` | `.clear` | List item background | +| `searchBarBackgroundColor` | `UIColor?` | `nil` | Search bar background | +| `searchBarTextColor` | `UIColor?` | `nil` | Search bar text color | +| `headerTitleColor` | `UIColor` | `CometChatTheme.textColorHighlight` | Section header color | +| `headerTitleFont` | `UIFont` | `CometChatTypography.Heading4.medium` | Section header font | + +### Customization Matrix + +| What to change | Where | Property/API | Example | +|----------------|-------|--------------|---------| +| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | +| Title appearance | Style | `titleColor`, `titleFont` | Custom colors and fonts | +| List item look | Style | `listItemBackground` | `UIColor.white` | +| Avatar appearance | Style | `avatarStyle` | `AvatarStyle()` with custom radius | +| Search bar | Style | `searchBarBackgroundColor` | Custom background | +| Hide search | Property | `hideSearch` | `users.hideSearch = true` | +| Hide status | Property | `hideUserStatus` | `users.hideUserStatus = true` | +| Custom row | View Slot | `set(listItemView:)` | See Custom View Slots | + +--- + +## Props + +All props are optional. Sorted alphabetically. + +### hideBackButton + +Hides the back button in the navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideErrorView + +Hides the error state view. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideLoadingState + +Hides the loading state indicator. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideNavigationBar + +Hides the entire navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideSearch + +Hides the search bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideSectionHeader + +Hides the alphabetical section headers. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### hideUserStatus + +Hides online/offline status indicators. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### searchRequestBuilder + +Custom request builder for search functionality. + +| | | +|---|---| +| Type | `UsersRequest.UsersRequestBuilder?` | +| Default | `nil` | + +### selectionMode + +Sets the selection mode for multi-select functionality. + +| | | +|---|---| +| Type | `SelectionMode` | +| Default | `.none` | + +### usersRequestBuilder + +Custom request builder for filtering users. + +| | | +|---|---| +| Type | `UsersRequest.UsersRequestBuilder?` | +| Default | `nil` | + +--- + +## Events + +| Event | Payload | Fires when | +|-------|---------|------------| +| `ccUserBlocked` | `User` | A user is blocked | +| `ccUserUnblocked` | `User` | A user is unblocked | + +--- + +## Troubleshooting + +| Issue | Solution | +|-------|----------| +| Empty user list | Ensure SDK is initialized and user is logged in | +| Users not updating in real-time | Check SDK connection and presence listeners | +| Search not working | Verify `hideSearch` is not set to true | +| Status not showing | Check that `hideUserStatus` is not set to true | +| Custom views not appearing | Ensure custom view has proper constraints | + +--- + +## Related Components + +- [Messages](/ui-kit/ios/messages) - Display messages with a user +- [Conversations](/ui-kit/ios/conversations) - List all conversations +- [Groups](/ui-kit/ios/groups) - List all groups +- [Users With Messages](/ui-kit/ios/users-with-messages) - Combined users and messages view From 4d0b1e1764c5bcecb6f456cd26a001ac78fac4b1 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 6 Mar 2026 12:20:59 +0530 Subject: [PATCH 050/106] Update .mintignore --- .mintignore | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.mintignore b/.mintignore index 15ada5362..9ddbca1cf 100644 --- a/.mintignore +++ b/.mintignore @@ -1,3 +1,8 @@ .kiro/ /codebase -/doc-auditor \ No newline at end of file +/doc-auditor +/prompts +/docs-templates +/mintignore +/doc-auditor +/docs-test-suite \ No newline at end of file From 2bbe7499b4a3766bae4c5e4d387689e2dda2cda3 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 6 Mar 2026 13:42:14 +0530 Subject: [PATCH 051/106] Update overview.mdx --- ui-kit/ios/overview.mdx | 165 ++++++++++++++++++++++++---------------- 1 file changed, 100 insertions(+), 65 deletions(-) diff --git a/ui-kit/ios/overview.mdx b/ui-kit/ios/overview.mdx index 3d54a09be..48985e87a 100644 --- a/ui-kit/ios/overview.mdx +++ b/ui-kit/ios/overview.mdx @@ -4,11 +4,46 @@ sidebarTitle: "Overview" description: "Integrate chat functionality into iOS applications with prebuilt, modular, and customizable UI components" --- -The CometChat UI Kit for iOS provides a seamless solution to integrate chat functionality into your iOS applications. With prebuilt, modular, and customizable UI components, it accelerates development and ensures your chat application is robust, scalable, and tailored to your needs. + +```json +{ + "platform": "iOS UI Kit", + "package": "CometChatUIKitSwift", + "version": "5.0.0", + "description": "Pre-built UI components for iOS chat applications using SwiftUI", + "metadata": { + "peerDependencies": { + "CometChatSDK": ">= 4.0.0" + }, + "supportedPlatforms": ["iOS 13.0+", "iPadOS 13.0+", "Mac Catalyst 13.0+"], + "language": "Swift 5.0+", + "license": "MIT" + }, + "quickLinks": { + "documentation": "https://www.cometchat.com/docs/ui-kit/ios/overview", + "repository": "https://github.com/cometchat/cometchat-uikit-ios", + "demo": "https://demo.cometchat.com" + } +} +``` + + +| Property | Value | +|----------|-------| +| Package | CometChatUIKitSwift | +| Version | 5.0.0 | +| Peer Dependencies | CometChatSDK >= 4.0.0 | +| Platforms | iOS 13.0+, iPadOS 13.0+, Mac Catalyst 13.0+ | +| Language | Swift 5.0+ | +| License | MIT | --- -## Why Choose CometChat UI Kit? +## Introduction + +The CometChat UI Kit for iOS provides a seamless solution to integrate chat functionality into your iOS applications. With prebuilt, modular, and customizable UI components, it accelerates development and ensures your chat application is robust, scalable, and tailored to your needs. + +### Key Features - Effortless Integration: Ready-to-use SwiftUI components for rapid implementation - Highly Customizable: Adapt UI components to match your brand and user experience requirements @@ -17,84 +52,84 @@ The CometChat UI Kit for iOS provides a seamless solution to integrate chat func --- -## User Interface Preview +## Try It - - - + + + Experience the UI Kit in action with our interactive demo + + + Explore the complete source code on GitHub + + --- -## Download the CometChat Demo App - -Get started with the CometChat UI Kit on your mobile device: - -**Download from the App Store** - -[](https://link.cometchat.com/ios-demo-app) - -**Or Scan the QR Code** - - - - - - -On iOS, open the camera app and scan the QR code to install directly. - - ---- - -## Getting Started +## Get Started Before integrating the CometChat UI Kit, familiarize yourself with the key concepts and features offered by CometChat's platform: - Review the [Key Concepts](/fundamentals/key-concepts) to understand essential terminology and features - Follow the [Getting Started Guide](/ui-kit/ios/getting-started) for detailed steps on initial setup and integration ---- - -## Integration and Customization - -The CometChat UI Kit consists of modular SwiftUI components that can be integrated effortlessly into your app, offering flexible customization: - -- Prebuilt UI Components: Ready-to-use chat UI elements -- Modular Structure: Easy to integrate and modify -- Customization Options: Highly configurable to fit your brand and UI requirements - -Explore more about UI customization in the [Customization Guide](/ui-kit/ios/theme-introduction). + + + --- -## Helpful Resources - -Explore these essential resources to gain a deeper understanding of CometChat UI Kits and streamline your integration process. - -#### 🚀 iOS Sample App - -Fully functional sample applications to accelerate your development. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-ios) - -#### 📦 UI Kit Source Code - -Access the complete UI Kit source code on GitHub. - -[View on GitHub](https://github.com/cometchat/cometchat-uikit-ios) - -#### 🎨 Figma Design File - -UI design resources for customization and prototyping. - -[View on Figma](https://www.figma.com/community/file/1444325479486807899/cometchat-ui-kit-for-ios) +## Explore + + + + Pre-built UI components for conversations, messages, users, and groups + + + Core messaging, calling, and AI-powered features + + + Customize colors, typography, and styling to match your brand + + + Step-by-step guides for integrating the UI Kit + + + Complete SDK documentation and API details + + + Tutorials and how-to guides for common use cases + + --- -## Need Help? - -If you need assistance, check out: - -- 💬 [Developer Community](http://community.cometchat.com/) -- ❓ [Support Portal](https://help.cometchat.com/hc/en-us/requests/new) +## Resources + + + + Try the interactive demo on your iOS device + + + Complete sample application source code + + + Step-by-step integration tutorials + + + Browse all available UI components + + + Explore messaging, calling, and AI features + + + Customize the look and feel + + + Common issues and solutions + + + Get help from our support team + + --- From eda7c2ca15f5edce1a36354fbc5695151dc49533 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 6 Mar 2026 13:42:45 +0530 Subject: [PATCH 052/106] updates code --- ui-kit/ios/ai-assistant-chat-history.mdx | 38 ++++++++++++++-- ui-kit/ios/call-buttons.mdx | 48 +++++++++++++++++++-- ui-kit/ios/call-logs.mdx | 55 ++++++++++++++++++++++-- ui-kit/ios/incoming-call.mdx | 50 +++++++++++++++++++-- ui-kit/ios/ongoing-call.mdx | 40 +++++++++++++++-- ui-kit/ios/outgoing-call.mdx | 49 +++++++++++++++++++-- ui-kit/ios/search.mdx | 38 ++++++++++++++-- ui-kit/ios/threaded-messages-header.mdx | 37 ++++++++++++++-- 8 files changed, 330 insertions(+), 25 deletions(-) diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index 5e2b7243d..3ecf42158 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -4,14 +4,46 @@ sidebarTitle: "AI Assistant Chat History" description: "Complete guide to displaying AI assistant conversation history in iOS apps - production-ready code included" --- -## Overview - -`CometChatAIAssistanceChatHistory` displays past conversations between users and AI assistants. Users can review previous AI interactions and start new conversations. +The `CometChatAIAssistanceChatHistory` component displays past conversations between users and AI assistants. Users can review previous AI interactions and start new conversations. + +```json +{ + "component": "CometChatAIAssistanceChatHistory", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays past conversations between users and AI assistants", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onItemClick", + "type": "(AIConversation) -> Void" + }, + "props": { + "data": { + "user": { "type": "User?", "default": "nil" }, + "group": { "type": "Group?", "default": "nil" } + }, + "callbacks": { + "onItemClick": "(AIConversation) -> Void", + "onBack": "() -> Void", + "onError": "(CometChatException) -> Void" + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "AIAssistanceChatHistory shows previous AI conversations for a user or group", + "components": ["CometChatAIAssistanceChatHistory", "CometChatMessages"], + "flow": "User opens AI history → selects conversation → views full AI chat" + } +} +``` + + --- ## Prerequisites diff --git a/ui-kit/ios/call-buttons.mdx b/ui-kit/ios/call-buttons.mdx index 7f790d10e..c5bed3075 100644 --- a/ui-kit/ios/call-buttons.mdx +++ b/ui-kit/ios/call-buttons.mdx @@ -1,15 +1,57 @@ --- title: "Call Buttons" +description: "Provides voice and video call buttons for initiating calls with users or groups" --- -## Overview - -The `Call Button` is a [Component](/ui-kit/ios/components-overview#components) provides users with the ability to make calls, access call-related functionalities, and control call settings. Clicking this button typically triggers the call to be placed to the desired recipient. +The `CometChatCallButtons` component provides users with the ability to make calls, access call-related functionalities, and control call settings. Clicking this button typically triggers the call to be placed to the desired recipient. + +```json +{ + "component": "CometChatCallButtons", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Provides voice and video call buttons for initiating calls with users or groups", + "inherits": "UIView", + "primaryOutput": { + "callback": "onVoiceCallClick", + "type": "(User?, Group?) -> Void" + }, + "props": { + "data": { + "user": { "type": "User?", "default": "nil" }, + "group": { "type": "Group?", "default": "nil" } + }, + "callbacks": { + "onVoiceCallClick": "(User?, Group?) -> Void", + "onVideoCallClick": "(User?, Group?) -> Void", + "onError": "(CometChatException) -> Void" + }, + "visibility": { + "hideVoiceCallButton": { "type": "Bool", "default": false }, + "hideVideoCallButton": { "type": "Bool", "default": false } + } + }, + "events": [ + { "name": "onOutgoingCallAccepted", "payload": "Call", "description": "Fires when outgoing call is accepted" }, + { "name": "onOutgoingCallRejected", "payload": "Call", "description": "Fires when outgoing call is rejected" } + ], + "sdkListeners": [], + "compositionExample": { + "description": "CallButtons is typically used in MessageHeader or as standalone call controls", + "components": ["CometChatCallButtons", "CometChatOutgoingCall"], + "flow": "User taps call button → OutgoingCall screen appears → Call connects or is rejected" + } +} +``` + + +--- + ## Usage ### Integration diff --git a/ui-kit/ios/call-logs.mdx b/ui-kit/ios/call-logs.mdx index f59346b3a..4d3721013 100644 --- a/ui-kit/ios/call-logs.mdx +++ b/ui-kit/ios/call-logs.mdx @@ -1,15 +1,64 @@ --- title: "Call Logs" +description: "Displays a list of call logs with call type, duration, and participant information" --- -## Overview - -`CometChatCallLogs` is a [Component](/ui-kit/ios/components-overview#components) that shows the list of Call Log available . By default, names are shown for all listed users, along with their avatar if available. +The `CometChatCallLogs` component shows the list of call logs available. By default, names are shown for all listed users, along with their avatar if available. + +```json +{ + "component": "CometChatCallLogs", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatCallsSDK", + "description": "Displays a list of call logs with call type, duration, and participant information", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onItemClick", + "type": "(CallLog, IndexPath) -> Void" + }, + "props": { + "data": { + "callRequestBuilder": { "type": "CallLogsRequest.CallLogsBuilder?", "default": "nil" } + }, + "callbacks": { + "onItemClick": "(CallLog, IndexPath) -> Void", + "onItemLongClick": "(CallLog, IndexPath) -> Void", + "onBack": "() -> Void", + "onError": "(CometChatCallException) -> Void", + "onEmpty": "() -> Void", + "onLoad": "([CallLog]) -> Void" + }, + "visibility": { + "hideError": { "type": "Bool", "default": false }, + "hideNavigationBar": { "type": "Bool", "default": false }, + "hideLoadingState": { "type": "Bool", "default": false }, + "hideBackIcon": { "type": "Bool", "default": false } + }, + "viewSlots": { + "listItemView": "(CallLog) -> UIView", + "titleView": "(CallLog) -> UIView", + "leadingView": "(CallLog) -> UIView", + "trailView": "(CallLog) -> UIView" + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "CallLogs is typically used as a standalone screen or tab in the main navigation", + "components": ["CometChatCallLogs", "CometChatCallLogDetails"], + "flow": "User views call history → taps call log → sees call details or initiates callback" + } +} +``` + + +--- + The `Call Logs` component is composed of the following BaseComponents: | Components | Description | diff --git a/ui-kit/ios/incoming-call.mdx b/ui-kit/ios/incoming-call.mdx index bcbf2a736..ce5235521 100644 --- a/ui-kit/ios/incoming-call.mdx +++ b/ui-kit/ios/incoming-call.mdx @@ -3,14 +3,58 @@ title: "Incoming Call" description: "Display and handle incoming voice and video calls" --- -## Overview - -The `Incoming call` is a [Component](/ui-kit/ios/components-overview#components) that serves as a visual representation when the user receives an incoming call, such as a voice call or video call, providing options to answer or decline the call. +The `CometChatIncomingCall` component serves as a visual representation when the user receives an incoming call, such as a voice call or video call, providing options to answer or decline the call. + +```json +{ + "component": "CometChatIncomingCall", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays incoming call interface with accept and reject options", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onAcceptClick", + "type": "(Call, UIViewController) -> Void" + }, + "props": { + "data": { + "call": { "type": "Call", "required": true } + }, + "callbacks": { + "onAcceptClick": "(Call, UIViewController) -> Void", + "onCancelClick": "(Call, UIViewController) -> Void", + "onError": "(CometChatException) -> Void" + }, + "sound": { + "disableSoundForCalls": { "type": "Bool", "default": false }, + "customSoundForCalls": { "type": "URL?", "default": "nil" } + }, + "viewSlots": { + "listItemView": "(Call) -> UIView", + "leadingView": "(Call) -> UIView", + "titleView": "(Call) -> UIView" + } + }, + "events": [ + { "name": "onIncomingCallAccepted", "payload": "Call", "description": "Fires when incoming call is accepted" }, + { "name": "onIncomingCallRejected", "payload": "Call", "description": "Fires when incoming call is rejected" }, + { "name": "onCallEnded", "payload": "Call", "description": "Fires when call ends" } + ], + "sdkListeners": [], + "compositionExample": { + "description": "IncomingCall is presented when a call is received", + "components": ["CometChatIncomingCall", "CometChatOngoingCall"], + "flow": "Call received → IncomingCall shown → User accepts → OngoingCall starts" + } +} +``` + + --- ## Usage diff --git a/ui-kit/ios/ongoing-call.mdx b/ui-kit/ios/ongoing-call.mdx index 1870f8ba7..3f3045664 100644 --- a/ui-kit/ios/ongoing-call.mdx +++ b/ui-kit/ios/ongoing-call.mdx @@ -1,15 +1,49 @@ --- title: "Ongoing Call" +description: "Displays active call interface with video, controls, and participant management" --- -## Overview - -The `Ongoing Call` is a [Component](/ui-kit/ios/components-overview#components) that provides users with a dedicated interface for managing real-time voice or video conversations. It includes features like a video display area for video calls, call controls for mic and camera management, participant information, call status indicators, and options for call recording and screen-sharing. +The `CometChatOngoingCall` component provides users with a dedicated interface for managing real-time voice or video conversations. It includes features like a video display area for video calls, call controls for mic and camera management, participant information, call status indicators, and options for call recording and screen-sharing. + +```json +{ + "component": "CometChatOngoingCall", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatCallsSDK", + "description": "Displays active call interface with video, controls, and participant management", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onCallEnded", + "type": "(Call) -> Void" + }, + "props": { + "data": { + "sessionID": { "type": "String", "required": true }, + "callSettingsBuilder": { "type": "CallSettingsBuilder?", "default": "nil" } + }, + "callbacks": { + "onCallEnded": "(Call) -> Void", + "onError": "(CometChatException) -> Void" + } + }, + "events": [ + { "name": "onCallEnded", "payload": "Call", "description": "Fires when call ends" } + ], + "sdkListeners": [], + "compositionExample": { + "description": "OngoingCall is presented during an active call", + "components": ["CometChatIncomingCall", "CometChatOutgoingCall", "CometChatOngoingCall"], + "flow": "Call accepted → OngoingCall shown → Call ends → Returns to previous screen" + } +} +``` + + --- ## Usage diff --git a/ui-kit/ios/outgoing-call.mdx b/ui-kit/ios/outgoing-call.mdx index 822de157b..1bcb30a0a 100644 --- a/ui-kit/ios/outgoing-call.mdx +++ b/ui-kit/ios/outgoing-call.mdx @@ -1,15 +1,58 @@ --- title: "Outgoing Call" +description: "Displays outgoing call interface while waiting for recipient to answer" --- -## Overview - -The `Outgoing Call` [Component](/ui-kit/ios/components-overview#components) is a visual representation of a user-initiated call, whether voice or video. It serves as an interface for managing outgoing calls, providing users with essential options to control the call experience. This component typically includes information about the call recipient, call controls for canceling the call, and feedback on the call status, such as indicating when the call is in progress. +The `CometChatOutgoingCall` component is a visual representation of a user-initiated call, whether voice or video. It serves as an interface for managing outgoing calls, providing users with essential options to control the call experience. + +```json +{ + "component": "CometChatOutgoingCall", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays outgoing call interface while waiting for recipient to answer", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onCancelClick", + "type": "(Call, UIViewController) -> Void" + }, + "props": { + "data": { + "call": { "type": "Call", "required": true } + }, + "callbacks": { + "onCancelClick": "(Call, UIViewController) -> Void", + "onError": "(CometChatException) -> Void" + }, + "sound": { + "disableSoundForCalls": { "type": "Bool", "default": false }, + "customSoundForCalls": { "type": "URL?", "default": "nil" } + }, + "viewSlots": { + "listItemView": "(Call) -> UIView", + "leadingView": "(Call) -> UIView", + "titleView": "(Call) -> UIView" + } + }, + "events": [ + { "name": "onOutgoingCallAccepted", "payload": "Call", "description": "Fires when outgoing call is accepted" }, + { "name": "onOutgoingCallRejected", "payload": "Call", "description": "Fires when outgoing call is rejected" } + ], + "sdkListeners": [], + "compositionExample": { + "description": "OutgoingCall is presented when user initiates a call", + "components": ["CometChatCallButtons", "CometChatOutgoingCall", "CometChatOngoingCall"], + "flow": "User taps call → OutgoingCall shown → Recipient answers → OngoingCall starts" + } +} +``` + + --- ## Usage diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index 9f4c12553..47f63a4f7 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -4,16 +4,46 @@ sidebarTitle: "Search" description: "Search across conversations and messages with customizable filters in CometChat UI Kit for iOS" --- -## Overview - The `CometChatSearch` component is a powerful and customizable search interface that allows users to search across conversations and messages in real time. It supports a wide variety of filters, scopes, and customization options. -`CometChatSearch` helps users find messages, conversations, media, and more through an intuitive and filterable search experience. It can be embedded in multiple contexts—as part of the conversation list, message header, or as a full-screen search experience. - + +```json +{ + "component": "CometChatSearch", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Provides search functionality across conversations and messages", + "inherits": "UIViewController", + "primaryOutput": { + "callback": "onMessageClicked", + "type": "(BaseMessage) -> Void" + }, + "props": { + "callbacks": { + "onConversationClicked": "(Conversation) -> Void", + "onMessageClicked": "(BaseMessage) -> Void", + "onBack": "() -> Void", + "onError": "(CometChatException) -> Void" + }, + "visibility": { + "hideNavigationBar": { "type": "Bool", "default": false } + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "Search is typically accessed from conversation list or message header", + "components": ["CometChatConversations", "CometChatSearch", "CometChatMessages"], + "flow": "User taps search → enters query → taps result → navigates to conversation/message" + } +} +``` + + --- ## Usage diff --git a/ui-kit/ios/threaded-messages-header.mdx b/ui-kit/ios/threaded-messages-header.mdx index c04904382..6f9b50893 100644 --- a/ui-kit/ios/threaded-messages-header.mdx +++ b/ui-kit/ios/threaded-messages-header.mdx @@ -4,14 +4,45 @@ sidebarTitle: "Threaded Messages Header" description: "Display and customize the header for threaded message conversations in CometChat UI Kit for iOS" --- -## Overview - -ThreadedMessages is a [Composite Component](/ui-kit/ios/components-overview#composite-components) that displays all replies made to a particular message in a conversation. By default, the parent message appears at the top, the message composer is at the bottom, and a message list containing all replies is displayed between them. +The `CometChatThreadedMessageHeader` component displays the header for threaded message conversations showing parent message info. By default, the parent message appears at the top, the message composer is at the bottom, and a message list containing all replies is displayed between them. + +```json +{ + "component": "CometChatThreadedMessageHeader", + "package": "CometChatUIKitSwift", + "import": "import CometChatUIKitSwift\nimport CometChatSDK", + "description": "Displays the header for threaded message conversations showing parent message info", + "inherits": "UIView", + "primaryOutput": { + "callback": "onBack", + "type": "() -> Void" + }, + "props": { + "data": { + "parentMessage": { "type": "BaseMessage", "required": true } + }, + "callbacks": { + "onBack": "() -> Void" + } + }, + "events": [], + "sdkListeners": [], + "compositionExample": { + "description": "ThreadedMessageHeader is used within ThreadedMessages component", + "components": ["CometChatThreadedMessageHeader", "CometChatMessageList", "CometChatMessageComposer"], + "flow": "User opens thread → sees parent message in header → views/sends replies below" + } +} +``` + + +--- + ThreadedMessages is composed of the following components: | Component | Description | From d60813eb92f954e5bbe0c56f2f07752232ca5f98 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 6 Mar 2026 14:34:49 +0530 Subject: [PATCH 053/106] Adds agent specs --- ui-kit/ios/ai-features.mdx | 19 +++++++ ui-kit/ios/call-features.mdx | 21 ++++++++ ui-kit/ios/components-overview.mdx | 37 +++++++++++++ ui-kit/ios/core-features.mdx | 21 ++++++++ ui-kit/ios/events.mdx | 69 +++++++++++++++++++++++++ ui-kit/ios/extensions.mdx | 26 ++++++++++ ui-kit/ios/getting-started.mdx | 28 ++++++++++ ui-kit/ios/guide-ai-agent.mdx | 16 ++++-- ui-kit/ios/guide-block-unblock-user.mdx | 18 +++++-- ui-kit/ios/guide-call-log-details.mdx | 14 +++++ ui-kit/ios/guide-group-chat.mdx | 14 +++++ ui-kit/ios/guide-group-ownership.mdx | 17 +++--- ui-kit/ios/guide-message-privately.mdx | 22 ++++++-- ui-kit/ios/guide-new-chat.mdx | 14 +++++ ui-kit/ios/guide-overview.mdx | 27 ++++++++++ ui-kit/ios/guide-threaded-messages.mdx | 23 +++++++-- ui-kit/ios/methods.mdx | 44 ++++++++++++++++ ui-kit/ios/theme-introduction.mdx | 27 ++++++++++ 18 files changed, 429 insertions(+), 28 deletions(-) diff --git a/ui-kit/ios/ai-features.mdx b/ui-kit/ios/ai-features.mdx index 38031c90e..0c4f01b71 100644 --- a/ui-kit/ios/ai-features.mdx +++ b/ui-kit/ios/ai-features.mdx @@ -4,6 +4,25 @@ sidebarTitle: "AI" description: "Complete guide to AI-powered chat features in iOS apps - conversation starters, smart replies, and summaries" --- + +```json +{ + "category": "ai", + "features": [ + {"name": "aiAgentChat", "description": "Chat with AI-powered assistants", "component": "CometChatMessages", "enabledByDefault": false}, + {"name": "chatHistory", "description": "Browse and resume previous AI sessions", "component": "CometChatAIAssistanceChatHistory", "enabledByDefault": false}, + {"name": "streamingResponses", "description": "Real-time AI message streaming", "component": "CometChatMessageList", "enabledByDefault": false}, + {"name": "suggestedMessages", "description": "AI-powered conversation starters and smart replies", "component": "CometChatMessageComposer", "enabledByDefault": false} + ], + "dashboardSetup": { + "location": "CometChat Dashboard → AI", + "features": ["Conversation Starter", "Smart Replies", "Conversation Summary"] + }, + "relatedComponents": ["CometChatMessages", "CometChatAIAssistanceChatHistory", "CometChatMessageList", "CometChatMessageComposer"] +} +``` + + ## Overview CometChat AI features enhance your chat experience with intelligent suggestions and summaries. Once enabled in your dashboard, they integrate automatically into the UI Kit components. diff --git a/ui-kit/ios/call-features.mdx b/ui-kit/ios/call-features.mdx index cbfca1a11..d39515839 100644 --- a/ui-kit/ios/call-features.mdx +++ b/ui-kit/ios/call-features.mdx @@ -4,6 +4,27 @@ sidebarTitle: "Call" description: "Complete guide to adding voice and video calling to iOS apps with CometChat UI Kit - production-ready code included" --- + +```json +{ + "category": "calling", + "features": [ + {"name": "voiceCalling", "description": "One-on-one and group audio calls", "component": "CometChatCallButtons", "enabledByDefault": true}, + {"name": "videoCalling", "description": "One-on-one and group video calls", "component": "CometChatCallButtons", "enabledByDefault": true}, + {"name": "callLogs", "description": "View call history with metadata", "component": "CometChatCallLogs", "enabledByDefault": true}, + {"name": "incomingCall", "description": "Handle incoming call UI with accept/reject", "component": "CometChatIncomingCall", "enabledByDefault": true}, + {"name": "outgoingCall", "description": "Display outgoing call screen while connecting", "component": "CometChatOutgoingCall", "enabledByDefault": true}, + {"name": "ongoingCall", "description": "Active call interface with controls", "component": "CometChatOngoingCall", "enabledByDefault": true} + ], + "sdkDependencies": { + "required": "CometChatCallsSDK 4.2.2", + "permissions": ["NSCameraUsageDescription", "NSMicrophoneUsageDescription"] + }, + "relatedComponents": ["CometChatCallButtons", "CometChatCallLogs", "CometChatIncomingCall", "CometChatOutgoingCall", "CometChatOngoingCall"] +} +``` + + ## Overview Add one-on-one and group audio/video calling to your iOS app. Once integrated, call buttons automatically appear in chat headers, and incoming/outgoing call screens are handled for you. diff --git a/ui-kit/ios/components-overview.mdx b/ui-kit/ios/components-overview.mdx index 0eebab191..e0cba4d8d 100644 --- a/ui-kit/ios/components-overview.mdx +++ b/ui-kit/ios/components-overview.mdx @@ -4,6 +4,43 @@ sidebarTitle: "Overview" description: "Understanding CometChat iOS UI Kit components - types, actions, events, and customization" --- + +```json +{ + "platform": "iOS UI Kit", + "package": "CometChatUIKitSwift", + "version": "5.0.0", + "componentTypes": { + "base": "Simple UI elements with no business logic", + "components": "UI elements with built-in business logic", + "composite": "Multiple components combined into complete features" + }, + "baseComponents": [ + {"name": "CometChatAvatar", "purpose": "User/group profile images"}, + {"name": "CometChatBadge", "purpose": "Notification counts"}, + {"name": "CometChatStatusIndicator", "purpose": "Online/offline status"}, + {"name": "CometChatDate", "purpose": "Formatted timestamps"}, + {"name": "CometChatReceipt", "purpose": "Message delivery status"} + ], + "components": [ + {"name": "CometChatUsers", "purpose": "List of users"}, + {"name": "CometChatGroups", "purpose": "List of groups"}, + {"name": "CometChatConversations", "purpose": "Recent chats list"}, + {"name": "CometChatMessageList", "purpose": "Chat messages"}, + {"name": "CometChatMessageComposer", "purpose": "Message input"}, + {"name": "CometChatMessageHeader", "purpose": "Chat header"}, + {"name": "CometChatCallLogs", "purpose": "Call history"} + ], + "compositeComponents": [ + {"name": "CometChatMessages", "contains": ["MessageHeader", "MessageList", "MessageComposer"]}, + {"name": "CometChatUsersWithMessages", "contains": ["Users", "Messages"]}, + {"name": "CometChatGroupsWithMessages", "contains": ["Groups", "Messages"]}, + {"name": "CometChatConversationsWithMessages", "contains": ["Conversations", "Messages"]} + ] +} +``` + + ## Overview CometChat UI Kit provides pre-built components that you can use to quickly build a chat experience. Components are organized into three types based on complexity. diff --git a/ui-kit/ios/core-features.mdx b/ui-kit/ios/core-features.mdx index 1f22abf21..7754c5a85 100644 --- a/ui-kit/ios/core-features.mdx +++ b/ui-kit/ios/core-features.mdx @@ -3,6 +3,27 @@ title: "Core Features" description: "Essential chat features built into CometChat UI Kit for iOS" --- + +```json +{ + "category": "messaging", + "features": [ + {"name": "instantMessaging", "description": "Send and receive text messages in real-time", "component": "CometChatMessages", "enabledByDefault": true}, + {"name": "mediaSharing", "description": "Share images, videos, audio files, and documents", "component": "CometChatMessageComposer", "enabledByDefault": true}, + {"name": "readReceipts", "description": "Show when messages are delivered and read", "component": "CometChatMessageList", "enabledByDefault": true}, + {"name": "typingIndicators", "description": "Show when users are typing in real-time", "component": "CometChatMessageHeader", "enabledByDefault": true}, + {"name": "userPresence", "description": "Display online/offline status for users", "component": "CometChatConversations", "enabledByDefault": true}, + {"name": "reactions", "description": "Let users react to messages with emojis", "component": "CometChatMessageList", "enabledByDefault": true}, + {"name": "mentions", "description": "Tag users in messages with @mentions", "component": "CometChatMessageComposer", "enabledByDefault": true}, + {"name": "threadedConversations", "description": "Reply to specific messages in threads", "component": "CometChatThreadedMessages", "enabledByDefault": true}, + {"name": "groupChat", "description": "Create and manage group conversations", "component": "CometChatGroups", "enabledByDefault": true}, + {"name": "search", "description": "Search across conversations and messages", "component": "CometChatSearch", "enabledByDefault": true} + ], + "relatedComponents": ["CometChatMessages", "CometChatConversations", "CometChatMessageList", "CometChatMessageComposer"] +} +``` + + CometChat UI Kit provides production-ready components that work together to deliver a complete chat experience. This guide shows how to implement each core feature with copy-paste code examples. ## Instant Messaging diff --git a/ui-kit/ios/events.mdx b/ui-kit/ios/events.mdx index a47d9739c..0bedb41ff 100644 --- a/ui-kit/ios/events.mdx +++ b/ui-kit/ios/events.mdx @@ -3,6 +3,75 @@ title: "Events" description: "Listen and respond to user actions and state changes in CometChat UI Kit" --- + +```json +{ + "category": "events", + "subscriptionPattern": { + "addListener": "CometChat{Category}Events.addListener(listenerId, self)", + "removeListener": "CometChat{Category}Events.removeListener(listenerId)" + }, + "eventCategories": [ + { + "name": "userEvents", + "listenerClass": "CometChatUserEvents", + "protocol": "CometChatUserEventListener", + "events": [ + {"name": "onUserBlock", "payload": "User", "description": "User was blocked"}, + {"name": "onUserUnblock", "payload": "User", "description": "User was unblocked"} + ] + }, + { + "name": "groupEvents", + "listenerClass": "CometChatGroupEvents", + "protocol": "CometChatGroupEventListener", + "events": [ + {"name": "onGroupCreate", "payload": "Group", "description": "New group created"}, + {"name": "onGroupDelete", "payload": "Group", "description": "Group deleted"}, + {"name": "onGroupMemberJoin", "payload": "(User, Group)", "description": "User joined group"}, + {"name": "onGroupMemberLeave", "payload": "(User, Group)", "description": "User left group"}, + {"name": "onGroupMemberKick", "payload": "(User, Group)", "description": "Member kicked"}, + {"name": "onGroupMemberBan", "payload": "(User, Group)", "description": "Member banned"}, + {"name": "onOwnershipChange", "payload": "(Group, GroupMember)", "description": "Ownership transferred"} + ] + }, + { + "name": "conversationEvents", + "listenerClass": "CometChatConversationEvents", + "protocol": "CometChatConversationEventListener", + "events": [ + {"name": "ccConversationDeleted", "payload": "Conversation", "description": "Conversation deleted"}, + {"name": "ccUpdateConversation", "payload": "Conversation", "description": "Conversation updated"} + ] + }, + { + "name": "messageEvents", + "listenerClass": "CometChatMessageEvents", + "protocol": "CometChatMessageEventListener", + "events": [ + {"name": "onMessageSent", "payload": "(BaseMessage, MessageStatus)", "description": "Message sent"}, + {"name": "onMessageEdit", "payload": "(BaseMessage, MessageStatus)", "description": "Message edited"}, + {"name": "onMessageDelete", "payload": "(BaseMessage, MessageStatus)", "description": "Message deleted"}, + {"name": "onMessageRead", "payload": "BaseMessage", "description": "Message read"}, + {"name": "onMessageReact", "payload": "(BaseMessage, Reaction)", "description": "Reaction added"} + ] + }, + { + "name": "callEvents", + "listenerClass": "CometChatCallEvents", + "protocol": "CometChatCallEventListener", + "events": [ + {"name": "onCallInitiated", "payload": "Call", "description": "Outgoing call started"}, + {"name": "onCallEnded", "payload": "Call", "description": "Call ended"}, + {"name": "onIncomingCallAccepted", "payload": "Call", "description": "Incoming call accepted"}, + {"name": "onOutgoingCallAccepted", "payload": "Call", "description": "Outgoing call accepted"} + ] + } + ] +} +``` + + Events allow different parts of your app to communicate without direct dependencies. When a user performs an action (like blocking someone, deleting a conversation, or sending a message), events are emitted so other components can react accordingly. ## How Events Work diff --git a/ui-kit/ios/extensions.mdx b/ui-kit/ios/extensions.mdx index 8bde20ada..ef5fcd9cf 100644 --- a/ui-kit/ios/extensions.mdx +++ b/ui-kit/ios/extensions.mdx @@ -3,6 +3,32 @@ title: "Extensions" description: "Enable powerful chat features with zero code using CometChat extensions" --- + +```json +{ + "category": "extensions", + "dashboardSetup": { + "location": "CometChat Dashboard → Extensions", + "activation": "Enable extensions in dashboard, they appear automatically in UI Kit" + }, + "extensions": [ + {"name": "stickers", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/stickers"}, + {"name": "polls", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/polls"}, + {"name": "whiteboard", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/collaborative-whiteboard"}, + {"name": "document", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/collaborative-document"}, + {"name": "reactions", "component": "CometChatMessageList", "setupGuide": "/fundamentals/reactions"}, + {"name": "translation", "component": "CometChatMessageList", "setupGuide": "/fundamentals/message-translation"}, + {"name": "linkPreview", "component": "CometChatMessageList", "setupGuide": "/fundamentals/link-preview"}, + {"name": "profanityFilter", "component": "CometChatMessageList", "setupGuide": "/moderation/legacy-extensions"}, + {"name": "dataMasking", "component": "CometChatMessageList", "setupGuide": "/moderation/legacy-extensions"}, + {"name": "imageModeration", "component": "CometChatMessageList", "setupGuide": "/moderation/legacy-extensions"}, + {"name": "thumbnails", "component": "CometChatMessageList", "setupGuide": "/fundamentals/thumbnail-generation"}, + {"name": "smartReplies", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/smart-replies"} + ] +} +``` + + Extensions add powerful features to your chat app without writing any code. Simply enable them in your [CometChat Dashboard](https://app.cometchat.com), and they automatically appear in the UI Kit components. ## How Extensions Work diff --git a/ui-kit/ios/getting-started.mdx b/ui-kit/ios/getting-started.mdx index 0fabda03d..a78eed906 100644 --- a/ui-kit/ios/getting-started.mdx +++ b/ui-kit/ios/getting-started.mdx @@ -3,6 +3,34 @@ title: "Getting Started With CometChat iOS UI Kit" sidebarTitle: "Integration" --- + +```json +{ + "platform": "iOS UI Kit", + "package": "CometChatUIKitSwift", + "version": "5.1.7", + "requirements": { + "xcode": "16 or later", + "ios": "13.0+", + "swift": "5.0+", + "dependencies": { + "CometChatSDK": "4.1.0", + "CometChatCallsSDK": "4.2.2 (optional)" + } + }, + "installation": { + "cocoapods": "pod 'CometChatUIKitSwift', '5.1.7'", + "spm": "https://github.com/cometchat/cometchat-uikit-ios" + }, + "quickStart": { + "initialize": "CometChatUIKit.init(uiKitSettings:)", + "login": "CometChatUIKit.login(uid:)", + "requiredCredentials": ["appID", "authKey", "region"] + } +} +``` + + The **CometChat UI Kit for iOS** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI elements**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat iOS UI Kit. diff --git a/ui-kit/ios/guide-ai-agent.mdx b/ui-kit/ios/guide-ai-agent.mdx index 1cd558bcc..ec3a6f5f3 100644 --- a/ui-kit/ios/guide-ai-agent.mdx +++ b/ui-kit/ios/guide-ai-agent.mdx @@ -528,8 +528,14 @@ class ChatHistoryViewController: UIViewController { ## Related Guides -- [AI Features](/ui-kit/ios/ai-features) - Overview of AI capabilities -- [AI Assistant Chat History](/ui-kit/ios/ai-assistant-chat-history) - Chat history component -- [Message List](/ui-kit/ios/message-list) - Message display component -- [Message Header](/ui-kit/ios/message-header) - Message header component -- [Message Composer](/ui-kit/ios/message-composer) - Message composer component + + + Overview of all AI-powered features + + + Browse and resume AI conversations + + + Display and customize chat messages + + diff --git a/ui-kit/ios/guide-block-unblock-user.mdx b/ui-kit/ios/guide-block-unblock-user.mdx index 5827a39f8..820ef4401 100644 --- a/ui-kit/ios/guide-block-unblock-user.mdx +++ b/ui-kit/ios/guide-block-unblock-user.mdx @@ -688,11 +688,21 @@ avatar.set(style: avatarStyle) | Call buttons missing | Import CometChatCallsSDK | | Avatar not loading | Check user has valid avatar URL | -## Related Components +## Related Guides -- [Users](/ui-kit/ios/users) - Display user list -- [Conversations](/ui-kit/ios/conversations) - Display conversation list -- [Message List](/ui-kit/ios/message-list) - Message display component + + + Display and manage user list + + + Handle user and block events + + + View and manage conversations + + + +--- diff --git a/ui-kit/ios/guide-call-log-details.mdx b/ui-kit/ios/guide-call-log-details.mdx index 77bf8c52f..39c1adb0c 100644 --- a/ui-kit/ios/guide-call-log-details.mdx +++ b/ui-kit/ios/guide-call-log-details.mdx @@ -239,3 +239,17 @@ func showEmptyState() { Review the call log components in the UIKit library + +## Related Guides + + + + Display call history list + + + Overview of calling capabilities + + + Handle call events + + diff --git a/ui-kit/ios/guide-group-chat.mdx b/ui-kit/ios/guide-group-chat.mdx index 4d26f85ab..1f5d8a79d 100644 --- a/ui-kit/ios/guide-group-chat.mdx +++ b/ui-kit/ios/guide-group-chat.mdx @@ -380,3 +380,17 @@ avatarView.set(image: UIImage(named: "default_group_avatar")) Browse the Group Details implementation
+ +## Related Guides + + + + Display and manage group list + + + View and manage group membership + + + Handle group and membership events + + diff --git a/ui-kit/ios/guide-group-ownership.mdx b/ui-kit/ios/guide-group-ownership.mdx index 4d98a700f..5f8655167 100644 --- a/ui-kit/ios/guide-group-ownership.mdx +++ b/ui-kit/ios/guide-group-ownership.mdx @@ -395,17 +395,16 @@ present(alert, animated: true) | Execute API transfer | `CometChat.transferGroupOwnership()` | `TransferOwnership.swift` | | Show/hide loading indicator | `addSpinnerView()`, `removeSpinnerView()` | `TransferOwnership.swift` | -## Related Components - -- [Groups](/ui-kit/ios/groups) - Display group list -- [Group Members](/ui-kit/ios/group-members) - Display group member list -- [Events](/ui-kit/ios/events) - Listen for chat events +## Related Guides - - Explore the transfer ownership feature in context + + Display and manage groups + + + View and manage group membership - - Review the implementation + + Complete group management guide diff --git a/ui-kit/ios/guide-message-privately.mdx b/ui-kit/ios/guide-message-privately.mdx index 857c5c5b6..c1b345cc1 100644 --- a/ui-kit/ios/guide-message-privately.mdx +++ b/ui-kit/ios/guide-message-privately.mdx @@ -14,11 +14,9 @@ The Message Privately feature allows users to long-press a message in a group ch Before implementing this feature, ensure you have: -- Completed [Getting Started](/ui-kit/ios/getting-started) setup -- CometChat UIKit v5+ installed via CocoaPods or Swift Package Manager -- Valid CometChat App ID, Region, and Auth Key -- Functional group chat via `CometChatMessageList` -- A one-on-one chat screen (`CometChatMessages` or custom) and navigation flow configured +1. Completed [Getting Started](/ui-kit/ios/getting-started) setup +2. CometChat UIKit v5+ installed +3. User logged in with `CometChatUIKit.login()` ## Components @@ -185,3 +183,17 @@ func getMessageOptions(for message: BaseMessage) -> [CometChatMessageOption] { Browse the message list component
+ +## Related Guides + + + + Display and manage users + + + View and manage conversations + + + View group membership + + diff --git a/ui-kit/ios/guide-new-chat.mdx b/ui-kit/ios/guide-new-chat.mdx index 18d9b7d1e..7b37a7ed3 100644 --- a/ui-kit/ios/guide-new-chat.mdx +++ b/ui-kit/ios/guide-new-chat.mdx @@ -298,6 +298,20 @@ groupsViewController.searchController.searchBar.placeholder = "Search teams..." - [Groups](/ui-kit/ios/groups) - Display group list - [Conversations](/ui-kit/ios/conversations) - Display conversation list +## Related Guides + + + + Display and select users + + + Display and select groups + + + View recent conversations + + + Explore the complete create-conversation flow diff --git a/ui-kit/ios/guide-overview.mdx b/ui-kit/ios/guide-overview.mdx index 01318aeb5..3b8cc90aa 100644 --- a/ui-kit/ios/guide-overview.mdx +++ b/ui-kit/ios/guide-overview.mdx @@ -6,6 +6,14 @@ description: "Index of feature guides for iOS UI Kit" This page indexes focused, task-oriented feature guides for the iOS UI Kit. Each guide shows how to implement a specific capability end-to-end using UIKit components. +## Prerequisites + +Before implementing any guide, ensure you have: + +1. Completed [Getting Started](/ui-kit/ios/getting-started) setup +2. CometChat UIKit v5+ installed +3. User logged in with `CometChatUIKit.login()` + ## When to Use These Guides Use these guides after completing [Getting Started](/ui-kit/ios/getting-started) and wiring your base conversations/messages flows. Apply them to layer feature depth without rebuilding standard patterns. @@ -30,3 +38,22 @@ Use these guides after completing [Getting Started](/ui-kit/ios/getting-started) - [Core Features](/ui-kit/ios/core-features) - Messaging, reactions, threads, and more Need another guide? Request one via the [Developer Community](http://community.cometchat.com/) or Support. + +--- + +## Related Guides + + + + Build AI-powered chat experiences + + + Create and manage group conversations + + + Start new conversations with users or groups + + + Implement threaded message replies + + diff --git a/ui-kit/ios/guide-threaded-messages.mdx b/ui-kit/ios/guide-threaded-messages.mdx index 6086f40d4..866c6aa56 100644 --- a/ui-kit/ios/guide-threaded-messages.mdx +++ b/ui-kit/ios/guide-threaded-messages.mdx @@ -16,12 +16,11 @@ Threaded messages allow users to reply to specific messages within a conversatio ## Prerequisites -Before implementing threaded messages, ensure you have: +Before implementing this feature, ensure you have: -- Completed [Getting Started](/ui-kit/ios/getting-started) setup -- CometChat UIKit v4+ installed via Swift Package Manager or CocoaPods -- Valid CometChat App ID, Region, and Auth Key -- A navigation controller configured in your project +1. Completed [Getting Started](/ui-kit/ios/getting-started) setup +2. CometChat UIKit v5+ installed +3. User logged in with `CometChatUIKit.login()` ## Components @@ -225,3 +224,17 @@ navigationItem.leftBarButtonItem = UIBarButtonItem( Browse the CometChat UIKit for iOS source code + +## Related Guides + + + + Customize the thread header component + + + Display and customize chat messages + + + Overview of messaging features + + diff --git a/ui-kit/ios/methods.mdx b/ui-kit/ios/methods.mdx index 6004762f5..d19ef0d27 100644 --- a/ui-kit/ios/methods.mdx +++ b/ui-kit/ios/methods.mdx @@ -2,6 +2,50 @@ title: "Methods" --- + +```json +{ + "category": "methods", + "wrapperClass": "CometChatUIKit", + "methodCategories": [ + { + "name": "initialization", + "methods": [ + {"name": "init", "signature": "CometChatUIKit.init(uiKitSettings: UIKitSettings, completion:)", "description": "Initialize UI Kit with settings"} + ] + }, + { + "name": "authentication", + "methods": [ + {"name": "loginWithUID", "signature": "CometChatUIKit.login(uid: String, completion:)", "description": "Login using UID and Auth Key"}, + {"name": "loginWithToken", "signature": "CometChatUIKit.login(authToken: String, completion:)", "description": "Login using Auth Token"}, + {"name": "logout", "signature": "CometChatUIKit.logout(user: User, completion:)", "description": "Logout current user"}, + {"name": "createUser", "signature": "CometChatUIKit.create(user: User, completion:)", "description": "Create new user"} + ] + }, + { + "name": "messaging", + "methods": [ + {"name": "sendTextMessage", "signature": "CometChatUIKit.sendTextMessage(message: TextMessage)", "description": "Send text message"}, + {"name": "sendMediaMessage", "signature": "CometChatUIKit.sendMediaMessage(message: MediaMessage)", "description": "Send media message"}, + {"name": "sendCustomMessage", "signature": "CometChatUIKit.sendCustomMessage(message: CustomMessage)", "description": "Send custom message"} + ] + }, + { + "name": "interactiveMessages", + "methods": [ + {"name": "sendFormMessage", "signature": "CometChatUIKit.sendFormMessage(formMessage: FormMessage, completion:)", "description": "Send form message"}, + {"name": "sendCardMessage", "signature": "CometChatUIKit.sendCardMessage(cardMessage: CardMessage, completion:)", "description": "Send card message"}, + {"name": "sendSchedulerMessage", "signature": "CometChatUIKit.sendSchedulerMessage(schedulerMessage: SchedulerMessage, completion:)", "description": "Send scheduler message"} + ] + } + ] +} +``` + + +--- + ## Overview The UI Kit's core function is to extend the [CometChat SDK](/sdk/ios/overview), translating raw data and functionality into visually appealing, easy-to-use UI components. diff --git a/ui-kit/ios/theme-introduction.mdx b/ui-kit/ios/theme-introduction.mdx index acdfe7aea..f9b13b700 100644 --- a/ui-kit/ios/theme-introduction.mdx +++ b/ui-kit/ios/theme-introduction.mdx @@ -4,6 +4,33 @@ sidebarTitle: "Introduction" description: "Create visually consistent and customizable user interfaces with CometChat theming for iOS" --- + +```json +{ + "platform": "iOS UI Kit", + "package": "CometChatUIKitSwift", + "themeSystem": { + "class": "CometChatTheme", + "description": "Global theming system for all CometChat components" + }, + "globalStyles": { + "primaryColor": "UIColor - Main accent color", + "backgroundColor": "UIColor - Background color", + "borderColor": "UIColor - Border color" + }, + "colorCustomization": { + "method": "CometChatTheme.primaryColor = UIColor", + "example": "CometChatTheme.primaryColor = UIColor(hex: \"#F76808\")" + }, + "typographyCustomization": { + "class": "CometChatTypography", + "properties": ["Body.regular", "Body.bold", "Heading.regular"], + "example": "CometChatTypography.Body.regular = UIFont.systemFont(ofSize: 18, weight: .bold)" + } +} +``` + + ## Overview Theming in CometChat for iOS allows you to create visually consistent and customizable user interfaces that align with your application's branding. The `CometChatTheme` system enables global theming, customization of colors, typography, spacing, and component-specific styles to enhance the user experience across all CometChat components. From 2065c1e0b38696919ffdb5293a4a7db83bac234f Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 11 Mar 2026 15:27:19 +0530 Subject: [PATCH 054/106] Update .gitignore --- .gitignore | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.gitignore b/.gitignore index 51b40734f..4669a449e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,15 @@ .DS_Store .kiro/ + +# IDE files +.idea/ + +# Python caches +__pycache__/ +*.pyc /codebase /doc-auditor +/docs-templates +/docs-test-suite +/prompts From acea5b3d8b5615138657b0dbeed7ddb28ff6072c Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 11 Mar 2026 15:28:12 +0530 Subject: [PATCH 055/106] Update .gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 4669a449e..82d9bf8ec 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,4 @@ __pycache__/ /doc-auditor /docs-templates /docs-test-suite -/prompts +/prompts \ No newline at end of file From c9eb2c7fcd4e6aa397ec25727ebff80f8692bcce Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 11 Mar 2026 16:48:18 +0530 Subject: [PATCH 056/106] fixes based on codebase comparison --- ui-kit/flutter/components-overview.mdx | 10 ++++++++++ ui-kit/flutter/conversations.mdx | 16 ++++++++++++++++ ui-kit/flutter/overview.mdx | 16 ++++++++++++++++ 3 files changed, 42 insertions(+) diff --git a/ui-kit/flutter/components-overview.mdx b/ui-kit/flutter/components-overview.mdx index 7fc03fe55..3dc6151d5 100644 --- a/ui-kit/flutter/components-overview.mdx +++ b/ui-kit/flutter/components-overview.mdx @@ -111,6 +111,7 @@ All components are imported from `cometchat_chat_uikit`. | CometChatMessageHeader | Toolbar with avatar, name, status, typing indicator | `user`, `group`, `backButton`, `hideBackButton` | [Message Header](/ui-kit/flutter/message-header) | | CometChatMessageList | Scrollable message list with reactions, receipts, threads | `user`, `group`, `messagesRequestBuilder`, `scrollToBottomOnNewMessages` | [Message List](/ui-kit/flutter/message-list) | | CometChatMessageComposer | Rich text input with attachments, mentions, voice notes | `user`, `group`, `onSendButtonTap`, `placeholderText` | [Message Composer](/ui-kit/flutter/message-composer) | +| CometChatMessageTemplate | Pre-defined structure for custom message bubbles | `type`, `category`, `contentView`, `headerView`, `footerView` | [Message Template](/ui-kit/flutter/message-template) | | CometChatThreadedHeader | Parent message bubble and reply count for threaded view | `parentMessage`, `onClose`, `hideReceipts` | [Threaded Header](/ui-kit/flutter/threaded-messages-header) | ### Search and AI @@ -120,6 +121,15 @@ All components are imported from `cometchat_chat_uikit`. | CometChatSearch | Real-time search input field | `onSearch`, `placeholder`, `style` | [Search](/ui-kit/flutter/search) | | CometChatAIAssistantChatHistory | AI assistant conversation history display | `user`, `group`, `style` | [AI Assistant Chat History](/ui-kit/flutter/ai-assistant-chat-history) | +### Calling + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatCallButtons | Voice and video call initiation buttons | `user`, `group`, `hideVoiceCallButton`, `hideVideoCallButton` | [Call Buttons](/ui-kit/flutter/call-buttons) | +| CometChatIncomingCall | Incoming call notification with accept/decline | `call`, `onAccept`, `onDecline` | [Incoming Call](/ui-kit/flutter/incoming-call) | +| CometChatOutgoingCall | Outgoing call screen with cancel control | `call`, `user`, `onCancelled` | [Outgoing Call](/ui-kit/flutter/outgoing-call) | +| CometChatCallLogs | Scrollable list of call history | `callLogsRequestBuilder`, `onItemClick` | [Call Logs](/ui-kit/flutter/call-logs) | + --- ## Component API Pattern diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index be2091653..9bda2cc3e 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -1187,6 +1187,9 @@ CometChatConversations( ```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + CometChatConversations( emptyStateView: (context) { return Center( @@ -1215,6 +1218,9 @@ CometChatConversations( ```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + CometChatConversations( receiptsVisibility: false, usersStatusVisibility: false, @@ -1232,6 +1238,9 @@ CometChatConversations( ```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + CometChatConversations( hideSearch: false, onSearchTap: () { @@ -1251,6 +1260,10 @@ CometChatConversations( ```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:intl/intl.dart'; + CometChatConversations( datePattern: (conversation) { final date = conversation.lastMessage?.sentAt ?? DateTime.now(); @@ -1272,6 +1285,9 @@ Configure text formatters for the conversation subtitle. See [CometChatMentionsF ```dart +import 'package:flutter/material.dart'; +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; + CometChatConversations( textFormatters: [ CometChatMentionsFormatter( diff --git a/ui-kit/flutter/overview.mdx b/ui-kit/flutter/overview.mdx index 815576fdb..5cf1f7c99 100644 --- a/ui-kit/flutter/overview.mdx +++ b/ui-kit/flutter/overview.mdx @@ -25,6 +25,16 @@ The CometChat Flutter UI Kit provides prebuilt, customizable widgets for adding --- +## Try It + + + + Clone and run the Flutter sample project + + + +--- + ## Get Started @@ -68,7 +78,13 @@ The CometChat Flutter UI Kit provides prebuilt, customizable widgets for adding Design resources and prototyping + + Common issues and fixes + Open a support ticket + + Upgrading from v4 +
From 2b2e8e9d4c676a31a68ace2063238f488553be5d Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Wed, 11 Mar 2026 17:03:22 +0530 Subject: [PATCH 057/106] Update .gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index d392eca55..035951657 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ /codebase /prompts /docs-test-suite -/doc-auditor +/doc-auditor +/docs-templates From 55683ddc3e3171d84bd176635377bac5fe8c0beb Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 12 Mar 2026 11:39:04 +0530 Subject: [PATCH 058/106] updates iOS UI Kit --- ui-kit/ios/call-buttons.mdx | 96 ++- ui-kit/ios/call-logs.mdx | 134 +++- ui-kit/ios/conversations.mdx | 555 ++++++++++++++- ui-kit/ios/group-members.mdx | 482 ++++++++++++- ui-kit/ios/groups.mdx | 244 ++++++- ui-kit/ios/incoming-call.mdx | 125 +++- ui-kit/ios/message-composer.mdx | 475 ++++++++++++- ui-kit/ios/message-header.mdx | 333 ++++++++- ui-kit/ios/message-list.mdx | 1151 ++++++++++++++++++++++++++++--- ui-kit/ios/outgoing-call.mdx | 134 +++- ui-kit/ios/search.mdx | 194 +++++- ui-kit/ios/users.mdx | 323 ++++++++- 12 files changed, 4053 insertions(+), 193 deletions(-) diff --git a/ui-kit/ios/call-buttons.mdx b/ui-kit/ios/call-buttons.mdx index c5bed3075..24010862a 100644 --- a/ui-kit/ios/call-buttons.mdx +++ b/ui-kit/ios/call-buttons.mdx @@ -6,7 +6,7 @@ description: "Provides voice and video call buttons for initiating calls with us The `CometChatCallButtons` component provides users with the ability to make calls, access call-related functionalities, and control call settings. Clicking this button typically triggers the call to be placed to the desired recipient. - + CometChatCallButtons showing voice and video call buttons for initiating calls @@ -262,7 +262,7 @@ callButton.style = callButtonStyle - + CometChatCallButtons with custom styling showing purple tinted call icons on light purple background List of properties exposed by ButtonStyle @@ -374,3 +374,95 @@ callButtons.set(controller: UIViewController) // Passing the controller is requi *** + +## Props + +All props are optional. + +--- + +### user + +The user for 1-on-1 call buttons. Pass either `user` or `group`, not both. + +| | | +|---|---| +| Type | `User?` | +| Default | `nil` | + +--- + +### group + +The group for group call buttons. Pass either `user` or `group`, not both. + +| | | +|---|---| +| Type | `Group?` | +| Default | `nil` | + +--- + +### hideVoiceCallButton + +Hides the voice call button. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +### hideVideoCallButton + +Hides the video call button. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +### outgoingCallConfiguration + +Configuration object for the internal `CometChatOutgoingCall` sub-component. + +| | | +|---|---| +| Type | `OutgoingCallConfiguration` | +| Default | `OutgoingCallConfiguration()` | + +--- + +### customSoundForCalls + +Custom sound file URL for calls. + +| | | +|---|---| +| Type | `URL?` | +| Default | `nil` | + +--- + +## Events + +Events emitted by the Call Buttons component: + +| Event | Description | +|-------|-------------| +| `onOutgoingCallAccepted` | Triggers when the outgoing call is accepted | +| `onOutgoingCallRejected` | Triggers when the outgoing call is rejected | +| `onCallEnded` | Triggers when the call ends | + +--- + +## Related Components + +- [Incoming Call](/ui-kit/ios/incoming-call) - Display incoming call interface +- [Outgoing Call](/ui-kit/ios/outgoing-call) - Display outgoing call interface +- [Call Logs](/ui-kit/ios/call-logs) - Display call history + +*** diff --git a/ui-kit/ios/call-logs.mdx b/ui-kit/ios/call-logs.mdx index 4d3721013..503e71e94 100644 --- a/ui-kit/ios/call-logs.mdx +++ b/ui-kit/ios/call-logs.mdx @@ -6,7 +6,7 @@ description: "Displays a list of call logs with call type, duration, and partici The `CometChatCallLogs` component shows the list of call logs available. By default, names are shown for all listed users, along with their avatar if available. - + CometChatCallLogs showing a list of call history with caller names, call types, and timestamps @@ -308,7 +308,7 @@ callLog.avatarStyle = customAvatarStyle - + CometChatCallLogs with custom styling showing orange title text and rounded avatar with custom background color List of properties exposed by CallLogStyle @@ -481,7 +481,7 @@ callLogs.set(listItemView: { callLog in - + CometChatCallLogs with custom list item view showing call icon, caller name, subtitle, and date @@ -595,7 +595,7 @@ callLogs.set(titleView: { callLog in **Example** - + CometChatCallLogs with custom title view showing caller name with clock icon and duration @@ -718,7 +718,7 @@ callLogs.set(leadingView: { callLog in **Example** - + CometChatCallLogs with custom leading view showing purple circular call icon button @@ -808,7 +808,7 @@ callLogs.set(subtitleView: { callLog in **Example** - + CometChatCallLogs with custom subtitle view showing call initiation timestamp @@ -894,7 +894,7 @@ callLogs.set(trailView: { callLog in **Example** - + CometChatCallLogs with custom trail view showing call timestamp on the right side @@ -955,10 +955,130 @@ class CustomTrailView: UIView { *** +--- + +## Props + +All props are optional. + +--- + +### callRequestBuilder + +Controls which call logs load and in what order. + +| | | +|---|---| +| Type | `CallLogsRequest.CallLogsBuilder?` | +| Default | `nil` | + +--- + +### hideError + +Hides the error state view. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +### hideNavigationBar + +Hides the navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +### hideLoadingState + +Hides the loading state view. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +### hideBackIcon + +Hides the back icon in the navigation bar. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +### avatarStyle + +Customizes the appearance of avatars in the call logs list. + +| | | +|---|---| +| Type | `AvatarStyle` | +| Default | `AvatarStyle()` | + +```swift +import CometChatUIKitSwift + +let customAvatarStyle = AvatarStyle() +customAvatarStyle.backgroundColor = UIColor.systemBlue +customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) + +let callLogs = CometChatCallLogs() +callLogs.avatarStyle = customAvatarStyle +``` + +--- + +## Events + +Events emitted by the Call Logs component: + +| Event | Description | +|-------|-------------| +| `onItemClick` | Triggers when a call log item is clicked | +| `onItemLongClick` | Triggers when a call log item is long pressed | +| `onBack` | Triggers when the back button is pressed | +| `onError` | Triggers when an error occurs | +| `onEmpty` | Triggers when the call logs list is empty | +| `onLoad` | Triggers when call logs are successfully loaded | + +--- + +## View Slots + +| Slot | Signature | Replaces | +|------|-----------|----------| +| `listItemView` | `(CallLog) -> UIView` | Entire list item row | +| `titleView` | `(CallLog) -> UIView` | Name / title text | +| `leadingView` | `(CallLog) -> UIView` | Avatar / left section | +| `trailView` | `(CallLog) -> UIView` | Right section with call button | +| `subtitleView` | `(CallLog) -> UIView` | Call type, direction, timestamp | + +--- + Ensure to pass and present `CometChatCallLogs`. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller. +--- + +## Related Components + +- [Incoming Call](/ui-kit/ios/incoming-call) - Display incoming call interface +- [Outgoing Call](/ui-kit/ios/outgoing-call) - Display outgoing call interface +- [Call Buttons](/ui-kit/ios/call-buttons) - Voice and video call buttons + *** diff --git a/ui-kit/ios/conversations.mdx b/ui-kit/ios/conversations.mdx index 5afcc86d4..f572914fc 100644 --- a/ui-kit/ios/conversations.mdx +++ b/ui-kit/ios/conversations.mdx @@ -6,7 +6,7 @@ description: "Display and manage all chat conversations for the logged-in user" The `CometChatConversations` component displays a list of all conversations (one-on-one and group chats) for the currently logged-in user. It shows the last message, unread count, typing indicators, and user presence in real-time. - + CometChatConversations showing a list of recent conversations with user avatars, last message previews, timestamps, and unread message badges @@ -156,7 +156,7 @@ class ChatListViewController: UIViewController { ``` - + CometChatConversations showing integration flow with conversation list navigating to messages screen --- @@ -171,7 +171,7 @@ navigationController?.pushViewController(conversations, animated: true) ``` - + CometChatConversations showing minimal render with default configuration displaying conversation list --- @@ -500,6 +500,112 @@ conversations.set(subtitleView: { conversation in }) ``` +### leadingView + +Customize the avatar / left section of the conversation row. + +| | | +|---|---| +| Signature | `(Conversation) -> UIView` | +| Replaces | Avatar / left section | + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +conversations.set(leadingView: { conversation in + let containerView = UIView() + containerView.translatesAutoresizingMaskIntoConstraints = false + + let avatarView = CometChatAvatar(image: UIImage()) + avatarView.translatesAutoresizingMaskIntoConstraints = false + + if let user = conversation.conversationWith as? User { + avatarView.setAvatar(avatarUrl: user.avatar, with: user.name ?? "") + } else if let group = conversation.conversationWith as? Group { + avatarView.setAvatar(avatarUrl: group.icon, with: group.name ?? "") + } + + containerView.addSubview(avatarView) + + // Add online indicator + let statusIndicator = UIView() + statusIndicator.backgroundColor = UIColor.systemGreen + statusIndicator.layer.cornerRadius = 6 + statusIndicator.translatesAutoresizingMaskIntoConstraints = false + containerView.addSubview(statusIndicator) + + NSLayoutConstraint.activate([ + avatarView.widthAnchor.constraint(equalToConstant: 48), + avatarView.heightAnchor.constraint(equalToConstant: 48), + avatarView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor), + avatarView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor), + statusIndicator.widthAnchor.constraint(equalToConstant: 12), + statusIndicator.heightAnchor.constraint(equalToConstant: 12), + statusIndicator.trailingAnchor.constraint(equalTo: avatarView.trailingAnchor), + statusIndicator.bottomAnchor.constraint(equalTo: avatarView.bottomAnchor) + ]) + + return containerView +}) +``` + +{/* TODO: Add screenshot showing leadingView customization */} + +### titleView + +Customize the title area that displays the conversation name. + +| | | +|---|---| +| Signature | `(Conversation) -> UIView` | +| Replaces | Name / title text area | + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +conversations.set(titleView: { conversation in + let stackView = UIStackView() + stackView.axis = .horizontal + stackView.spacing = 8 + stackView.alignment = .center + + // Name label + let nameLabel = UILabel() + nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .semibold) + nameLabel.textColor = UIColor.label + + if let user = conversation.conversationWith as? User { + nameLabel.text = user.name + } else if let group = conversation.conversationWith as? Group { + nameLabel.text = group.name + } + + stackView.addArrangedSubview(nameLabel) + + // Add verified badge for specific users + if let user = conversation.conversationWith as? User, + user.metadata?["verified"] as? Bool == true { + let badgeImage = UIImageView(image: UIImage(systemName: "checkmark.seal.fill")) + badgeImage.tintColor = UIColor.systemBlue + badgeImage.widthAnchor.constraint(equalToConstant: 16).isActive = true + badgeImage.heightAnchor.constraint(equalToConstant: 16).isActive = true + stackView.addArrangedSubview(badgeImage) + } + + return stackView +}) +``` + +{/* TODO: Add screenshot showing titleView customization */} + ### tailView Customize the right side of the conversation row (time, unread badge). Note: The setter method is `set(trailView:)`. @@ -550,6 +656,8 @@ conversations.set(trailView: { conversation in }) ``` +{/* TODO: Add screenshot showing trailingView customization */} + --- ## Styling @@ -603,7 +711,7 @@ conversations.style = customStyle ``` - + CometChatConversations with custom styling applied showing customized background, colors, and list item appearance ### Key Style Properties @@ -637,10 +745,273 @@ conversations.style = customStyle --- +## Methods + +### Swipe Action Methods + +#### set(options:) + +Sets custom swipe actions for conversation list items, replacing the default options. + +```swift +@discardableResult +public func set(options: ((_ conversation: Conversation?) -> [CometChatConversationOption])?) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `options` | `((Conversation?) -> [CometChatConversationOption])?` | Closure that returns an array of swipe action options for a conversation | + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +conversations.set(options: { conversation in + var options = [CometChatConversationOption]() + + // Add delete option + let deleteOption = CometChatConversationOption( + id: "delete", + title: "Delete", + icon: UIImage(systemName: "trash"), + backgroundColor: .systemRed + ) { conv in + // Handle delete action + print("Delete conversation: \(conv?.conversationId ?? "")") + } + options.append(deleteOption) + + return options +}) +``` + +#### add(options:) + +Adds additional swipe actions to the existing default options. + +```swift +@discardableResult +public func add(options: ((_ conversation: Conversation?) -> [CometChatConversationOption])?) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `options` | `((Conversation?) -> [CometChatConversationOption])?` | Closure that returns additional swipe action options to append | + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +conversations.add(options: { conversation in + var options = [CometChatConversationOption]() + + // Add mute option + let muteOption = CometChatConversationOption( + id: "mute", + title: "Mute", + icon: UIImage(systemName: "bell.slash"), + backgroundColor: .systemOrange + ) { conv in + print("Mute conversation: \(conv?.conversationId ?? "")") + } + options.append(muteOption) + + return options +}) +``` + +{/* TODO: Add screenshot showing swipe action options customization */} + +### Data Manipulation Methods + +#### insert(conversation:at:) + +Inserts a conversation at a specific index in the list. + +```swift +public func insert(conversation: Conversation, at index: Int) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `conversation` | `Conversation` | The conversation to insert | +| `index` | `Int` | The position at which to insert the conversation | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +// Insert a conversation at the top of the list +if let conversation = someConversation { + conversations.insert(conversation: conversation, at: 0) +} +``` + +#### getSelectedConversations() + +Returns the list of currently selected conversations when in selection mode. + +```swift +public func getSelectedConversations() -> [Conversation] +``` + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() +conversations.selectionMode = .multiple + +// Get selected conversations +let selectedConversations = conversations.getSelectedConversations() +print("Selected \(selectedConversations.count) conversations") +``` + +#### getConversationList() + +Returns the complete list of conversations currently displayed. + +```swift +public func getConversationList() -> [Conversation] +``` + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let conversations = CometChatConversations() + +// Get all conversations in the list +let allConversations = conversations.getConversationList() +print("Total conversations: \(allConversations.count)") +``` + +### Connection Methods + +#### connect() + +Manually establishes the WebSocket connection for real-time updates. Use this when you need to reconnect after calling `disconnect()`. + +```swift +public func connect() +``` + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +// Reconnect to receive real-time updates +conversations.connect() +``` + +#### disconnect() + +Manually disconnects the WebSocket connection. Use this when you want to temporarily stop receiving real-time updates, such as when the view is not visible. + +```swift +public func disconnect() +``` + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +// Disconnect when view is not visible +conversations.disconnect() + +// Later, reconnect when view becomes visible again +conversations.connect() +``` + +### Text Formatter Methods + +#### set(textFormatters:) + +Sets custom text formatters for processing and displaying message text in conversation subtitles. + +```swift +@discardableResult +public func set(textFormatters: [CometChatTextFormatter]) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `textFormatters` | `[CometChatTextFormatter]` | Array of text formatters to apply to message text | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +// Create custom text formatters +let mentionFormatter = CometChatMentionTextFormatter() +let urlFormatter = CometChatURLTextFormatter() + +conversations.set(textFormatters: [mentionFormatter, urlFormatter]) +``` + +--- + ## Props All props are optional. Sorted alphabetically. +### avatarStyle + +Customizes the appearance of avatars in conversation list items. + +| | | +|---|---| +| Type | `AvatarStyle` | +| Default | `AvatarStyle()` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor.systemBlue +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) +avatarStyle.borderWidth = 1 +avatarStyle.borderColor = UIColor.systemGray4 + +conversations.set(avatarStyle: avatarStyle) +``` + +### badgeStyle + +Customizes the appearance of unread message count badges. + +| | | +|---|---| +| Type | `BadgeStyle` | +| Default | `BadgeStyle()` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +let badgeStyle = BadgeStyle() +badgeStyle.backgroundColor = UIColor.systemRed +badgeStyle.textColor = UIColor.white +badgeStyle.textFont = UIFont.systemFont(ofSize: 12, weight: .bold) +badgeStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 10) + +conversations.set(badgeStyle: badgeStyle) +``` + ### conversationRequestBuilder Custom request builder for filtering which conversations appear. @@ -650,6 +1021,49 @@ Custom request builder for filtering which conversations appear. | Type | `ConversationRequest.ConversationRequestBuilder?` | | Default | `nil` | +### dateStyle + +Customizes the appearance of date/time labels in conversation list items. + +| | | +|---|---| +| Type | `DateStyle` | +| Default | `DateStyle()` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +let dateStyle = DateStyle() +dateStyle.textColor = UIColor.secondaryLabel +dateStyle.textFont = UIFont.systemFont(ofSize: 12) + +conversations.set(dateStyle: dateStyle) +``` + +### dateTimeFormatter + +Custom formatter for date/time display in conversation list items. + +| | | +|---|---| +| Type | `CometChatDateTimeFormatter?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +let dateTimeFormatter = CometChatDateTimeFormatter() +dateTimeFormatter.todayFormat = "h:mm a" +dateTimeFormatter.yesterdayFormat = "'Yesterday'" +dateTimeFormatter.otherFormat = "MMM d" + +conversations.dateTimeFormatter = dateTimeFormatter +``` + ### customSoundForMessages Custom sound URL for new message notifications. @@ -668,6 +1082,22 @@ Disables notification sounds for new messages. | Type | `Bool` | | Default | `false` | +### disableTyping + +Disables typing indicators in the conversation list. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() +conversations.disableTyping = true +``` + ### hideBackButton Hides the back button in the navigation bar. @@ -731,6 +1161,80 @@ Hides online/offline status indicators. | Type | `Bool` | | Default | `false` | +### onSearchClick + +Callback triggered when the search button is clicked. + +| | | +|---|---| +| Type | `(() -> Void)?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +conversations.set(onSearchClick: { [weak self] in + // Handle search button click + self?.presentSearchViewController() +}) +``` + +### privateGroupIcon + +Custom icon for private group conversations. + +| | | +|---|---| +| Type | `UIImage?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() +conversations.privateGroupIcon = UIImage(systemName: "lock.fill") +``` + +### protectedGroupIcon + +Custom icon for password-protected group conversations. + +| | | +|---|---| +| Type | `UIImage?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() +conversations.protectedGroupIcon = UIImage(systemName: "lock.shield.fill") +``` + +### receiptStyle + +Customizes the appearance of message receipt indicators (sent, delivered, read). + +| | | +|---|---| +| Type | `ReceiptStyle` | +| Default | `ReceiptStyle()` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +let receiptStyle = ReceiptStyle() +receiptStyle.sentIconTint = UIColor.systemGray +receiptStyle.deliveredIconTint = UIColor.systemGray +receiptStyle.readIconTint = UIColor.systemBlue + +conversations.set(receiptStyle: receiptStyle) +``` + ### selectionMode Sets the selection mode for multi-select functionality. @@ -740,6 +1244,28 @@ Sets the selection mode for multi-select functionality. | Type | `SelectionMode` | | Default | `.none` | +### statusIndicatorStyle + +Customizes the appearance of online/offline status indicators. + +| | | +|---|---| +| Type | `StatusIndicatorStyle` | +| Default | `StatusIndicatorStyle()` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +let statusIndicatorStyle = StatusIndicatorStyle() +statusIndicatorStyle.backgroundColor = UIColor.systemGreen +statusIndicatorStyle.borderWidth = 2 +statusIndicatorStyle.borderColor = UIColor.white + +conversations.set(statusIndicatorStyle: statusIndicatorStyle) +``` + ### textFormatters Array of text formatters for customizing message text display. @@ -749,6 +1275,27 @@ Array of text formatters for customizing message text display. | Type | `[CometChatTextFormatter]` | | Default | `[]` | +### typingIndicatorStyle + +Customizes the appearance of typing indicators in conversation list items. + +| | | +|---|---| +| Type | `TypingIndicatorStyle` | +| Default | `TypingIndicatorStyle()` | + +```swift +import CometChatUIKitSwift + +let conversations = CometChatConversations() + +let typingIndicatorStyle = TypingIndicatorStyle() +typingIndicatorStyle.textColor = UIColor.systemGray +typingIndicatorStyle.textFont = UIFont.italicSystemFont(ofSize: 14) + +conversations.set(typingIndicatorStyle: typingIndicatorStyle) +``` + --- ## Events diff --git a/ui-kit/ios/group-members.mdx b/ui-kit/ios/group-members.mdx index 88a9515ca..88630ebf5 100644 --- a/ui-kit/ios/group-members.mdx +++ b/ui-kit/ios/group-members.mdx @@ -6,7 +6,7 @@ description: "Display and manage members of a CometChat group" The `CometChatGroupMembers` component displays all members of a group with their roles (owner, admin, moderator, participant). It supports member management actions like kick, ban, and role changes based on the logged-in user's permissions. - + CometChatGroupMembers showing a list of group members with their avatars, names, and role badges indicating owner, admin, moderator, and participant status @@ -39,6 +39,7 @@ The `CometChatGroupMembers` component displays all members of a group with their "onItemLongClick": "(GroupMember, IndexPath) -> Void", "onBack": "() -> Void", "onSelection": "([GroupMember]) -> Void", + "onSelectedItemProceed": "([GroupMember]) -> Void", "onError": "(CometChatException) -> Void", "onEmpty": "() -> Void", "onLoad": "([GroupMember]) -> Void" @@ -57,6 +58,10 @@ The `CometChatGroupMembers` component displays all members of a group with their "selection": { "selectionMode": { "type": "SelectionMode", "default": ".none" } }, + "styling": { + "avatarStyle": { "type": "AvatarStyle", "default": "AvatarStyle()" }, + "statusIndicatorStyle": { "type": "StatusIndicatorStyle", "default": "StatusIndicatorStyle()" } + }, "viewSlots": { "listItemView": "(GroupMember?) -> UIView", "leadingView": "(GroupMember?) -> UIView", @@ -68,6 +73,20 @@ The `CometChatGroupMembers` component displays all members of a group with their "loadingStateView": "UIView" } }, + "methods": { + "swipeActions": { + "set(options:)": "((Group, GroupMember?) -> [CometChatGroupMemberOption])? - Sets custom swipe actions", + "add(options:)": "((Group, GroupMember?) -> [CometChatGroupMemberOption])? - Adds additional swipe actions" + }, + "dataManipulation": { + "add(groupMember:)": "GroupMember - Adds a member to the list", + "update(groupMember:)": "GroupMember - Updates a member in the list", + "remove(groupMember:)": "GroupMember - Removes a member from the list", + "insert(groupMember:at:)": "GroupMember, Int - Inserts a member at a specific index", + "clearList()": "Void - Removes all members from the list", + "size()": "Int - Returns the number of members in the list" + } + }, "events": [ { "name": "ccGroupMemberKicked", @@ -157,7 +176,7 @@ class GroupDetailViewController: UIViewController { ``` - + CometChatGroupMembers displaying group members in a navigation context with search functionality and member details --- @@ -174,7 +193,7 @@ present(navController, animated: true) ``` - + CometChatGroupMembers showing minimal render with default configuration displaying member list --- @@ -408,6 +427,143 @@ class MyViewController: UIViewController, CometChatGroupEventListener { | `errorStateView` | - | `UIView` | Error state display | | `loadingStateView` | - | `UIView` | Loading state display | +### set(titleView:) + +Replaces the default title view (member name) with a custom implementation. + +| | | +|---|---| +| Signature | `(GroupMember?) -> UIView` | +| Replaces | Member name / title text | + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(titleView: { member in + let containerView = UIView() + + let nameLabel = UILabel() + nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .semibold) + nameLabel.textColor = UIColor.label + nameLabel.text = member?.name ?? "Unknown" + nameLabel.translatesAutoresizingMaskIntoConstraints = false + + let roleLabel = UILabel() + roleLabel.font = UIFont.systemFont(ofSize: 10, weight: .medium) + roleLabel.textColor = UIColor.white + roleLabel.textAlignment = .center + roleLabel.layer.cornerRadius = 4 + roleLabel.clipsToBounds = true + roleLabel.translatesAutoresizingMaskIntoConstraints = false + + // Set role badge color based on scope + switch member?.scope { + case .owner: + roleLabel.text = " Owner " + roleLabel.backgroundColor = UIColor.systemOrange + case .admin: + roleLabel.text = " Admin " + roleLabel.backgroundColor = UIColor.systemPurple + case .moderator: + roleLabel.text = " Mod " + roleLabel.backgroundColor = UIColor.systemBlue + default: + roleLabel.text = "" + roleLabel.backgroundColor = .clear + } + + containerView.addSubview(nameLabel) + containerView.addSubview(roleLabel) + + NSLayoutConstraint.activate([ + nameLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + nameLabel.centerYAnchor.constraint(equalTo: containerView.centerYAnchor), + + roleLabel.leadingAnchor.constraint(equalTo: nameLabel.trailingAnchor, constant: 8), + roleLabel.centerYAnchor.constraint(equalTo: containerView.centerYAnchor) + ]) + + return containerView +}) +``` + +### set(leadingView:) + +Replaces the default leading view (avatar) with a custom implementation. + +| | | +|---|---| +| Signature | `(GroupMember?) -> UIView` | +| Replaces | Avatar / left section | + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(leadingView: { member in + let containerView = UIView() + containerView.translatesAutoresizingMaskIntoConstraints = false + + // Create avatar + let avatar = CometChatAvatar(image: UIImage()) + avatar.setAvatar(avatarUrl: member?.avatar, with: member?.name ?? "") + avatar.translatesAutoresizingMaskIntoConstraints = false + + // Create role badge overlay + let badgeView = UIView() + badgeView.layer.cornerRadius = 10 + badgeView.layer.borderWidth = 2 + badgeView.layer.borderColor = UIColor.white.cgColor + badgeView.translatesAutoresizingMaskIntoConstraints = false + + // Set badge color based on scope + switch member?.scope { + case .owner: + badgeView.backgroundColor = UIColor.systemOrange + case .admin: + badgeView.backgroundColor = UIColor.systemPurple + case .moderator: + badgeView.backgroundColor = UIColor.systemBlue + default: + badgeView.backgroundColor = UIColor.systemGray + } + + let badgeIcon = UIImageView(image: UIImage(systemName: "star.fill")) + badgeIcon.tintColor = .white + badgeIcon.translatesAutoresizingMaskIntoConstraints = false + badgeView.addSubview(badgeIcon) + + containerView.addSubview(avatar) + containerView.addSubview(badgeView) + + NSLayoutConstraint.activate([ + avatar.topAnchor.constraint(equalTo: containerView.topAnchor), + avatar.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), + avatar.widthAnchor.constraint(equalToConstant: 40), + avatar.heightAnchor.constraint(equalToConstant: 40), + + badgeView.widthAnchor.constraint(equalToConstant: 20), + badgeView.heightAnchor.constraint(equalToConstant: 20), + badgeView.bottomAnchor.constraint(equalTo: avatar.bottomAnchor, constant: 2), + badgeView.trailingAnchor.constraint(equalTo: avatar.trailingAnchor, constant: 2), + + badgeIcon.centerXAnchor.constraint(equalTo: badgeView.centerXAnchor), + badgeIcon.centerYAnchor.constraint(equalTo: badgeView.centerYAnchor), + badgeIcon.widthAnchor.constraint(equalToConstant: 12), + badgeIcon.heightAnchor.constraint(equalToConstant: 12) + ]) + + return containerView +}) +``` + ### subtitleView Customize the subtitle area below the member name. @@ -435,6 +591,8 @@ groupMembers.set(subtitleView: { member in }) ``` +{/* TODO: Add screenshot showing subtitleView customization */} + ### tailView Customize the right side of the member row (role badge). Note: The setter method is `set(trailView:)`. @@ -478,6 +636,8 @@ groupMembers.set(trailView: { member in }) ``` +{/* TODO: Add screenshot showing trailingView customization */} + --- ## Styling @@ -521,7 +681,7 @@ groupMembers.style = customStyle ``` - + CometChatGroupMembers with custom styling showing modified background color, title appearance, and list item styling ### Key Style Properties @@ -554,6 +714,27 @@ groupMembers.style = customStyle All props are optional except `group`. Sorted alphabetically. +### avatarStyle + +Customizes the appearance of member avatars in the list. + +| | | +|---|---| +| Type | `AvatarStyle` | +| Default | `AvatarStyle()` | + +```swift +import CometChatUIKitSwift + +let groupMembers = CometChatGroupMembers(group: group) + +let avatarStyle = AvatarStyle() +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) +avatarStyle.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.1) + +groupMembers.avatarStyle = avatarStyle +``` + ### group (required) The group whose members to display. @@ -662,6 +843,28 @@ Sets the selection mode for multi-select functionality. | Type | `SelectionMode` | | Default | `.none` | +### statusIndicatorStyle + +Customizes the appearance of online/offline status indicators. + +| | | +|---|---| +| Type | `StatusIndicatorStyle` | +| Default | `StatusIndicatorStyle()` | + +```swift +import CometChatUIKitSwift + +let groupMembers = CometChatGroupMembers(group: group) + +let statusIndicatorStyle = StatusIndicatorStyle() +statusIndicatorStyle.backgroundColor = UIColor.systemGreen +statusIndicatorStyle.borderWidth = 2 +statusIndicatorStyle.borderColor = UIColor.white + +groupMembers.statusIndicatorStyle = statusIndicatorStyle +``` + --- ## Events @@ -674,6 +877,273 @@ Sets the selection mode for multi-select functionality. --- +## Methods + +### Swipe Action Methods + +#### set(options:) + +Sets custom swipe actions for group member list items, replacing the default options. These options appear when the user swipes on a member cell. + +```swift +@discardableResult +public func set(options: ((_ group: Group, _ member: GroupMember?) -> [CometChatGroupMemberOption])?) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `options` | `((Group, GroupMember?) -> [CometChatGroupMemberOption])?` | Closure that returns an array of swipe action options for a member | + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(options: { group, member in + var options = [CometChatGroupMemberOption]() + + // Add message option + let messageOption = CometChatGroupMemberOption( + id: "message", + title: "Message", + icon: UIImage(systemName: "message"), + backgroundColor: .systemBlue, + onClick: { member, group, section, option, controller in + let messages = CometChatMessages() + messages.set(user: member) + controller.navigationController?.pushViewController(messages, animated: true) + } + ) + options.append(messageOption) + + // Add remove option + let removeOption = CometChatGroupMemberOption( + id: "remove", + title: "Remove", + icon: UIImage(systemName: "trash"), + backgroundColor: .systemRed, + onClick: { member, group, section, option, controller in + print("Remove member: \(member.name ?? "")") + } + ) + options.append(removeOption) + + return options +}) +``` + +#### add(options:) + +Adds additional swipe actions to the existing default options. + +```swift +@discardableResult +public func add(options: ((_ group: Group, _ member: GroupMember?) -> [CometChatGroupMemberOption])?) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `options` | `((Group, GroupMember?) -> [CometChatGroupMemberOption])?` | Closure that returns additional swipe action options to append | + +```swift +import UIKit +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.add(options: { group, member in + var options = [CometChatGroupMemberOption]() + + // Add promote option + let promoteOption = CometChatGroupMemberOption( + id: "promote", + title: "Promote", + icon: UIImage(systemName: "arrow.up.circle"), + backgroundColor: .systemGreen, + onClick: { member, group, section, option, controller in + print("Promote member: \(member.name ?? "")") + } + ) + options.append(promoteOption) + + return options +}) +``` + +### Data Manipulation Methods + +#### add(groupMember:) + +Adds a new group member to the list. + +```swift +@discardableResult +public func add(groupMember: GroupMember) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `groupMember` | `GroupMember` | The group member to add to the list | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +// Add a member programmatically +let newMember = GroupMember(uid: "user-123", groupMemberScope: .participant) +newMember.name = "John Doe" +groupMembers.add(groupMember: newMember) +``` + +#### update(groupMember:) + +Updates an existing group member in the list. + +```swift +@discardableResult +public func update(groupMember: GroupMember) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `groupMember` | `GroupMember` | The group member with updated information | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +// Update a member's information +if var existingMember = memberToUpdate { + existingMember.scope = .admin + groupMembers.update(groupMember: existingMember) +} +``` + +#### remove(groupMember:) + +Removes a group member from the list. + +```swift +@discardableResult +public func remove(groupMember: GroupMember) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `groupMember` | `GroupMember` | The group member to remove from the list | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +// Remove a member from the UI +groupMembers.remove(groupMember: memberToRemove) +``` + +#### insert(groupMember:at:) + +Inserts a group member at a specific index in the list. + +```swift +@discardableResult +public func insert(groupMember: GroupMember, at index: Int) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `groupMember` | `GroupMember` | The group member to insert | +| `index` | `Int` | The position at which to insert the member | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) + +// Insert a member at the top of the list +let newMember = GroupMember(uid: "user-456", groupMemberScope: .participant) +newMember.name = "Jane Smith" +groupMembers.insert(groupMember: newMember, at: 0) +``` + +#### clearList() + +Removes all group members from the list. + +```swift +public func clearList() +``` + +```swift +import CometChatUIKitSwift + +let groupMembers = CometChatGroupMembers(group: group) + +// Clear all members from the list +groupMembers.clearList() +``` + +#### size() + +Returns the number of group members currently in the list. + +```swift +public func size() -> Int +``` + +```swift +import CometChatUIKitSwift + +let groupMembers = CometChatGroupMembers(group: group) + +// Get the count of members +let memberCount = groupMembers.size() +print("Total members: \(memberCount)") +``` + +--- + +## Selection Properties + +### onSelectedItemProceed + +Callback that fires when the user proceeds with selected members in selection mode. This is typically triggered when the user taps a "Done" or "Proceed" button after selecting members. + +| | | +|---|---| +| Type | `(([GroupMember]) -> Void)?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let groupMembers = CometChatGroupMembers(group: group) +groupMembers.selectionMode = .multiple + +groupMembers.set(onSelectedItemProceed: { [weak self] selectedMembers in + print("Proceeding with \(selectedMembers.count) selected members") + + for member in selectedMembers { + print("Selected: \(member.name ?? "")") + } + + // Perform action with selected members + self?.handleSelectedMembers(selectedMembers) +}) +``` + +--- + ## Custom Swipe Options Add custom actions when swiping on a member: @@ -714,7 +1184,7 @@ groupMembers.setOptions(options: { group, member in ``` - + CometChatGroupMembers showing custom swipe options with Remove and Message action buttons revealed on a member row --- @@ -762,7 +1232,7 @@ class GroupMembersViewController: UIViewController { ``` - + CometChatGroupMembers showing custom navigation bar menu with an add member button in the top right corner --- diff --git a/ui-kit/ios/groups.mdx b/ui-kit/ios/groups.mdx index 02959af1d..5f67dbd23 100644 --- a/ui-kit/ios/groups.mdx +++ b/ui-kit/ios/groups.mdx @@ -6,7 +6,7 @@ description: "Display and manage a list of groups with search functionality" The `CometChatGroups` component displays a searchable list of all available groups. It shows group names, avatars, member counts, and group type indicators (public/private/password-protected). Users can browse, join, and interact with group conversations. - + CometChatGroups showing a searchable list of groups with avatars, names, member counts, and group type indicators @@ -39,6 +39,7 @@ The `CometChatGroups` component displays a searchable list of all available grou "onItemLongClick": "(Group, IndexPath) -> Void", "onBack": "() -> Void", "onSelection": "([Group]) -> Void", + "onSelectedItemProceed": "([Group]) -> Void", "onError": "(CometChatException) -> Void", "onEmpty": "() -> Void", "onLoad": "([Group]) -> Void" @@ -53,7 +54,13 @@ The `CometChatGroups` component displays a searchable list of all available grou "hideLoadingState": { "type": "Bool", "default": false } }, "selection": { - "selectionMode": { "type": "SelectionMode", "default": ".none" } + "selectionMode": { "type": "SelectionMode", "default": ".none" }, + "selectionLimit": { "type": "Int", "default": 0 }, + "selectedCellCount": { "type": "Int", "default": 0 } + }, + "styling": { + "avatarStyle": { "type": "AvatarStyle", "default": "AvatarStyle()" }, + "statusIndicatorStyle": { "type": "StatusIndicatorStyle", "default": "StatusIndicatorStyle()" } }, "viewSlots": { "listItemView": "(Group) -> UIView", @@ -160,7 +167,7 @@ class GroupsViewController: UIViewController { ``` - + CometChatGroups showing integration with navigation controller and group selection handling --- @@ -176,7 +183,7 @@ present(navController, animated: true) ``` - + CometChatGroups showing minimal render with default configuration displaying group list --- @@ -289,6 +296,31 @@ groups.set(onSelection: { [weak self] selectedGroups in }) ``` +#### onSelectedItemProceed + +Fires when the user confirms their selection by tapping the proceed/submit button. Use this to handle the final selection action. + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let groups = CometChatGroups() +groups.selectionMode = .multiple +groups.selectionLimit = 5 + +groups.onSelectedItemProceed = { [weak self] selectedGroups in + guard let self = self else { return } + + // Handle the selected groups + for group in selectedGroups { + print("Selected group: \(group.name ?? "")") + } + + // Proceed with the selection + self.processSelectedGroups(selectedGroups) +} +``` + #### onError Fires when an error occurs while loading groups. @@ -340,6 +372,7 @@ groups.set(onLoad: { groups in | `set(onItemLongClick:)` | Triggered on long press | Show options menu | | `set(onBack:)` | Triggered when back button is pressed | Custom navigation | | `set(onSelection:)` | Triggered in selection mode | Multi-select groups | +| `onSelectedItemProceed` | Triggered when selection is confirmed | Process selected groups | | `set(onError:)` | Triggered when an error occurs | Show error alert | | `set(onEmpty:)` | Triggered when list is empty | Show empty state | | `set(onLoad:)` | Triggered when groups load | Analytics tracking | @@ -433,7 +466,7 @@ groups.set(listItemView: { group in ``` - + CometChatGroups with custom listItemView showing customized group row with avatar, title, member count, and join button You can create a `CustomGroupCell` as a custom `UIView`: @@ -558,7 +591,7 @@ groups.set(leadingView: { group in ``` - + CometChatGroups with custom leadingView showing customized avatar area with icon and join button You can create a `CustomLeadingView` as a custom `UIView`: @@ -625,7 +658,7 @@ groups.set(titleView: { group in ``` - + CometChatGroups with custom titleView showing group name with public badge indicator You can create a `CustomTitleView` as a custom `UIView`: @@ -719,7 +752,7 @@ groups.set(subtitleView: { group in ``` - + CometChatGroups with custom subtitleView showing member count and group description text You can create a `CustomSubtitleView` as a custom `UIView`: @@ -761,7 +794,7 @@ groups.set(trailView: { group in ``` - + CometChatGroups with custom trailingView showing joined status badge on the right side You can create a `CustomTrailView` as a custom `UIView`: @@ -859,7 +892,7 @@ groups.set(emptyView: emptyLabel) ### set(options:) -Define custom options for each group. This method allows you to return an array of `CometChatGroupOption` based on the group object. +Define custom swipe options for each group. This method allows you to return an array of `CometChatGroupOption` based on the group object. These options appear when the user swipes on a group cell. ```swift import CometChatUIKitSwift @@ -868,13 +901,37 @@ import CometChatSDK let groups = CometChatGroups() groups.set(options: { group in - return [CometChatGroupOption]() + // Create a custom delete option + let deleteOption = CometChatGroupOption( + id: "delete", + title: "Delete", + icon: UIImage(systemName: "trash"), + backgroundColor: .systemRed, + onClick: { group, section, option, controller in + // Handle delete action + print("Delete group: \(group.name ?? "")") + } + ) + + // Create a custom mute option + let muteOption = CometChatGroupOption( + id: "mute", + title: "Mute", + icon: UIImage(systemName: "bell.slash"), + backgroundColor: .systemOrange, + onClick: { group, section, option, controller in + // Handle mute action + print("Mute group: \(group.name ?? "")") + } + ) + + return [deleteOption, muteOption] }) ``` ### add(options:) -Dynamically add options to groups. This method lets you return additional `CometChatGroupOption` elements. +Dynamically add additional swipe options to groups while preserving the default options. This method lets you return additional `CometChatGroupOption` elements that will be appended to the existing options. ```swift import CometChatUIKitSwift @@ -883,10 +940,77 @@ import CometChatSDK let groups = CometChatGroups() groups.add(options: { group in - return [ArchiveOption()] + // Add a custom archive option + let archiveOption = CometChatGroupOption( + id: "archive", + title: "Archive", + icon: UIImage(systemName: "archivebox"), + backgroundColor: .systemBlue, + onClick: { group, section, option, controller in + // Handle archive action + print("Archive group: \(group.name ?? "")") + } + ) + + return [archiveOption] +}) +``` + +--- + +## Data Manipulation Methods + +### showJoiningGroupAlert(for:) + +Displays an alert dialog when a user attempts to join a password-protected group. This method shows a prompt for the user to enter the group password. + +```swift +public func showJoiningGroupAlert(for group: Group) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `group` | `Group` | The password-protected group to join | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let groups = CometChatGroups() + +// Show joining alert for a password-protected group +groups.set(onItemClick: { [weak self] group, indexPath in + if group.groupType == .password && !group.hasJoined { + self?.groups.showJoiningGroupAlert(for: group) + } else { + // Navigate to group chat + } }) ``` +### hideJoiningGroupAlert(completion:) + +Dismisses the joining group alert dialog programmatically. Use this when you need to close the alert without user interaction. + +```swift +public func hideJoiningGroupAlert(completion: (() -> Void)? = nil) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `completion` | `(() -> Void)?` | Optional closure called after the alert is dismissed | + +```swift +import CometChatUIKitSwift + +let groups = CometChatGroups() + +// Hide the joining alert with a completion handler +groups.hideJoiningGroupAlert { + print("Alert dismissed") +} +``` + --- ## Styling @@ -965,6 +1089,29 @@ groups.style = customStyle All props are optional. Sorted alphabetically. +### avatarStyle + +Customizes the appearance of avatars in group list items. + +| | | +|---|---| +| Type | `AvatarStyle` | +| Default | `AvatarStyle()` | + +```swift +import CometChatUIKitSwift + +let groups = CometChatGroups() + +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor.systemBlue +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) +avatarStyle.borderWidth = 1 +avatarStyle.borderColor = UIColor.systemGray4 + +groups.set(avatarStyle: avatarStyle) +``` + ### groupsRequestBuilder Custom request builder for filtering groups. @@ -1046,6 +1193,55 @@ Custom request builder for search functionality. | Type | `GroupsRequest.GroupsRequestBuilder?` | | Default | `nil` | +### selectedCellCount + +Returns the count of currently selected groups when in selection mode. + +| | | +|---|---| +| Type | `Int` | +| Default | `0` | + +```swift +import CometChatUIKitSwift + +let groups = CometChatGroups() +groups.selectionMode = .multiple + +// Get the count of selected groups +let selectedCount = groups.selectedCellCount +print("Selected \(selectedCount) groups") +``` + +### selectionLimit + +Sets the maximum number of groups that can be selected in selection mode. When the limit is reached, further selections are disabled. + +| | | +|---|---| +| Type | `Int` | +| Default | `0` (unlimited) | + +```swift +import CometChatUIKitSwift + +let groups = CometChatGroups() +groups.selectionMode = .multiple + +// Limit selection to 5 groups +groups.selectionLimit = 5 + +// Handle selection confirmation +groups.onSelectedItemProceed = { selectedGroups in + print("Selected \(selectedGroups.count) groups") + + // Process the selected groups + for group in selectedGroups { + print("Group: \(group.name ?? "")") + } +} +``` + ### selectionMode Sets the selection mode for multi-select functionality. @@ -1055,6 +1251,28 @@ Sets the selection mode for multi-select functionality. | Type | `SelectionMode` | | Default | `.none` | +### statusIndicatorStyle + +Customizes the appearance of group type status indicators. + +| | | +|---|---| +| Type | `StatusIndicatorStyle` | +| Default | `StatusIndicatorStyle()` | + +```swift +import CometChatUIKitSwift + +let groups = CometChatGroups() + +let statusIndicatorStyle = StatusIndicatorStyle() +statusIndicatorStyle.backgroundColor = UIColor.systemGreen +statusIndicatorStyle.borderWidth = 2 +statusIndicatorStyle.borderColor = UIColor.white + +groups.set(statusIndicatorStyle: statusIndicatorStyle) +``` + --- ## Events diff --git a/ui-kit/ios/incoming-call.mdx b/ui-kit/ios/incoming-call.mdx index ce5235521..dbf566017 100644 --- a/ui-kit/ios/incoming-call.mdx +++ b/ui-kit/ios/incoming-call.mdx @@ -6,7 +6,7 @@ description: "Display and handle incoming voice and video calls" The `CometChatIncomingCall` component serves as a visual representation when the user receives an incoming call, such as a voice call or video call, providing options to answer or decline the call. - + CometChatIncomingCall showing incoming call interface with caller avatar, name, and accept/reject buttons @@ -270,7 +270,7 @@ incomingCall.avatarStyle = customAvatarStyle - + CometChatIncomingCall with custom styling showing custom fonts and rounded button corners List of properties exposed by IncomingCallStyle: @@ -332,7 +332,7 @@ cometChatIncomingCall.set(listItemView: { call in Demonstration: - + CometChatIncomingCall with custom list item view showing compact call notification with avatar and action buttons You can create a CustomListItemView as a custom `UIView`: @@ -457,7 +457,7 @@ cometChatIncomingCall.set(leadingView: { call in Demonstration: - + CometChatIncomingCall with custom leading view showing PRO USER badge with star icon You can create a CustomLeadingView as a custom `UIView`: @@ -542,7 +542,7 @@ cometChatIncomingCall.set(titleView: { call in Demonstration: - + CometChatIncomingCall with custom title view showing Voice Call label with Important tag You can create a `CustomTitleView` as a custom `UIView` which we will inflate in `setTitleView()`: @@ -628,6 +628,121 @@ class CustomTitleView: UIView { --- +## Props + +All props are optional unless noted. + +--- + +### call + +The incoming call object to display. + +| | | +|---|---| +| Type | `Call` | +| Default | Auto-detected | + +--- + +### disableSoundForCalls + +Disables the incoming call ringtone. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +### customSoundForCalls + +Custom sound file URL for incoming calls. + +| | | +|---|---| +| Type | `URL?` | +| Default | `nil` | + +--- + +### avatarStyle + +Customizes the appearance of the caller's avatar. + +| | | +|---|---| +| Type | `AvatarStyle` | +| Default | `AvatarStyle()` | + +```swift +import CometChatUIKitSwift + +let customAvatarStyle = AvatarStyle() +customAvatarStyle.backgroundColor = UIColor.systemPurple +customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) + +let incomingCall = CometChatIncomingCall() +incomingCall.avatarStyle = customAvatarStyle +``` + +--- + +## Events + +Events emitted by the Incoming Call component: + +| Event | Description | +|-------|-------------| +| `onIncomingCallAccepted` | Triggers when the logged-in user accepts the incoming call | +| `onIncomingCallRejected` | Triggers when the logged-in user rejects the incoming call | +| `onCallEnded` | Triggers when the call ends | + +--- + +## View Slots + +| Slot | Signature | Replaces | +|------|-----------|----------| +| `listItemView` | `(Call) -> UIView` | Entire list item | +| `leadingView` | `(Call) -> UIView` | Avatar / left section | +| `titleView` | `(Call) -> UIView` | Name / title text | +| `subtitleView` | `(Call) -> UIView` | Subtitle text (call type) | +| `trailingView` | `(Call) -> UIView` | Right section | + +### subtitleView + +You can customize the subtitle view of an incoming call component using the property below. + + + +```swift +cometChatIncomingCall.set(subtitleView: { call in + let view = CustomSubtitleView() + return view +}) +``` + + + +### trailingView + +You can customize the trailing view of an incoming call component using the property below. + + + +```swift +cometChatIncomingCall.set(trailingView: { call in + let view = CustomTrailingView() + return view +}) +``` + + + +--- + ## Related Components - [Outgoing Call](/ui-kit/ios/outgoing-call) - Display outgoing call interface diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index 82df42aba..5465cf9c4 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -6,7 +6,7 @@ description: "Enable users to write and send text, media, and custom messages" The `CometChatMessageComposer` component enables users to write and send messages including text, images, videos, audio, files, and custom messages. It supports attachments, voice recording, stickers, mentions, and AI-powered features. - + CometChatMessageComposer showing the default message input field with attachment, voice recording, and send buttons @@ -49,6 +49,9 @@ The `CometChatMessageComposer` component enables users to write and send message "hideVoiceRecordingButton": { "type": "Bool", "default": false }, "hideStickersButton": { "type": "Bool", "default": false }, "hideSendButton": { "type": "Bool", "default": false }, + "hideAIButton": { "type": "Bool", "default": false }, + "hideHeaderView": { "type": "Bool", "default": false }, + "hideFooterView": { "type": "Bool", "default": false }, "hideImageAttachmentOption": { "type": "Bool", "default": false }, "hideVideoAttachmentOption": { "type": "Bool", "default": false }, "hideAudioAttachmentOption": { "type": "Bool", "default": false }, @@ -61,18 +64,32 @@ The `CometChatMessageComposer` component enables users to write and send message "disableTypingEvents": { "type": "Bool", "default": false }, "disableMentions": { "type": "Bool", "default": false }, "disableSoundForMessages": { "type": "Bool", "default": false }, - "maxLine": { "type": "Int", "default": 5 } + "maxLine": { "type": "Int", "default": 5 }, + "placeholderText": { "type": "String", "default": "Type a message..." } }, "viewSlots": { "headerView": "(User?, Group?) -> UIView", "footerView": "(User?, Group?) -> UIView", "sendButtonView": "(User?, Group?) -> UIView", + "auxillaryButtonView": "(User?, Group?) -> UIView", "attachmentOptions": "(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]" }, "formatting": { "textFormatters": "[CometChatTextFormatter]" + }, + "styling": { + "mediaRecorderStyle": { "type": "MediaRecorderStyle", "default": "MediaRecorderStyle()" }, + "attachmentSheetStyle": { "type": "AttachmentSheetStyle", "default": "AttachmentSheetStyle()" }, + "suggestionsStyle": { "type": "SuggestionsStyle", "default": "SuggestionsStyle()" }, + "aiOptionsStyle": { "type": "AIOptionsStyle", "default": "AIOptionsStyle()" }, + "mentionStyle": { "type": "MentionStyle", "default": "MentionStyle()" } } }, + "methods": { + "set(textFormatter:)": "Sets a custom text formatter for the composer", + "setDisableMentionAll(_:)": "Disables or enables the @all mention feature", + "setMentionAllLabel(_:_:)": "Customizes the label for @all mentions" + }, "events": [], "sdkListeners": [], "compositionExample": { @@ -134,7 +151,7 @@ class ChatViewController: UIViewController { ``` - + CometChatMessageComposer showing integration within a chat view controller with user configuration --- @@ -150,7 +167,7 @@ messageComposer.set(user: user) ``` - + CometChatMessageComposer showing minimal configuration with user set for direct messaging --- @@ -225,11 +242,17 @@ messageComposer.set(onError: { error in | `headerView` | `(User?, Group?) -> UIView` | Header above composer | | `footerView` | `(User?, Group?) -> UIView` | Footer below composer | | `sendButtonView` | `(User?, Group?) -> UIView` | Send button | +| `auxillaryButtonView` | `(User?, Group?) -> UIView` | Auxiliary button area | | `attachmentOptions` | `(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]` | Attachment menu options | -### headerView +### set(headerView:) + +Replaces the default header with a custom view above the composer. -Add a custom header above the composer. +| | | +|---|---| +| Signature | `(User?, Group?) -> UIView` | +| Replaces | Default header above composer | ```swift import UIKit @@ -244,7 +267,7 @@ messageComposer.set(headerView: { user, group in ``` - + CometChatMessageComposer with custom header view showing a notification pause message above the input field You can create a `CustomHeaderView` as a custom `UIView`: @@ -303,9 +326,50 @@ class CustomHeaderView: UIView { } ``` -### sendButtonView +### set(footerView:) -Replace the default send button with a custom view. +Replaces the default footer with a custom view below the composer. + +| | | +|---|---| +| Signature | `(User?, Group?) -> UIView` | +| Replaces | Default footer below composer | + +```swift +import UIKit +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +messageComposer.set(footerView: { user, group in + let footerView = UIView() + footerView.backgroundColor = UIColor.systemGray6 + + let label = UILabel() + label.text = "Messages are end-to-end encrypted" + label.font = UIFont.systemFont(ofSize: 12) + label.textColor = UIColor.secondaryLabel + label.textAlignment = .center + + footerView.addSubview(label) + label.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + label.centerXAnchor.constraint(equalTo: footerView.centerXAnchor), + label.centerYAnchor.constraint(equalTo: footerView.centerYAnchor) + ]) + + return footerView +}) +``` + +### set(sendButtonView:) + +Replaces the default send button with a custom view. + +| | | +|---|---| +| Signature | `(User?, Group?) -> UIView` | +| Replaces | Default send button | ```swift import UIKit @@ -323,9 +387,53 @@ messageComposer.set(sendButtonView: { user, group in }) ``` -### attachmentOptions +{/* TODO: Add screenshot showing sendButtonView customization */} -Customize the attachment menu options. +### set(auxillaryButtonView:) + +Replaces the auxiliary button area with a custom view. The auxiliary button is typically used for additional actions like AI features. + +| | | +|---|---| +| Signature | `(User?, Group?) -> UIView` | +| Replaces | Default auxiliary button area | + +```swift +import UIKit +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +messageComposer.set(auxillaryButtonView: { user, group in + let stackView = UIStackView() + stackView.axis = .horizontal + stackView.spacing = 8 + + let aiButton = UIButton(type: .system) + aiButton.setImage(UIImage(systemName: "sparkles"), for: .normal) + aiButton.tintColor = UIColor.systemPurple + + let emojiButton = UIButton(type: .system) + emojiButton.setImage(UIImage(systemName: "face.smiling"), for: .normal) + emojiButton.tintColor = UIColor.systemOrange + + stackView.addArrangedSubview(aiButton) + stackView.addArrangedSubview(emojiButton) + + return stackView +}) +``` + +{/* TODO: Add screenshot showing auxiliaryButtonView customization */} + +### set(attachmentOptions:) + +Customizes the attachment menu options with custom actions. + +| | | +|---|---| +| Signature | `(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]` | +| Replaces | Default attachment menu options | ```swift import UIKit @@ -367,10 +475,23 @@ messageComposer.set(attachmentOptions: { user, group, controller in } ) - return [photoAction, cameraAction, locationAction] + let documentAction = CometChatMessageComposerAction( + id: "document", + text: "Document", + startIcon: UIImage(systemName: "doc"), + startIconTint: UIColor.systemIndigo, + textColor: UIColor.label, + onActionClick: { + print("Document selected") + } + ) + + return [photoAction, cameraAction, locationAction, documentAction] }) ``` +{/* TODO: Add screenshot showing attachmentOptions customization */} + --- ## Styling @@ -414,7 +535,7 @@ messageComposer.style = customStyle ``` - + CometChatMessageComposer with custom styling showing modified background color and orange send button ### Key Style Properties @@ -441,6 +562,118 @@ messageComposer.style = customStyle | `voiceRecordingImage` | `UIImage?` | System mic icon | Voice recording icon | | `voiceRecordingImageTint` | `UIColor` | `CometChatTheme.iconColorSecondary` | Voice recording tint | +### Style Properties + +#### mediaRecorderStyle + +Customizes the appearance of the media recorder (voice recording) interface. + +| | | +|---|---| +| Type | `MediaRecorderStyle` | +| Default | `MediaRecorderStyle()` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +let mediaRecorderStyle = MediaRecorderStyle() +mediaRecorderStyle.backgroundColor = UIColor.systemBackground +mediaRecorderStyle.recordButtonTint = UIColor.systemRed +mediaRecorderStyle.timerTextColor = UIColor.label + +messageComposer.mediaRecorderStyle = mediaRecorderStyle +``` + +#### attachmentSheetStyle + +Customizes the appearance of the attachment options sheet. + +| | | +|---|---| +| Type | `AttachmentSheetStyle` | +| Default | `AttachmentSheetStyle()` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +let attachmentSheetStyle = AttachmentSheetStyle() +attachmentSheetStyle.backgroundColor = UIColor.systemBackground +attachmentSheetStyle.iconTint = UIColor.systemBlue +attachmentSheetStyle.titleColor = UIColor.label + +messageComposer.attachmentSheetStyle = attachmentSheetStyle +``` + +#### suggestionsStyle + +Customizes the appearance of the suggestions view (for mentions and other suggestions). + +| | | +|---|---| +| Type | `SuggestionsStyle` | +| Default | `SuggestionsStyle()` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +let suggestionsStyle = SuggestionsStyle() +suggestionsStyle.backgroundColor = UIColor.systemBackground +suggestionsStyle.textColor = UIColor.label +suggestionsStyle.separatorColor = UIColor.separator + +messageComposer.suggestionsStyle = suggestionsStyle +``` + +#### aiOptionsStyle + +Customizes the appearance of the AI options menu. + +| | | +|---|---| +| Type | `AIOptionsStyle` | +| Default | `AIOptionsStyle()` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +let aiOptionsStyle = AIOptionsStyle() +aiOptionsStyle.backgroundColor = UIColor.systemBackground +aiOptionsStyle.iconTint = UIColor.systemPurple +aiOptionsStyle.titleColor = UIColor.label + +messageComposer.aiOptionsStyle = aiOptionsStyle +``` + +#### mentionStyle + +Customizes the appearance of mentions in the composer. + +| | | +|---|---| +| Type | `MentionStyle` | +| Default | `MentionStyle()` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +let mentionStyle = MentionStyle() +mentionStyle.textColor = UIColor.systemBlue +mentionStyle.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.1) +mentionStyle.font = UIFont.systemFont(ofSize: 16, weight: .medium) + +messageComposer.mentionStyle = mentionStyle +``` + ### Customization Matrix | What to change | Where | Property/API | Example | @@ -450,9 +683,22 @@ messageComposer.style = customStyle | Input text style | Style | `textFiledColor`, `textFiledFont` | Custom colors and fonts | | Compose box look | Style | `composeBoxBackgroundColor`, `composeBoxBorderColor` | Custom styling | | Attachment icon | Style | `attachmentImage`, `attachmentImageTint` | Custom icon | +| Media recorder | Style | `mediaRecorderStyle` | Custom MediaRecorderStyle | +| Attachment sheet | Style | `attachmentSheetStyle` | Custom AttachmentSheetStyle | +| Suggestions | Style | `suggestionsStyle` | Custom SuggestionsStyle | +| AI options | Style | `aiOptionsStyle` | Custom AIOptionsStyle | +| Mentions | Style | `mentionStyle` | Custom MentionStyle | | Hide attachment | Property | `hideAttachmentButton` | `composer.hideAttachmentButton = true` | | Hide voice recording | Property | `hideVoiceRecordingButton` | `composer.hideVoiceRecordingButton = true` | +| Hide AI button | Property | `hideAIButton` | `composer.hideAIButton = true` | +| Hide header | Property | `hideHeaderView` | `composer.hideHeaderView = true` | +| Hide footer | Property | `hideFooterView` | `composer.hideFooterView = true` | +| Placeholder text | Property | `placeholderText` | `composer.placeholderText = "..."` | | Custom send button | View Slot | `set(sendButtonView:)` | See Custom View Slots | +| Custom header | View Slot | `set(headerView:)` | See Custom View Slots | +| Custom footer | View Slot | `set(footerView:)` | See Custom View Slots | +| Custom auxiliary | View Slot | `set(auxillaryButtonView:)` | See Custom View Slots | +| Custom attachments | View Slot | `set(attachmentOptions:)` | See Custom View Slots | --- @@ -496,6 +742,22 @@ Hides the attachment button. | Type | `Bool` | | Default | `false` | +### hideAIButton + +Hides the AI button in the composer. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideAIButton = true +``` + ### hideAudioAttachmentOption Hides the audio attachment option. @@ -507,49 +769,116 @@ Hides the audio attachment option. ### hideCollaborativeDocumentOption -Hides the collaborative document option. +Hides the collaborative document option in the attachment menu. | | | |---|---| | Type | `Bool` | | Default | `false` | +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideCollaborativeDocumentOption = true +``` + ### hideCollaborativeWhiteboardOption -Hides the collaborative whiteboard option. +Hides the collaborative whiteboard option in the attachment menu. | | | |---|---| | Type | `Bool` | | Default | `false` | +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideCollaborativeWhiteboardOption = true +``` + ### hideFileAttachmentOption -Hides the file attachment option. +Hides the file attachment option in the attachment menu. | | | |---|---| | Type | `Bool` | | Default | `false` | +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideFileAttachmentOption = true +``` + +### hideFooterView + +Hides the footer view below the composer. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideFooterView = true +``` + +### hideHeaderView + +Hides the header view above the composer. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideHeaderView = true +``` + ### hideImageAttachmentOption -Hides the image attachment option. +Hides the image attachment option in the attachment menu. | | | |---|---| | Type | `Bool` | | Default | `false` | +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideImageAttachmentOption = true +``` + ### hidePollsOption -Hides the polls option. +Hides the polls option in the attachment menu. | | | |---|---| | Type | `Bool` | | Default | `false` | +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hidePollsOption = true +``` + ### hideSendButton Hides the send button. @@ -559,6 +888,13 @@ Hides the send button. | Type | `Bool` | | Default | `false` | +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideSendButton = true +``` + ### hideStickersButton Hides the stickers button. @@ -568,15 +904,29 @@ Hides the stickers button. | Type | `Bool` | | Default | `false` | +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideStickersButton = true +``` + ### hideVideoAttachmentOption -Hides the video attachment option. +Hides the video attachment option in the attachment menu. | | | |---|---| | Type | `Bool` | | Default | `false` | +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.hideVideoAttachmentOption = true +``` + ### hideVoiceRecordingButton Hides the voice recording button. @@ -595,6 +945,22 @@ Sets the maximum number of lines for the composer input before scrolling. | Type | `Int` | | Default | `5` | +### placeholderText + +Sets the placeholder text displayed in the composer input field when empty. + +| | | +|---|---| +| Type | `String` | +| Default | `"Type a message..."` | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() +messageComposer.placeholderText = "Write your message here..." +``` + ### textFormatters Array of text formatters for customizing text display (e.g., mentions). @@ -606,6 +972,77 @@ Array of text formatters for customizing text display (e.g., mentions). --- +## Text Formatter and Mention Methods + +### set(textFormatter:) + +Sets a custom text formatter for the composer input. + +```swift +@discardableResult +public func set(textFormatter: CometChatTextFormatter) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `textFormatter` | `CometChatTextFormatter` | The text formatter to apply | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +let mentionFormatter = MentionTextFormatter(trackingCharacter: "@") +messageComposer.set(textFormatter: mentionFormatter) +``` + +### setDisableMentionAll(_:) + +Disables or enables the @all mention feature that notifies all group members. + +```swift +@discardableResult +public func setDisableMentionAll(_ disable: Bool) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `disable` | `Bool` | Whether to disable the @all mention feature | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +// Disable @all mentions +messageComposer.setDisableMentionAll(true) +``` + +### setMentionAllLabel(_:_:) + +Customizes the label displayed for @all mentions in the suggestions list. + +```swift +@discardableResult +public func setMentionAllLabel(_ title: String, _ subtitle: String) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `title` | `String` | The title for the @all mention | +| `subtitle` | `String` | The subtitle for the @all mention | + +```swift +import CometChatUIKitSwift + +let messageComposer = CometChatMessageComposer() + +// Customize the @all mention label +messageComposer.setMentionAllLabel("Everyone", "Notify all members in this group") +``` + +--- + ## Events The MessageComposer component does not emit any global UI events. diff --git a/ui-kit/ios/message-header.mdx b/ui-kit/ios/message-header.mdx index 611d7f976..56f85b14d 100644 --- a/ui-kit/ios/message-header.mdx +++ b/ui-kit/ios/message-header.mdx @@ -6,7 +6,7 @@ description: "Display user or group details with typing indicators and navigatio The `CometChatMessageHeader` component displays user or group details in the toolbar including avatar, name, status, and typing indicators. It also provides navigation controls and call buttons. - + CometChatMessageHeader showing user avatar, name, online status, and call buttons in the navigation bar @@ -36,13 +36,26 @@ The `CometChatMessageHeader` component displays user or group details in the too }, "callbacks": { "onBack": "() -> Void", - "onError": "(CometChatException) -> Void" + "onError": "(CometChatException) -> Void", + "onAiChatHistoryClicked": "() -> Void", + "onAiNewChatClicked": "() -> Void" }, "visibility": { "hideBackButton": { "type": "Bool", "default": false }, "hideUserStatus": { "type": "Bool", "default": false }, "hideVideoCallButton": { "type": "Bool", "default": false }, - "hideVoiceCallButton": { "type": "Bool", "default": false } + "hideVoiceCallButton": { "type": "Bool", "default": false }, + "hideNewChatButton": { "type": "Bool", "default": false }, + "hideChatHistoryButton": { "type": "Bool", "default": false }, + "disableTyping": { "type": "Bool", "default": false } + }, + "style": { + "avatarStyle": { "type": "AvatarStyle", "default": "AvatarStyle()" }, + "statusIndicatorStyle": { "type": "StatusIndicatorStyle", "default": "StatusIndicatorStyle()" }, + "typingIndicatorStyle": { "type": "TypingIndicatorStyle", "default": "TypingIndicatorStyle()" } + }, + "formatting": { + "dateTimeFormatter": { "type": "CometChatDateTimeFormatter?", "default": "nil" } }, "viewSlots": { "listItemView": "(User?, Group?) -> UIView", @@ -52,6 +65,15 @@ The `CometChatMessageHeader` component displays user or group details in the too "trailView": "(User?, Group?) -> UIView" } }, + "methods": { + "connection": { + "connect()": "Establishes WebSocket connection for real-time updates", + "disconnect()": "Disconnects WebSocket connection" + }, + "menuCustomization": { + "set(options:)": "((User?, Group?) -> [CometChatMessageHeaderOption])? - Sets custom menu options" + } + }, "events": [], "sdkListeners": [ "onUserOnline", @@ -104,7 +126,7 @@ class ChatViewController: UIViewController { ``` - + CometChatMessageHeader showing user avatar, name, online status, and call buttons in the navigation bar --- @@ -120,7 +142,7 @@ messageHeader.set(user: user) ``` - + CometChatMessageHeader showing minimal render with user details and default styling --- @@ -179,6 +201,8 @@ messageHeader.set(onError: { error in ## Custom View Slots +{/* TODO: Add screenshot showing auxiliaryButtonView customization - Note: iOS MessageHeader uses trailView instead of auxiliaryButtonView (which is Android-specific). The trailView screenshot below demonstrates equivalent functionality for customizing the right side action buttons area. */} + | Slot | Signature | Replaces | |------|-----------|----------| | `listItemView` | `(User?, Group?) -> UIView` | Entire header content | @@ -336,7 +360,7 @@ messageHeader.set(leadingView: { user, group in ``` - + CometChatMessageHeader with custom leadingView showing avatar with Admin badge overlay You can create a `CustomLeadingView` as a custom `UIView`: @@ -419,7 +443,7 @@ messageHeader.set(titleView: { user, group in ``` - + CometChatMessageHeader with custom titleView showing group name with Public badge You can create a `CustomTitleView` as a custom `UIView`: @@ -539,7 +563,7 @@ messageHeader.set(trailView: { user, group in ``` - + CometChatMessageHeader with custom trailView showing video call, voice call, and bookmark buttons You can create a `CustomTrailView` as a custom `UIView`: @@ -648,7 +672,7 @@ messageHeader.style = customStyle ``` - + CometChatMessageHeader with custom instance styling showing modified background color and text appearance ### Key Style Properties @@ -667,7 +691,9 @@ messageHeader.style = customStyle | `backButtonIcon` | `UIImage?` | System chevron | Back button icon | | `privateGroupBadgeImageTintColor` | `UIColor` | `CometChatTheme.iconColorSecondary` | Private group badge tint | | `passwordProtectedGroupBadgeImageTintColor` | `UIColor` | `CometChatTheme.iconColorSecondary` | Password group badge tint | -| `avatarStyle` | `AvatarStyle` | Default avatar style | Avatar customization | +| `avatarStyle` | `AvatarStyle` | `AvatarStyle()` | Avatar customization | +| `statusIndicatorStyle` | `StatusIndicatorStyle` | `StatusIndicatorStyle()` | Online/offline status indicator customization | +| `typingIndicatorStyle` | `TypingIndicatorStyle` | `TypingIndicatorStyle()` | Typing indicator customization | ### Customization Matrix @@ -678,9 +704,119 @@ messageHeader.style = customStyle | Subtitle appearance | Style | `subtitleTextColor`, `subtitleTextFont` | Custom colors and fonts | | Back button | Style | `backButtonIcon`, `backButtonImageTintColor` | Custom icon and color | | Avatar look | Style | `avatarStyle` | `AvatarStyle()` with custom radius | +| Status indicator | Style | `statusIndicatorStyle` | `StatusIndicatorStyle()` with custom colors | +| Typing indicator | Style | `typingIndicatorStyle` | `TypingIndicatorStyle()` with custom font | | Hide back button | Property | `hideBackButton` | `header.hideBackButton = true` | | Hide status | Property | `hideUserStatus` | `header.hideUserStatus = true` | +| Disable typing | Property | `disableTyping` | `header.disableTyping = true` | +| Hide AI buttons | Property | `hideNewChatButton`, `hideChatHistoryButton` | `header.hideNewChatButton = true` | | Custom subtitle | View Slot | `set(subtitleView:)` | See Custom View Slots | +| Custom menu options | Method | `set(options:)` | See Menu Customization | + +--- + +## Connection Management + +Manually control the WebSocket connection for the message header. + +### connect() + +Establishes the WebSocket connection for real-time updates. Use this when you need to manually reconnect after disconnecting. + +```swift +@discardableResult +public func connect() -> Self +``` + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() + +// Manually connect to receive real-time updates +messageHeader.connect() +``` + +### disconnect() + +Disconnects the WebSocket connection. Use this when you want to temporarily stop receiving real-time updates, such as when the view is not visible. + +```swift +@discardableResult +public func disconnect() -> Self +``` + +```swift +import UIKit +import CometChatUIKitSwift + +class ChatViewController: UIViewController { + + private var messageHeader: CometChatMessageHeader! + + override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + messageHeader.disconnect() + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + messageHeader.connect() + } +} +``` + +--- + +## Menu Customization + +### set(options:) + +Sets custom menu options for the message header. These options appear in the header's menu (typically accessed via a more button or long press). + +```swift +@discardableResult +public func set(options: ((_ user: User?, _ group: Group?) -> [CometChatMessageHeaderOption])?) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `options` | `((User?, Group?) -> [CometChatMessageHeaderOption])?` | Closure that returns an array of menu options based on the current user or group | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let messageHeader = CometChatMessageHeader() + +messageHeader.set(options: { user, group in + var options = [CometChatMessageHeaderOption]() + + // Add a custom "View Profile" option + let viewProfileOption = CometChatMessageHeaderOption( + id: "view_profile", + title: "View Profile", + icon: UIImage(systemName: "person.circle") + ) { user, group in + // Handle view profile action + print("View profile tapped") + } + options.append(viewProfileOption) + + // Add a custom "Mute Notifications" option + let muteOption = CometChatMessageHeaderOption( + id: "mute_notifications", + title: "Mute Notifications", + icon: UIImage(systemName: "bell.slash") + ) { user, group in + // Handle mute action + print("Mute notifications tapped") + } + options.append(muteOption) + + return options +}) +``` --- @@ -688,6 +824,67 @@ messageHeader.style = customStyle All props are optional. Sorted alphabetically. +### avatarStyle + +Customizes the appearance of the avatar in the message header. + +| | | +|---|---| +| Type | `AvatarStyle` | +| Default | `AvatarStyle()` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() + +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor.systemBlue +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) +avatarStyle.borderWidth = 2 +avatarStyle.borderColor = UIColor.white + +messageHeader.set(avatarStyle: avatarStyle) +``` + +### dateTimeFormatter + +Custom formatter for date/time display in the message header (e.g., "Last seen at..."). + +| | | +|---|---| +| Type | `CometChatDateTimeFormatter?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() + +let dateTimeFormatter = CometChatDateTimeFormatter() +dateTimeFormatter.todayFormat = "h:mm a" +dateTimeFormatter.yesterdayFormat = "'Yesterday at' h:mm a" +dateTimeFormatter.otherFormat = "MMM d, yyyy" + +messageHeader.dateTimeFormatter = dateTimeFormatter +``` + +### disableTyping + +Disables typing indicators in the message header. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() +messageHeader.disableTyping = true +``` + ### hideBackButton Hides the back button in the header. @@ -697,6 +894,38 @@ Hides the back button in the header. | Type | `Bool` | | Default | `false` | +### hideChatHistoryButton + +Hides the AI chat history button in the header. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() +messageHeader.hideChatHistoryButton = true +``` + +### hideNewChatButton + +Hides the AI new chat button in the header. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() +messageHeader.hideNewChatButton = true +``` + ### hideUserStatus Hides the user status (online/offline/last active). @@ -724,6 +953,90 @@ Hides the voice call button. | Type | `Bool` | | Default | `false` | +### onAiChatHistoryClicked + +Callback triggered when the AI chat history button is clicked. + +| | | +|---|---| +| Type | `(() -> Void)?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() + +messageHeader.set(onAiChatHistoryClicked: { [weak self] in + // Handle AI chat history button click + self?.presentAiChatHistory() +}) +``` + +### onAiNewChatClicked + +Callback triggered when the AI new chat button is clicked. + +| | | +|---|---| +| Type | `(() -> Void)?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() + +messageHeader.set(onAiNewChatClicked: { [weak self] in + // Handle AI new chat button click + self?.startNewAiChat() +}) +``` + +### statusIndicatorStyle + +Customizes the appearance of the online/offline status indicator. + +| | | +|---|---| +| Type | `StatusIndicatorStyle` | +| Default | `StatusIndicatorStyle()` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() + +let statusIndicatorStyle = StatusIndicatorStyle() +statusIndicatorStyle.backgroundColor = UIColor.systemGreen +statusIndicatorStyle.borderWidth = 2 +statusIndicatorStyle.borderColor = UIColor.white +statusIndicatorStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 6) + +messageHeader.set(statusIndicatorStyle: statusIndicatorStyle) +``` + +### typingIndicatorStyle + +Customizes the appearance of the typing indicator in the message header subtitle. + +| | | +|---|---| +| Type | `TypingIndicatorStyle` | +| Default | `TypingIndicatorStyle()` | + +```swift +import CometChatUIKitSwift + +let messageHeader = CometChatMessageHeader() + +let typingIndicatorStyle = TypingIndicatorStyle() +typingIndicatorStyle.textColor = UIColor.systemGray +typingIndicatorStyle.textFont = UIFont.italicSystemFont(ofSize: 13) + +messageHeader.set(typingIndicatorStyle: typingIndicatorStyle) +``` + --- ## Events diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index e20864a09..e6b63d20a 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -6,7 +6,7 @@ description: "Display and manage real-time chat messages with various message ty The `CometChatMessageList` component displays a scrollable list of messages in a conversation. It supports text messages, media messages, reactions, threads, and real-time updates for new messages, edits, and deletions. - + CometChatMessageList showing a scrollable list of chat messages with text bubbles, timestamps, and read receipts in a conversation view @@ -172,7 +172,7 @@ class ChatViewController: UIViewController { ``` - + CometChatMessageList integrated within a chat view controller showing message bubbles with thread replies and reaction handling --- @@ -188,7 +188,7 @@ messageList.set(user: user) ``` - + CometChatMessageList showing minimal render with default configuration displaying messages for a user conversation --- @@ -354,20 +354,215 @@ messageList.set(onLoad: { messages in --- +## Data Manipulation Methods + +Programmatically manage messages in the list using these methods. + +### add(message:) + +Adds a new message to the message list. + +```swift +@discardableResult +public func add(message: BaseMessage) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | `BaseMessage` | The message to add to the list | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let messageList = CometChatMessageList() + +// Add a message programmatically +let textMessage = TextMessage(receiverUid: "user-id", text: "Hello!", receiverType: .user) +messageList.add(message: textMessage) +``` + +### update(message:) + +Updates an existing message in the list. + +```swift +@discardableResult +public func update(message: BaseMessage) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | `BaseMessage` | The message with updated content | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let messageList = CometChatMessageList() + +// Update a message after editing +if let editedMessage = existingMessage as? TextMessage { + editedMessage.text = "Updated message text" + messageList.update(message: editedMessage) +} +``` + +### remove(message:) + +Removes a message from the list without deleting it from the server. + +```swift +@discardableResult +public func remove(message: BaseMessage) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | `BaseMessage` | The message to remove from the list | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let messageList = CometChatMessageList() + +// Remove a message from the UI +messageList.remove(message: messageToRemove) +``` + +### delete(message:) + +Deletes a message from both the list and the server. + +```swift +@discardableResult +public func delete(message: BaseMessage) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `message` | `BaseMessage` | The message to delete | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let messageList = CometChatMessageList() + +// Delete a message permanently +messageList.delete(message: messageToDelete) +``` + +### clearList() + +Removes all messages from the list. + +```swift +@discardableResult +public func clearList() -> Self +``` + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +// Clear all messages from the list +messageList.clearList() +``` + +### isEmpty() + +Checks if the message list is empty. + +```swift +public func isEmpty() -> Bool +``` + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +// Check if list is empty +if messageList.isEmpty() { + print("No messages in the list") +} +``` + +--- + +## Connection Management + +Manually control the WebSocket connection for the message list. + +### connect() + +Establishes the WebSocket connection for real-time updates. Use this when you need to manually reconnect after disconnecting. + +```swift +@discardableResult +public func connect() -> Self +``` + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +// Manually connect to receive real-time updates +messageList.connect() +``` + +### disconnect() + +Disconnects the WebSocket connection. Use this when you want to temporarily stop receiving real-time updates, such as when the view is not visible. + +```swift +@discardableResult +public func disconnect() -> Self +``` + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +// Disconnect when view disappears +override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + messageList.disconnect() +} + +// Reconnect when view appears +override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + messageList.connect() +} +``` + +--- + ## Custom View Slots | Slot | Signature | Replaces | |------|-----------|----------| -| `headerView` | `() -> UIView` | Header above message list | -| `footerView` | `() -> UIView` | Footer below message list | -| `emptyStateView` | `() -> UIView` | Empty state display | -| `errorStateView` | `() -> UIView` | Error state display | -| `loadingStateView` | `() -> UIView` | Loading state display | -| `newMessageIndicatorView` | `() -> UIView` | New message indicator | +| `headerView` | `UIView` | Header above message list | +| `footerView` | `UIView` | Footer below message list | +| `emptyView` | `UIView` | Empty state display | +| `errorView` | `UIView` | Error state display | +| `loadingView` | `UIView` | Loading state display | +| `newMessageIndicatorView` | `UIView` | New message indicator | -### headerView +### set(headerView:) -Add a custom header above the message list. +Replaces the default header with a custom view. + +| | | +|---|---| +| Signature | `(UIView) -> Self` | +| Replaces | Default header above message list | ```swift import UIKit @@ -387,9 +582,16 @@ headerView.addSubview(label) messageList.set(headerView: headerView) ``` -### footerView +{/* TODO: Add screenshot showing headerView customization */} + +### set(footerView:) -Add a custom footer below the message list. +Replaces the default footer with a custom view. + +| | | +|---|---| +| Signature | `(UIView) -> Self` | +| Replaces | Default footer below message list | ```swift import UIKit @@ -417,9 +619,16 @@ footerView.addSubview(quickRepliesStack) messageList.set(footerView: footerView) ``` -### emptyStateView +{/* TODO: Add screenshot showing footerView customization */} + +### set(emptyView:) -Customize the view shown when there are no messages. +Replaces the default empty state view with a custom view. + +| | | +|---|---| +| Signature | `(UIView) -> Self` | +| Replaces | Default empty state when no messages exist | ```swift import UIKit @@ -442,9 +651,14 @@ emptyView.addSubview(label) messageList.set(emptyView: emptyView) ``` -### loadingStateView +### set(errorView:) -Customize the loading indicator. +Replaces the default error state view with a custom view. + +| | | +|---|---| +| Signature | `(UIView) -> Self` | +| Replaces | Default error state when loading fails | ```swift import UIKit @@ -452,16 +666,29 @@ import CometChatUIKitSwift let messageList = CometChatMessageList() -let loadingView = UIActivityIndicatorView(style: .large) -loadingView.color = UIColor.systemBlue -loadingView.startAnimating() +let errorView = UIView() +let errorLabel = UILabel() +errorLabel.text = "Something went wrong!" +errorLabel.textColor = .red +errorLabel.textAlignment = .center -messageList.set(loadingView: loadingView) +let retryButton = UIButton(type: .system) +retryButton.setTitle("Retry", for: .normal) + +errorView.addSubview(errorLabel) +errorView.addSubview(retryButton) + +messageList.set(errorView: errorView) ``` -### errorStateView +### set(loadingView:) -Customize the error state view. +Replaces the default loading indicator with a custom view. + +| | | +|---|---| +| Signature | `(UIView) -> Self` | +| Replaces | Default loading indicator | ```swift import UIKit @@ -469,15 +696,21 @@ import CometChatUIKitSwift let messageList = CometChatMessageList() -let errorLabel = UILabel() -errorLabel.text = "Something went wrong!" -errorLabel.textColor = .red -messageList.set(errorView: errorLabel) +let loadingView = UIActivityIndicatorView(style: .large) +loadingView.color = UIColor.systemBlue +loadingView.startAnimating() + +messageList.set(loadingView: loadingView) ``` -### newMessageIndicatorView +### set(newMessageIndicatorView:) + +Replaces the default new message indicator with a custom view. -Set a custom view for the unread message indicator. +| | | +|---|---| +| Signature | `(UIView) -> Self` | +| Replaces | Default new message indicator | ```swift import UIKit @@ -535,6 +768,53 @@ let cometChatMessages = CometChatMessages() .set(textFormatter: [myCustomTextFormatter]) ``` +### set(textFormatters:) + +Sets custom text formatters for message text display. + +```swift +@discardableResult +public func set(textFormatters: [CometChatTextFormatter]) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `textFormatters` | `[CometChatTextFormatter]` | Array of text formatters to apply | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let hashtagFormatter = HashtagTextFormatter(trackingCharacter: "#") +let mentionFormatter = MentionTextFormatter(trackingCharacter: "@") + +messageList.set(textFormatters: [hashtagFormatter, mentionFormatter]) +``` + +### setMentionAllLabel(_:_:) + +Customizes the label displayed for @all mentions. + +```swift +@discardableResult +public func setMentionAllLabel(_ title: String, _ subtitle: String) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `title` | `String` | The title for the @all mention | +| `subtitle` | `String` | The subtitle for the @all mention | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +// Customize the @all mention label +messageList.setMentionAllLabel("Everyone", "Notify all members") +``` + You can create a custom text formatter: ```swift @@ -586,106 +866,569 @@ class MyCustomTextFormatter: CometChatTextFormatter { return attrString } - override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) { - // Handle text tap action - } -} + override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) { + // Handle text tap action + } +} +``` + +--- + +## AI Features + +Configure AI-powered features for the message list. + +### enableSmartReplies + +Enables AI-powered smart reply suggestions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.enableSmartReplies = true +``` + +### enableConversationStarters + +Enables AI-powered conversation starter suggestions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.enableConversationStarters = true +``` + +### enableConversationSummary + +Enables AI-powered conversation summary feature. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.enableConversationSummary = true +``` + +### set(smartRepliesKeywords:) + +Sets keywords that trigger smart reply suggestions. + +```swift +@discardableResult +public func set(smartRepliesKeywords: [String]) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `smartRepliesKeywords` | `[String]` | Keywords that trigger smart replies | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +// Set keywords that trigger smart replies +messageList.set(smartRepliesKeywords: ["help", "question", "support"]) +``` + +### set(smartRepliesDelayDuration:) + +Sets the delay duration before showing smart reply suggestions. + +```swift +@discardableResult +public func set(smartRepliesDelayDuration: TimeInterval) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `smartRepliesDelayDuration` | `TimeInterval` | Delay in seconds before showing suggestions | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +// Set a 2-second delay before showing smart replies +messageList.set(smartRepliesDelayDuration: 2.0) +``` + +--- + +## Reactions Configuration + +Configure how reactions are displayed and behave in the message list. + +### reactionsConfiguration + +Configuration object for the reactions feature. + +| | | +|---|---| +| Type | `ReactionsConfiguration` | +| Default | `ReactionsConfiguration()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let reactionsConfig = ReactionsConfiguration() +reactionsConfig.reactionLimit = 5 +reactionsConfig.showReactionCount = true + +messageList.reactionsConfiguration = reactionsConfig +``` + +### reactionListConfiguration + +Configuration object for the reaction list display. + +| | | +|---|---| +| Type | `ReactionListConfiguration` | +| Default | `ReactionListConfiguration()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let reactionListConfig = ReactionListConfiguration() +reactionListConfig.showUserNames = true + +messageList.reactionListConfiguration = reactionListConfig +``` + +### quickReactionsConfiguration + +Configuration object for quick reactions. + +| | | +|---|---| +| Type | `QuickReactionsConfiguration` | +| Default | `QuickReactionsConfiguration()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let quickReactionsConfig = QuickReactionsConfiguration() +quickReactionsConfig.quickReactions = ["👍", "❤️", "😂", "😮", "😢"] + +messageList.quickReactionsConfiguration = quickReactionsConfig +``` + +### messageInformationConfiguration + +Configuration object for message information display. + +| | | +|---|---| +| Type | `MessageInformationConfiguration` | +| Default | `MessageInformationConfiguration()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let messageInfoConfig = MessageInformationConfiguration() +messageInfoConfig.showReadReceipts = true +messageInfoConfig.showDeliveryReceipts = true + +messageList.messageInformationConfiguration = messageInfoConfig +``` + +--- + +## Styling + +### Style Hierarchy + +1. Global styles (`CometChatMessageList.style`) apply to all instances +2. Instance styles override global for specific instances + +### Global Level Styling + +```swift +import UIKit +import CometChatUIKitSwift + +// Apply global styles that affect all CometChatMessageList instances +CometChatMessageList.style.backgroundColor = UIColor.systemBackground +CometChatMessageList.style.emptyStateTitleColor = UIColor.label +CometChatMessageList.style.emptyStateTitleFont = UIFont.systemFont(ofSize: 20, weight: .bold) +CometChatMessageList.style.emptyStateSubtitleColor = UIColor.secondaryLabel + +// Customize message bubble styles +CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor.systemBlue +CometChatMessageList.messageBubbleStyle.incoming.backgroundColor = UIColor.systemGray5 +``` + +### Instance Level Styling + +```swift +import UIKit +import CometChatUIKitSwift + +// Create a custom style for a specific instance +let messageListStyle = MessageListStyle() +messageListStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +messageListStyle.borderWidth = 0 +messageListStyle.borderColor = .clear + +let messageList = CometChatMessageList() +messageList.style = messageListStyle +``` + + + CometChatMessageList with custom styling applied showing modified background color and message bubble appearance + + +### Key Style Properties + +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color of the list | +| `borderWidth` | `CGFloat` | `0` | Border width for the component | +| `borderColor` | `UIColor` | `.clear` | Border color for the component | +| `cornerRadius` | `CometChatCornerStyle?` | `nil` | Corner radius for the component | +| `shimmerGradientColor1` | `UIColor` | `CometChatTheme.backgroundColor04` | First shimmer gradient color | +| `shimmerGradientColor2` | `UIColor` | `CometChatTheme.backgroundColor03` | Second shimmer gradient color | +| `emptyStateTitleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Empty state title color | +| `emptyStateTitleFont` | `UIFont` | `CometChatTypography.Heading3.bold` | Empty state title font | +| `emptyStateSubtitleColor` | `UIColor` | `CometChatTheme.textColorSecondary` | Empty state subtitle color | +| `emptyStateSubtitleFont` | `UIFont` | `CometChatTypography.Body.regular` | Empty state subtitle font | +| `errorStateTitleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Error state title color | +| `errorStateTitleFont` | `UIFont` | `CometChatTypography.Heading3.bold` | Error state title font | +| `newMessageIndicatorTextColor` | `UIColor?` | `nil` | New message indicator text color | +| `newMessageIndicatorBackgroundColor` | `UIColor?` | `nil` | New message indicator background | + +### Style Properties + +#### emojiKeyboardStyle + +Customizes the appearance of the emoji keyboard. + +| | | +|---|---| +| Type | `EmojiKeyboardStyle` | +| Default | `EmojiKeyboardStyle()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let emojiKeyboardStyle = EmojiKeyboardStyle() +emojiKeyboardStyle.backgroundColor = UIColor.systemBackground +emojiKeyboardStyle.borderColor = UIColor.systemGray4 + +messageList.emojiKeyboardStyle = emojiKeyboardStyle +``` + +#### dateSeparatorStyle + +Customizes the appearance of date separators between messages. + +| | | +|---|---| +| Type | `DateSeparatorStyle` | +| Default | `DateSeparatorStyle()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let dateSeparatorStyle = DateSeparatorStyle() +dateSeparatorStyle.textColor = UIColor.secondaryLabel +dateSeparatorStyle.textFont = UIFont.systemFont(ofSize: 12, weight: .medium) +dateSeparatorStyle.backgroundColor = UIColor.systemGray6 + +messageList.dateSeparatorStyle = dateSeparatorStyle +``` + +#### newMessageIndicatorStyle + +Customizes the appearance of the new message indicator. + +| | | +|---|---| +| Type | `NewMessageIndicatorStyle` | +| Default | `NewMessageIndicatorStyle()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let newMessageIndicatorStyle = NewMessageIndicatorStyle() +newMessageIndicatorStyle.textColor = UIColor.white +newMessageIndicatorStyle.backgroundColor = UIColor.systemBlue +newMessageIndicatorStyle.cornerRadius = 16 + +messageList.newMessageIndicatorStyle = newMessageIndicatorStyle +``` + +#### messageBubbleStyle + +Customizes the appearance of message bubbles. + +| | | +|---|---| +| Type | `MessageBubbleStyle` | +| Default | `MessageBubbleStyle()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let messageBubbleStyle = MessageBubbleStyle() +messageBubbleStyle.outgoing.backgroundColor = UIColor.systemBlue +messageBubbleStyle.incoming.backgroundColor = UIColor.systemGray5 +messageBubbleStyle.outgoing.textColor = UIColor.white +messageBubbleStyle.incoming.textColor = UIColor.label + +messageList.messageBubbleStyle = messageBubbleStyle +``` + +#### actionBubbleStyle + +Customizes the appearance of action message bubbles (e.g., group actions). + +| | | +|---|---| +| Type | `ActionBubbleStyle` | +| Default | `ActionBubbleStyle()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let actionBubbleStyle = ActionBubbleStyle() +actionBubbleStyle.backgroundColor = UIColor.systemGray6 +actionBubbleStyle.textColor = UIColor.secondaryLabel +actionBubbleStyle.textFont = UIFont.systemFont(ofSize: 13, weight: .regular) + +messageList.actionBubbleStyle = actionBubbleStyle +``` + +#### callActionBubbleStyle + +Customizes the appearance of call action message bubbles. + +| | | +|---|---| +| Type | `CallActionBubbleStyle` | +| Default | `CallActionBubbleStyle()` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +let callActionBubbleStyle = CallActionBubbleStyle() +callActionBubbleStyle.backgroundColor = UIColor.systemGreen.withAlphaComponent(0.1) +callActionBubbleStyle.iconTintColor = UIColor.systemGreen +callActionBubbleStyle.textColor = UIColor.label + +messageList.callActionBubbleStyle = callActionBubbleStyle +``` + +### Customization Matrix + +| What to change | Where | Property/API | Example | +|----------------|-------|--------------|---------| +| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | +| Empty state text | Style | `emptyStateTitleColor`, `emptyStateTitleFont` | Custom colors and fonts | +| Error state text | Style | `errorStateTitleColor`, `errorStateTitleFont` | Custom colors and fonts | +| Loading shimmer | Style | `shimmerGradientColor1`, `shimmerGradientColor2` | Custom gradient colors | +| Outgoing bubble | Style | `messageBubbleStyle.outgoing` | `UIColor.systemBlue` | +| Incoming bubble | Style | `messageBubbleStyle.incoming` | `UIColor.systemGray5` | +| Hide avatars | Property | `hideAvatar` | `messageList.hideAvatar = true` | +| Hide receipts | Property | `hideReceipts` | `messageList.hideReceipts = true` | +| Custom header | View Slot | `set(headerView:)` | See Custom View Slots section | + +--- + +## Props + +All props are optional. Sorted alphabetically. + +### actionBubbleStyle + +Customizes the appearance of action message bubbles. + +| | | +|---|---| +| Type | `ActionBubbleStyle` | +| Default | `ActionBubbleStyle()` | + +### callActionBubbleStyle + +Customizes the appearance of call action message bubbles. + +| | | +|---|---| +| Type | `CallActionBubbleStyle` | +| Default | `CallActionBubbleStyle()` | + +### dateSeparatorStyle + +Customizes the appearance of date separators. + +| | | +|---|---| +| Type | `DateSeparatorStyle` | +| Default | `DateSeparatorStyle()` | + +### disableSoundForMessages + +Disables notification sounds for new messages. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +### disableSwipeToReply + +Disables the swipe-to-reply gesture on messages. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.disableSwipeToReply = true ``` ---- +### emojiKeyboardStyle -## Styling +Customizes the appearance of the emoji keyboard. -### Style Hierarchy +| | | +|---|---| +| Type | `EmojiKeyboardStyle` | +| Default | `EmojiKeyboardStyle()` | -1. Global styles (`CometChatMessageList.style`) apply to all instances -2. Instance styles override global for specific instances +### emptySubtitleText -### Global Level Styling +Custom subtitle text for the empty state view. + +| | | +|---|---| +| Type | `String` | +| Default | `""` | ```swift -import UIKit import CometChatUIKitSwift -// Apply global styles that affect all CometChatMessageList instances -CometChatMessageList.style.backgroundColor = UIColor.systemBackground -CometChatMessageList.style.emptyStateTitleColor = UIColor.label -CometChatMessageList.style.emptyStateTitleFont = UIFont.systemFont(ofSize: 20, weight: .bold) -CometChatMessageList.style.emptyStateSubtitleColor = UIColor.secondaryLabel - -// Customize message bubble styles -CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor.systemBlue -CometChatMessageList.messageBubbleStyle.incoming.backgroundColor = UIColor.systemGray5 +let messageList = CometChatMessageList() +messageList.emptySubtitleText = "Send a message to start the conversation" ``` -### Instance Level Styling +### emptyTitleText + +Custom title text for the empty state view. + +| | | +|---|---| +| Type | `String` | +| Default | `"No Messages"` | ```swift -import UIKit import CometChatUIKitSwift -// Create a custom style for a specific instance -let messageListStyle = MessageListStyle() -messageListStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) -messageListStyle.borderWidth = 0 -messageListStyle.borderColor = .clear - let messageList = CometChatMessageList() -messageList.style = messageListStyle +messageList.emptyTitleText = "No messages yet" ``` - - - - -### Key Style Properties - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color of the list | -| `borderWidth` | `CGFloat` | `0` | Border width for the component | -| `borderColor` | `UIColor` | `.clear` | Border color for the component | -| `cornerRadius` | `CometChatCornerStyle?` | `nil` | Corner radius for the component | -| `shimmerGradientColor1` | `UIColor` | `CometChatTheme.backgroundColor04` | First shimmer gradient color | -| `shimmerGradientColor2` | `UIColor` | `CometChatTheme.backgroundColor03` | Second shimmer gradient color | -| `emptyStateTitleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Empty state title color | -| `emptyStateTitleFont` | `UIFont` | `CometChatTypography.Heading3.bold` | Empty state title font | -| `emptyStateSubtitleColor` | `UIColor` | `CometChatTheme.textColorSecondary` | Empty state subtitle color | -| `emptyStateSubtitleFont` | `UIFont` | `CometChatTypography.Body.regular` | Empty state subtitle font | -| `errorStateTitleColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Error state title color | -| `errorStateTitleFont` | `UIFont` | `CometChatTypography.Heading3.bold` | Error state title font | -| `newMessageIndicatorTextColor` | `UIColor?` | `nil` | New message indicator text color | -| `newMessageIndicatorBackgroundColor` | `UIColor?` | `nil` | New message indicator background | +### enableConversationStarters -### Customization Matrix +Enables AI-powered conversation starter suggestions. -| What to change | Where | Property/API | Example | -|----------------|-------|--------------|---------| -| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | -| Empty state text | Style | `emptyStateTitleColor`, `emptyStateTitleFont` | Custom colors and fonts | -| Error state text | Style | `errorStateTitleColor`, `errorStateTitleFont` | Custom colors and fonts | -| Loading shimmer | Style | `shimmerGradientColor1`, `shimmerGradientColor2` | Custom gradient colors | -| Outgoing bubble | Style | `messageBubbleStyle.outgoing` | `UIColor.systemBlue` | -| Incoming bubble | Style | `messageBubbleStyle.incoming` | `UIColor.systemGray5` | -| Hide avatars | Property | `hideAvatar` | `messageList.hideAvatar = true` | -| Hide receipts | Property | `hideReceipts` | `messageList.hideReceipts = true` | -| Custom header | View Slot | `set(headerView:)` | See Custom View Slots section | +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | ---- +### enableConversationSummary -## Props +Enables AI-powered conversation summary feature. -All props are optional. Sorted alphabetically. +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | -### disableSoundForMessages +### enableSmartReplies -Disables notification sounds for new messages. +Enables AI-powered smart reply suggestions. | | | |---|---| | Type | `Bool` | | Default | `false` | +### errorSubtitleText + +Custom subtitle text for the error state view. + +| | | +|---|---| +| Type | `String` | +| Default | `""` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.errorSubtitleText = "Please check your connection and try again" +``` + +### errorTitleText + +Custom title text for the error state view. + +| | | +|---|---| +| Type | `String` | +| Default | `"Something went wrong"` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.errorTitleText = "Unable to load messages" +``` + ### hideAvatar Hides the sender's avatar in message bubbles. @@ -695,6 +1438,22 @@ Hides the sender's avatar in message bubbles. | Type | `Bool` | | Default | `false` | +### hideBubbleHeader + +Hides the header section of message bubbles (sender name, timestamp). + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.hideBubbleHeader = true +``` + ### hideCopyMessageOption Hides the copy message option in message actions. @@ -749,6 +1508,22 @@ Hides the error view when an error occurs. | Type | `Bool` | | Default | `false` | +### hideFlagMessageOption + +Hides the flag/report message option in message actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.hideFlagMessageOption = true +``` + ### hideFooterView Hides the footer view of the message list. @@ -839,6 +1614,38 @@ Hides the reply in thread option. | Type | `Bool` | | Default | `false` | +### hideReplyMessageOption + +Hides the reply to message option in message actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.hideReplyMessageOption = true +``` + +### hideShareMessageOption + +Hides the share message option in message actions. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() +messageList.hideShareMessageOption = true +``` + ### hideTranslateMessageOption Hides the message translation option. @@ -857,6 +1664,24 @@ Sets the alignment of messages in the list. | Type | `MessageAlignment` | | Default | `.standard` | +### messageBubbleStyle + +Customizes the appearance of message bubbles. + +| | | +|---|---| +| Type | `MessageBubbleStyle` | +| Default | `MessageBubbleStyle()` | + +### messageInformationConfiguration + +Configuration object for message information display. + +| | | +|---|---| +| Type | `MessageInformationConfiguration` | +| Default | `MessageInformationConfiguration()` | + ### messagesRequestBuilder Custom request builder for filtering messages. @@ -866,6 +1691,42 @@ Custom request builder for filtering messages. | Type | `MessagesRequest.MessageRequestBuilder?` | | Default | `nil` | +### newMessageIndicatorStyle + +Customizes the appearance of the new message indicator. + +| | | +|---|---| +| Type | `NewMessageIndicatorStyle` | +| Default | `NewMessageIndicatorStyle()` | + +### quickReactionsConfiguration + +Configuration object for quick reactions. + +| | | +|---|---| +| Type | `QuickReactionsConfiguration` | +| Default | `QuickReactionsConfiguration()` | + +### reactionsConfiguration + +Configuration object for the reactions feature. + +| | | +|---|---| +| Type | `ReactionsConfiguration` | +| Default | `ReactionsConfiguration()` | + +### reactionListConfiguration + +Configuration object for the reaction list display. + +| | | +|---|---| +| Type | `ReactionListConfiguration` | +| Default | `ReactionListConfiguration()` | + ### reactionsRequestBuilder Custom request builder for fetching reactions. @@ -915,7 +1776,56 @@ Array of text formatters for customizing message text display. ## Events -The MessageList component does not emit any global UI events. It relies on SDK listeners for real-time updates. +The MessageList component provides callback events for handling state changes. + +### set(onLoad:) + +Fires when messages are successfully loaded. + +```swift +@discardableResult +public func set(onLoad: @escaping ([BaseMessage]) -> Void) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `onLoad` | `([BaseMessage]) -> Void` | Callback with loaded messages | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let messageList = CometChatMessageList() + +messageList.set(onLoad: { messages in + print("Loaded \(messages.count) messages") + // Perform analytics tracking or other actions +}) +``` + +### set(onEmpty:) + +Fires when the message list is empty. + +```swift +@discardableResult +public func set(onEmpty: @escaping () -> Void) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `onEmpty` | `() -> Void` | Callback when list is empty | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() + +messageList.set(onEmpty: { + print("No messages found") + // Show custom empty state or prompt user to start conversation +}) +``` --- @@ -955,6 +1865,19 @@ CometChatMessageList.dateTimeFormatter.otherDay = { timestamp in ### Instance Level Formatting +#### set(datePattern:) + +Sets a custom date pattern for message timestamps. + +```swift +@discardableResult +public func set(datePattern: @escaping (Int?) -> String) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `datePattern` | `(Int?) -> String` | Closure that formats timestamp to date string | + ```swift import CometChatUIKitSwift @@ -967,6 +1890,25 @@ messageList.set(datePattern: { timestamp in formatter.dateFormat = "dd-MM-yyyy" return formatter.string(from: date) }) +``` + +#### set(timePattern:) + +Sets a custom time pattern for message timestamps. + +```swift +@discardableResult +public func set(timePattern: @escaping (Int) -> String) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `timePattern` | `(Int) -> String` | Closure that formats timestamp to time string | + +```swift +import CometChatUIKitSwift + +let messageList = CometChatMessageList() messageList.set(timePattern: { timestamp in let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) @@ -976,7 +1918,18 @@ messageList.set(timePattern: { timestamp in }) ``` -### Date Separator Pattern +#### set(dateSeparatorPattern:) + +Sets a custom pattern for date separators between messages. + +```swift +@discardableResult +public func set(dateSeparatorPattern: @escaping (Int?) -> String) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `dateSeparatorPattern` | `(Int?) -> String` | Closure that formats timestamp to date separator string | ```swift import CometChatUIKitSwift diff --git a/ui-kit/ios/outgoing-call.mdx b/ui-kit/ios/outgoing-call.mdx index 1bcb30a0a..642cd5e7a 100644 --- a/ui-kit/ios/outgoing-call.mdx +++ b/ui-kit/ios/outgoing-call.mdx @@ -6,7 +6,7 @@ description: "Displays outgoing call interface while waiting for recipient to an The `CometChatOutgoingCall` component is a visual representation of a user-initiated call, whether voice or video. It serves as an interface for managing outgoing calls, providing users with essential options to control the call experience. - + CometChatOutgoingCall showing outgoing call interface with recipient avatar, name, and cancel button @@ -233,7 +233,7 @@ outgoingCall.avatarStyle = customAvatarStyle - + CometChatOutgoingCall with custom styling showing custom fonts and rounded decline button #### OutgoingCallStyle Properties @@ -288,7 +288,7 @@ cometChatOutgoingCall.set(avatarView: { call in **Demonstration** - + CometChatOutgoingCall with custom avatar view showing profile image with star badge overlay You can create a `CustomAvatarView` as a custom `UIView`: @@ -383,7 +383,7 @@ cometChatOutgoingCall.set(cancelView: { call in **Demonstration** - + CometChatOutgoingCall with custom cancel view showing red End Call button with phone icon You can create a `CustomCancelView` as a custom `UIView`: @@ -465,7 +465,7 @@ cometChatOutgoingCall.set(titleView: { call in **Demonstration** - + CometChatOutgoingCall with custom title view showing call initiator and receiver names You can create a `CustomTitleView` as a custom `UIView`: @@ -521,7 +521,7 @@ cometChatOutgoingCall.set(subtitleView: { call in **Demonstration** - + CometChatOutgoingCall with custom subtitle view showing phone icon and Calling status text You can create a `CustomSubtitleView` as a custom `UIView`: @@ -574,3 +574,125 @@ class CustomSubtitleView: UIStackView { --- + + +## Props + +All props are optional unless noted. + +--- + +### call + +The outgoing call object to display. + +| | | +|---|---| +| Type | `Call` | +| Default | `undefined` | + +--- + +### disableSoundForCalls + +Disables the outgoing call ringtone. + +| | | +|---|---| +| Type | `Bool` | +| Default | `false` | + +--- + +### customSoundForCalls + +Custom sound file URL for outgoing calls. + +| | | +|---|---| +| Type | `URL?` | +| Default | `nil` | + +--- + +### avatarStyle + +Customizes the appearance of the recipient's avatar. + +| | | +|---|---| +| Type | `AvatarStyle` | +| Default | `AvatarStyle()` | + +```swift +import CometChatUIKitSwift + +let customAvatarStyle = AvatarStyle() +customAvatarStyle.backgroundColor = UIColor.systemOrange +customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) + +let outgoingCall = CometChatOutgoingCall() +outgoingCall.avatarStyle = customAvatarStyle +``` + +--- + +## Events + +Events emitted by the Outgoing Call component: + +| Event | Description | +|-------|-------------| +| `onOutgoingCallAccepted` | Triggers when the outgoing call is accepted by the recipient | +| `onOutgoingCallRejected` | Triggers when the outgoing call is rejected by the recipient | + +--- + +## View Slots + +| Slot | Signature | Replaces | +|------|-----------|----------| +| `avatarView` | `(Call) -> UIView` | Recipient avatar | +| `cancelView` | `(Call) -> UIView` | Cancel call button | +| `titleView` | `(Call) -> UIView` | Recipient name | +| `subtitleView` | `(Call) -> UIView` | "Calling..." text | +| `leadingView` | `(Call) -> UIView` | Left section | +| `trailingView` | `(Call) -> UIView` | Right section | + +### leadingView + +You can customize the leading view of an outgoing call component using the property below. + + + +```swift +cometChatOutgoingCall.set(leadingView: { call in + let view = CustomLeadingView() + return view +}) +``` + + + +### trailingView + +You can customize the trailing view of an outgoing call component using the property below. + + + +```swift +cometChatOutgoingCall.set(trailingView: { call in + let view = CustomTrailingView() + return view +}) +``` + + + +--- + +## Related Components + +- [Incoming Call](/ui-kit/ios/incoming-call) - Display incoming call interface +- [Ongoing Call](/ui-kit/ios/ongoing-call) - Display active call interface +- [Call Logs](/ui-kit/ios/call-logs) - Display call history diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index 47f63a4f7..a531785cf 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -7,7 +7,7 @@ description: "Search across conversations and messages with customizable filters The `CometChatSearch` component is a powerful and customizable search interface that allows users to search across conversations and messages in real time. It supports a wide variety of filters, scopes, and customization options. - + CometChatSearch showing the search interface with search bar, filter options, and search results displaying conversations and messages @@ -23,14 +23,46 @@ The `CometChatSearch` component is a powerful and customizable search interface "type": "(BaseMessage) -> Void" }, "props": { + "data": { + "user": { "type": "User?", "default": "nil", "note": "Limits search to specific user" }, + "group": { "type": "Group?", "default": "nil", "note": "Limits search to specific group" }, + "conversationsRequestBuilder": { "type": "ConversationsRequest.ConversationsRequestBuilder", "default": "SDK default" }, + "messagesRequestBuilder": { "type": "MessagesRequest.MessageRequestBuilder", "default": "SDK default" } + }, "callbacks": { "onConversationClicked": "(Conversation) -> Void", "onMessageClicked": "(BaseMessage) -> Void", "onBack": "() -> Void", - "onError": "(CometChatException) -> Void" + "onError": "(CometChatException) -> Void", + "onEmpty": "() -> Void" }, "visibility": { - "hideNavigationBar": { "type": "Bool", "default": false } + "hideNavigationBar": { "type": "Bool", "default": false }, + "hideBackButton": { "type": "Bool", "default": false }, + "hideUserStatus": { "type": "Bool", "default": false }, + "hideGroupType": { "type": "Bool", "default": false }, + "hideReceipts": { "type": "Bool", "default": false } + }, + "search": { + "searchFilters": { "type": "[SearchFilter]", "default": "All available filters" }, + "initialSearchFilter": { "type": "SearchFilter?", "default": "nil" }, + "searchIn": { "type": "[SearchScope]", "default": "[.conversations, .messages]" } + }, + "viewSlots": { + "listItemViewForConversation": "(Conversation) -> UIView", + "leadingViewForConversation": "(Conversation) -> UIView", + "titleViewForConversation": "(Conversation) -> UIView", + "subtitleViewForConversation": "(Conversation) -> UIView", + "tailViewForConversation": "(Conversation) -> UIView", + "listItemViewForMessage": "(BaseMessage) -> UIView", + "leadingViewForMessage": "(BaseMessage) -> UIView", + "titleViewForMessage": "(BaseMessage) -> UIView", + "subtitleViewForMessage": "(BaseMessage) -> UIView", + "trailingViewForMessage": "(BaseMessage) -> UIView", + "initialView": "UIView", + "loadingView": "UIView", + "emptyView": "UIView", + "errorView": "UIView" } }, "events": [], @@ -55,6 +87,8 @@ The `CometChatSearch` component is a powerful and customizable search interface ```swift +import CometChatUIKitSwift + let search = CometChatSearch() self.navigationController?.pushViewController(search, animated: true) ``` @@ -74,6 +108,9 @@ Triggered when you click on a Conversation from the search result. This action d ```swift +import CometChatUIKitSwift + +let search = CometChatSearch() search.onConversationClicked = { conversation in print("Conversation clicked:", conversation.conversationId) } @@ -90,6 +127,9 @@ Triggered when you click on a Message from the search result. This action doesn' ```swift +import CometChatUIKitSwift + +let search = CometChatSearch() search.onMessageClicked = { message in print("Message clicked:", message.id) } @@ -106,6 +146,9 @@ Triggered when you click on the back button of the search component. ```swift +import CometChatUIKitSwift + +let search = CometChatSearch() search.onBack = { self.navigationController?.popViewController(animated: true) } @@ -122,6 +165,9 @@ Listens for any errors that occur in the Search component. This action doesn't c ```swift +import CometChatUIKitSwift + +let search = CometChatSearch() search.set(onError: { error in print("Search error:", error.localizedDescription) }) @@ -138,6 +184,9 @@ Listens for the empty state of the Search component. This action doesn't change ```swift +import CometChatUIKitSwift + +let search = CometChatSearch() search.set(onEmpty: { print("No results found") }) @@ -161,6 +210,10 @@ The `SearchScope` enum defines what types of content to search: | `.messages` | Search in messages | ```swift +import CometChatUIKitSwift + +let search = CometChatSearch() + // Search only in messages search.set(searchIn: [.messages]) @@ -183,6 +236,10 @@ The `SearchFilter` enum defines available filter options: | `.audio` | Filter by audio messages | ```swift +import CometChatUIKitSwift + +let search = CometChatSearch() + // Set available filters with an initial selection search.set(searchFilters: [.unread, .groups, .photos, .videos], initialFilter: .photos) ``` @@ -194,9 +251,13 @@ Set the `ConversationsRequestBuilder` in the Search Component to filter the sear ```swift +import CometChatUIKitSwift +import CometChatSDK + let convBuilder = ConversationsRequest.ConversationsRequestBuilder() .set(limit: 20) +let search = CometChatSearch() search.set(conversationsRequestBuilder: convBuilder) ``` @@ -211,10 +272,14 @@ Set the `MessagesRequestBuilder` in the Search Component to filter the search re ```swift +import CometChatUIKitSwift +import CometChatSDK + let msgBuilder = MessagesRequest.MessageRequestBuilder() .set(limit: 30) .hide(deletedMessages: true) +let search = CometChatSearch() search.set(messagesRequestBuilder: msgBuilder) ``` @@ -239,12 +304,14 @@ To fit your app's design requirements, you can customize the appearance of the ` Using Style, you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. - + CometChatSearch with custom styling showing modified background color, list item styling, and custom fonts applied ```swift +import CometChatUIKitSwift + // Instance-level styling let style = SearchStyle() style.backgroundColor = UIColor(hex: "#EDEAFA") @@ -279,12 +346,15 @@ These are small functional customizations that allow you to fine-tune the overal | group | Restrict search to a group | `search.group = group` | | hideUserStatus | Hide online/offline indicator | `search.hideUserStatus = true` | | hideGroupType | Hide group type icon | `search.hideGroupType = true` | +| hideBackButton | Hide the back button | `search.hideBackButton = true` | +| hideReceipts | Hide message read/delivery receipt indicators | `search.hideReceipts = true` | | searchFilters | Filters like "Unread", "Groups", "Photos", etc. | `search.set(searchFilters: [.unread, .groups, .photos])` | | initialSearchFilter | Default filter to apply on load | `search.set(searchFilters: [...], initialFilter: .photos)` | | searchIn (searchScopes) | Restrict search: messages / conversations / both | `search.set(searchIn: [.messages, .conversations])` | | loadingView | Custom loader view | `search.set(loadingView: spinner)` | | emptyView | Custom empty result view | `search.set(emptyView: emptyView)` | | errorView | Custom error UI | `search.set(errorView: errorView)` | +| initialView | Custom view before search query is entered | `search.set(initialView: initialView)` | | disableTyping | Disable typing indicators | `search.disableTyping = true` | | disableSoundForMessages | Disable message sounds | `search.disableSoundForMessages = true` | | customSoundForMessages | Custom sound URL for messages | `search.customSoundForMessages = URL(string: "...")` | @@ -308,6 +378,8 @@ For advanced-level customization, you can set custom views to the component. Thi ```swift +import CometChatUIKitSwift + let searchVC = CometChatSearch() searchVC.set(listItemViewForConversation: { conversation in @@ -328,6 +400,8 @@ Here's how you can override the default message item view with a custom one for ```swift +import CometChatUIKitSwift + let searchVC = CometChatSearch() searchVC.set(listItemViewForMessage: { message in return SearchMessageItemView() @@ -337,7 +411,7 @@ searchVC.set(listItemViewForMessage: { message in - + CometChatSearch with custom message item view showing sender name and message text in a customized layout with purple accent styling Custom view implementation: @@ -467,6 +541,8 @@ Available message item view functions for customization: ```swift +import CometChatUIKitSwift + let searchVC = CometChatSearch() // Custom view for image messages @@ -507,6 +583,110 @@ searchVC.set(listItemViewForLink: { mediaMessage in +#### Message Granular View Customization + +For more granular control over message search results, you can customize individual parts of the message item: + +| Function | Description | +|-----------------------------|----------------------------------------------------------| +| leadingViewForMessage | Replaces the message avatar / left section | +| titleViewForMessage | Replaces the message title text | +| subtitleViewForMessage | Replaces the message subtitle text | +| trailingViewForMessage | Replaces the message trailing section | + + + +```swift +import CometChatUIKitSwift + +let searchVC = CometChatSearch() + +// Custom leading view for messages (avatar area) +searchVC.set(leadingViewForMessage: { message in + let customView = UIView() + customView.backgroundColor = .systemPurple + customView.layer.cornerRadius = 24 + // Configure custom leading view + return customView +}) + +// Custom title view for messages +searchVC.set(titleViewForMessage: { message in + let label = UILabel() + label.text = message.sender?.name ?? "Unknown" + label.font = .boldSystemFont(ofSize: 16) + return label +}) + +// Custom subtitle view for messages +searchVC.set(subtitleViewForMessage: { message in + let label = UILabel() + if let textMessage = message as? TextMessage { + label.text = textMessage.text + } else { + label.text = message.type + } + label.textColor = .secondaryLabel + return label +}) + +// Custom trailing view for messages +searchVC.set(trailingViewForMessage: { message in + let label = UILabel() + let date = Date(timeIntervalSince1970: TimeInterval(message.sentAt)) + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm" + label.text = formatter.string(from: date) + label.font = .systemFont(ofSize: 12) + label.textColor = .tertiaryLabel + return label +}) +``` + + + +#### Initial View + +Customize the view displayed before the user enters a search query using the `initialView` property. + + + +```swift +import CometChatUIKitSwift + +let searchVC = CometChatSearch() + +// Create a custom initial view +let initialView = UIView() +let imageView = UIImageView(image: UIImage(systemName: "magnifyingglass")) +imageView.tintColor = .systemGray +imageView.contentMode = .scaleAspectFit +imageView.translatesAutoresizingMaskIntoConstraints = false + +let label = UILabel() +label.text = "Search for conversations and messages" +label.textColor = .secondaryLabel +label.textAlignment = .center +label.translatesAutoresizingMaskIntoConstraints = false + +initialView.addSubview(imageView) +initialView.addSubview(label) + +NSLayoutConstraint.activate([ + imageView.centerXAnchor.constraint(equalTo: initialView.centerXAnchor), + imageView.centerYAnchor.constraint(equalTo: initialView.centerYAnchor, constant: -20), + imageView.widthAnchor.constraint(equalToConstant: 60), + imageView.heightAnchor.constraint(equalToConstant: 60), + label.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 16), + label.leadingAnchor.constraint(equalTo: initialView.leadingAnchor, constant: 20), + label.trailingAnchor.constraint(equalTo: initialView.trailingAnchor, constant: -20) +]) + +searchVC.set(initialView: initialView) +``` + + + --- #### Mention Configuration @@ -516,6 +696,8 @@ Configure how @all mentions appear in search results using the `setMentionAllLab ```swift +import CometChatUIKitSwift + let searchVC = CometChatSearch() // Set a custom label for @all mentions @@ -533,6 +715,8 @@ By providing a custom implementation of the DateTimeFormatterCallback, you can c ```swift +import CometChatUIKitSwift + let searchVC = CometChatSearch() searchVC.dateTimeFormatter.today = { timestamp in diff --git a/ui-kit/ios/users.mdx b/ui-kit/ios/users.mdx index be6db7d30..ac98c622d 100644 --- a/ui-kit/ios/users.mdx +++ b/ui-kit/ios/users.mdx @@ -6,7 +6,7 @@ description: "Display and manage a list of users with search functionality" The `CometChatUsers` component displays a searchable list of all available users. It shows user names, avatars, and online/offline status indicators. Users can be filtered, searched, and selected for starting conversations. - + CometChatUsers showing a searchable list of users with avatars, names, and online/offline status indicators @@ -39,6 +39,7 @@ The `CometChatUsers` component displays a searchable list of all available users "onItemLongClick": "(User, IndexPath) -> Void", "onBack": "() -> Void", "onSelection": "([User]) -> Void", + "onSelectedItemProceed": "([User]) -> Void", "onError": "(CometChatException) -> Void", "onEmpty": "() -> Void", "onLoad": "([[User]]) -> Void" @@ -53,7 +54,13 @@ The `CometChatUsers` component displays a searchable list of all available users "hideLoadingState": { "type": "Bool", "default": false } }, "selection": { - "selectionMode": { "type": "SelectionMode", "default": ".none" } + "selectionMode": { "type": "SelectionMode", "default": ".none" }, + "selectionLimit": { "type": "Int", "default": 0, "note": "0 means unlimited" }, + "selectedCellCount": { "type": "Int", "default": 0, "note": "Read-only count of selected users" } + }, + "styling": { + "avatarStyle": { "type": "AvatarStyle", "default": "AvatarStyle()" }, + "statusIndicatorStyle": { "type": "StatusIndicatorStyle", "default": "StatusIndicatorStyle()" } }, "viewSlots": { "listItemView": "(User) -> UIView", @@ -66,6 +73,18 @@ The `CometChatUsers` component displays a searchable list of all available users "loadingStateView": "() -> UIView" } }, + "methods": { + "swipeActions": { + "set(options:)": "((User?) -> [CometChatUserOption])? - Sets custom swipe actions", + "add(options:)": "((User?) -> [CometChatUserOption])? - Adds additional swipe actions" + }, + "dataManipulation": { + "add(user:)": "User - Adds a user to the list", + "update(user:)": "User - Updates a user in the list", + "remove(user:)": "User - Removes a user from the list", + "getSelectedUsers()": "[User] - Returns selected users" + } + }, "events": [ { "name": "ccUserBlocked", @@ -143,7 +162,7 @@ class UsersViewController: UIViewController { ``` - + CometChatUsers displaying the user list within a navigation controller hierarchy --- @@ -159,7 +178,7 @@ present(navController, animated: true) ``` - + CometChatUsers showing the minimal render with default configuration --- @@ -439,7 +458,7 @@ users.set(leadingView: { user in ``` - + CometChatUsers with custom leadingView showing user avatars with a star badge overlay You can create a `CustomLeadingView` as a custom `UIView`: @@ -528,7 +547,7 @@ users.set(titleView: { user in ``` - + CometChatUsers with custom titleView showing user names with a green Teacher badge You can create a `CustomTitleView` as a custom `UIView`: @@ -604,7 +623,7 @@ users.set(subtitleView: { user in ``` - + CometChatUsers with custom subtitleView showing last active timestamp below user names You can create a `CustomSubtitleView` as a custom `UIView`: @@ -646,7 +665,7 @@ users.set(trailView: { user in ``` - + CometChatUsers with custom trailingView showing a purple PRO badge with star icon You can create a `CustomTrailView` as a custom `UIView`: @@ -762,38 +781,198 @@ users.set(emptyView: emptyLabel) --- -## Options +## Methods + +### Swipe Action Methods -### set(options:) +#### set(options:) -Define custom options for each user. This method allows you to return an array of `CometChatUserOption` based on the user object. +Sets custom swipe actions for user list items, replacing the default options. These options appear when the user swipes on a user cell. ```swift +@discardableResult +public func set(options: ((_ user: User?) -> [CometChatUserOption])?) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `options` | `((User?) -> [CometChatUserOption])?` | Closure that returns an array of swipe action options for a user | + +```swift +import UIKit import CometChatUIKitSwift import CometChatSDK let users = CometChatUsers() users.set(options: { user in - return [CometChatUserOption]() + var options = [CometChatUserOption]() + + // Add block option + let blockOption = CometChatUserOption( + id: "block", + title: "Block", + icon: UIImage(systemName: "hand.raised"), + backgroundColor: .systemRed + ) { selectedUser in + // Handle block action + print("Block user: \(selectedUser?.name ?? "")") + } + options.append(blockOption) + + // Add message option + let messageOption = CometChatUserOption( + id: "message", + title: "Message", + icon: UIImage(systemName: "message"), + backgroundColor: .systemBlue + ) { selectedUser in + // Handle message action + print("Message user: \(selectedUser?.name ?? "")") + } + options.append(messageOption) + + return options }) ``` -### add(options:) +#### add(options:) + +Adds additional swipe actions to the existing default options. + +```swift +@discardableResult +public func add(options: ((_ user: User?) -> [CometChatUserOption])?) -> Self +``` -Dynamically add options to users. This method lets you return additional `CometChatUserOption` elements. +| Parameter | Type | Description | +|-----------|------|-------------| +| `options` | `((User?) -> [CometChatUserOption])?` | Closure that returns additional swipe action options to append | ```swift +import UIKit import CometChatUIKitSwift import CometChatSDK let users = CometChatUsers() users.add(options: { user in - return [ArchiveOption()] + var options = [CometChatUserOption]() + + // Add favorite option + let favoriteOption = CometChatUserOption( + id: "favorite", + title: "Favorite", + icon: UIImage(systemName: "star.fill"), + backgroundColor: .systemOrange + ) { selectedUser in + print("Favorite user: \(selectedUser?.name ?? "")") + } + options.append(favoriteOption) + + return options }) ``` +### Data Manipulation Methods + +#### add(user:) + +Adds a new user to the user list. + +```swift +@discardableResult +public func add(user: User) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `user` | `User` | The user to add to the list | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +// Add a user programmatically +let newUser = User(uid: "user-123", name: "John Doe") +users.add(user: newUser) +``` + +#### update(user:) + +Updates an existing user in the list. + +```swift +@discardableResult +public func update(user: User) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `user` | `User` | The user with updated information | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +// Update a user's information +if var existingUser = userToUpdate { + existingUser.name = "Updated Name" + users.update(user: existingUser) +} +``` + +#### remove(user:) + +Removes a user from the list. + +```swift +@discardableResult +public func remove(user: User) -> Self +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `user` | `User` | The user to remove from the list | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() + +// Remove a user from the UI +users.remove(user: userToRemove) +``` + +#### getSelectedUsers() + +Returns an array of currently selected users when in selection mode. + +```swift +public func getSelectedUsers() -> [User] +``` + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() +users.selectionMode = .multiple + +// Get all selected users +let selectedUsers = users.getSelectedUsers() +print("Selected \(selectedUsers.count) users") + +for user in selectedUsers { + print("User: \(user.name ?? "")") +} +``` + --- ## Custom ListItem @@ -801,7 +980,7 @@ users.add(options: { user in For more complex or unique list items, you can create a custom `UIView` file named `CustomListItem` and integrate it into the `set(listItemView:)` method. - + CometChatUsers with custom listItemView showing a simplified user row with avatar and name ```swift @@ -921,7 +1100,7 @@ users.style = customStyle ``` - + CometChatUsers with custom styling showing modified background colors and text appearance ### Key Style Properties @@ -960,6 +1139,29 @@ users.style = customStyle All props are optional. Sorted alphabetically. +### avatarStyle + +Customizes the appearance of avatars in user list items. + +| | | +|---|---| +| Type | `AvatarStyle` | +| Default | `AvatarStyle()` | + +```swift +import CometChatUIKitSwift + +let users = CometChatUsers() + +let avatarStyle = AvatarStyle() +avatarStyle.backgroundColor = UIColor.systemBlue +avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) +avatarStyle.borderWidth = 1 +avatarStyle.borderColor = UIColor.systemGray4 + +users.set(avatarStyle: avatarStyle) +``` + ### hideBackButton Hides the back button in the navigation bar. @@ -1023,6 +1225,33 @@ Hides online/offline status indicators. | Type | `Bool` | | Default | `false` | +### onSelectedItemProceed + +Callback triggered when the user confirms their selection in selection mode. Use this to handle the selected users. + +| | | +|---|---| +| Type | `(([User]) -> Void)?` | +| Default | `nil` | + +```swift +import CometChatUIKitSwift +import CometChatSDK + +let users = CometChatUsers() +users.selectionMode = .multiple +users.selectionLimit = 5 + +users.onSelectedItemProceed = { selectedUsers in + print("Proceeding with \(selectedUsers.count) users") + + // Process the selected users + for user in selectedUsers { + print("User: \(user.name ?? "")") + } +} +``` + ### searchRequestBuilder Custom request builder for search functionality. @@ -1032,6 +1261,44 @@ Custom request builder for search functionality. | Type | `UsersRequest.UsersRequestBuilder?` | | Default | `nil` | +### selectedCellCount + +Returns the count of currently selected users in selection mode. + +| | | +|---|---| +| Type | `Int` | +| Default | `0` | + +### selectionLimit + +Sets the maximum number of users that can be selected in selection mode. When the limit is reached, further selections are disabled. + +| | | +|---|---| +| Type | `Int` | +| Default | `0` (unlimited) | + +```swift +import CometChatUIKitSwift + +let users = CometChatUsers() +users.selectionMode = .multiple + +// Limit selection to 5 users +users.selectionLimit = 5 + +// Handle selection confirmation +users.onSelectedItemProceed = { selectedUsers in + print("Selected \(selectedUsers.count) users") + + // Process the selected users + for user in selectedUsers { + print("User: \(user.name ?? "")") + } +} +``` + ### selectionMode Sets the selection mode for multi-select functionality. @@ -1041,6 +1308,28 @@ Sets the selection mode for multi-select functionality. | Type | `SelectionMode` | | Default | `.none` | +### statusIndicatorStyle + +Customizes the appearance of online/offline status indicators. + +| | | +|---|---| +| Type | `StatusIndicatorStyle` | +| Default | `StatusIndicatorStyle()` | + +```swift +import CometChatUIKitSwift + +let users = CometChatUsers() + +let statusIndicatorStyle = StatusIndicatorStyle() +statusIndicatorStyle.backgroundColor = UIColor.systemGreen +statusIndicatorStyle.borderWidth = 2 +statusIndicatorStyle.borderColor = UIColor.white + +users.set(statusIndicatorStyle: statusIndicatorStyle) +``` + ### usersRequestBuilder Custom request builder for filtering users. From 6c289247da4da3933497db0e98e3979fcb50f86c Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 11:51:41 +0530 Subject: [PATCH 059/106] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4669a449e..2b6c95161 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ __pycache__/ /docs-templates /docs-test-suite /prompts +/docs-comparison-tool From de13ef04b5437c3fc2dbb9cd86e9cc418bfc57c8 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 12:25:44 +0530 Subject: [PATCH 060/106] Update getting-started.mdx --- ui-kit/ios/getting-started.mdx | 513 ++++++++++++--------------------- 1 file changed, 184 insertions(+), 329 deletions(-) diff --git a/ui-kit/ios/getting-started.mdx b/ui-kit/ios/getting-started.mdx index a78eed906..919538ace 100644 --- a/ui-kit/ios/getting-started.mdx +++ b/ui-kit/ios/getting-started.mdx @@ -1,283 +1,163 @@ --- -title: "Getting Started With CometChat iOS UI Kit" +title: "iOS Integration" sidebarTitle: "Integration" +description: "Add CometChat to an iOS app in 5 steps: create project, install, init, login, render." --- - -```json -{ - "platform": "iOS UI Kit", - "package": "CometChatUIKitSwift", - "version": "5.1.7", - "requirements": { - "xcode": "16 or later", - "ios": "13.0+", - "swift": "5.0+", - "dependencies": { - "CometChatSDK": "4.1.0", - "CometChatCallsSDK": "4.2.2 (optional)" - } - }, - "installation": { - "cocoapods": "pod 'CometChatUIKitSwift', '5.1.7'", - "spm": "https://github.com/cometchat/cometchat-uikit-ios" - }, - "quickStart": { - "initialize": "CometChatUIKit.init(uiKitSettings:)", - "login": "CometChatUIKit.login(uid:)", - "requiredCredentials": ["appID", "authKey", "region"] - } -} -``` - + -The **CometChat UI Kit for iOS** streamlines the integration of in-app chat functionality by providing a **comprehensive set of prebuilt UI elements**. It offers seamless **theming options**, including **light and dark modes**, customizable fonts, colors, and extensive styling capabilities. +| Field | Value | +| --- | --- | +| Package | `CometChatUIKitSwift` | +| Version | `5.1.7` | +| Requirements | Xcode 16+, iOS 13.0+, Swift 5.0+ | +| Init | `CometChatUIKit.init(uiKitSettings:)` — must complete before `login()` | +| Login | `CometChatUIKit.login(uid:)` — must complete before rendering components | +| Order | `init()` → `login()` → render. Breaking this order = blank screen | +| Auth Key | Dev/testing only. Use Auth Token in production | +| Calling | Optional. Install `CometChatCallsSDK 4.2.2` to enable | +| Dependencies | `CometChatSDK 4.1.0` (installed automatically) | -With built-in support for **one-to-one and group conversations**, developers can efficiently enable chat features within their applications. Follow this guide to **quickly integrate chat functionality** using the CometChat iOS UI Kit. + + +This guide walks you through adding CometChat to an iOS app. By the end you'll have a working chat UI. -*** - -## **Prerequisites** - -Before installing the **CometChat UI Kit for iOS**, you must first **create a CometChat application** via the **[CometChat Dashboard](https://app.cometchat.com/)**. The dashboard provides all the essential chat service components, including: - -* **User Management** -* **Group Chat & Messaging** -* **Voice & Video Calling** -* **Real-time Notifications** - - - -To initialize the **UI Kit**, you will need the following credentials from your **CometChat application**: - -1. **App ID** -2. **Auth Key** -3. **Region** - -Ensure you have these details ready before proceeding with the installation and configuration. - - - -*** - -## **Register & Set Up CometChat** - -Follow these steps to **register on CometChat** and **set up your development environment**. - -### **Step 1: Register on CometChat** - -To use **CometChat UI Kit**, you first need to register on the **CometChat Dashboard**. - -🔗 **[Click here to Sign Up](https://app.cometchat.com/login)** - -### **Step 2: Get Your Application Keys** - -After registering, create a **new app** and retrieve your **authentication details**: - -1. Navigate to the **QuickStart** or **API & Auth Keys section**. - -2. Note down the following keys: - - * **App ID** - * **Auth Key** - * **Region** - - - -Each CometChat application can be integrated with a **single client app**. Users within the same application can communicate across multiple platforms, including **web and mobile**. - - - -### **Step 3: Set Up Your Development Environment** +--- -Ensure your system meets the following **prerequisites** before proceeding with integration. +## Prerequisites -**System Requirements:** +You need three things from the [CometChat Dashboard](https://app.cometchat.com/): -* **Xcode 16 or later** installed on your machine. -* An **iOS device or simulator** with iOS version 13.0 or above. -* **Swift 5.0**. -* **macOS**. +| 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: +- Xcode 16 or later +- iOS device or simulator running iOS 13.0+ +- Swift 5.0+ +- macOS -## **Integration Steps** + +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/ios/methods#login-using-auth-token). Never ship Auth Keys in client code. + -### **Create an iOS Project** +--- -To get started, open Xcode and create a new project for UI Kit in the Project window as follows: +## Step 1 — Create an iOS Project -1. Select **iOS App** in the **Choose a template for your new project** window and click Next. -2. Enter your project name in the **Name** field in the **Choose options for your new project** window. -3. Enter your identifier in the **Bundle Identifier** field in the **Choose options for your new project** window. -4. Select **Storyboard** in the **Interface** field in the **Choose options for your new project** window. -5. Select **Swift** in the **Language** field in the **Choose options for your new project** window. +Open Xcode and create a new project: -*** +1. Select **iOS App** in the template picker and click Next +2. Enter your project name and bundle identifier +3. Select **Storyboard** for Interface +4. Select **Swift** for Language -### **Install Dependencies** +--- -This developer kit is an add-on feature to CometChat iOS SDK so installing it will also install the core Chat SDK. You can install CometChat UI Kit into your iOS project using CocoaPods or Swift Package Manager (SPM). +## Step 2 — Install the UI Kit -We recommend using CocoaPods, as they are the most advanced way of managing iOS project dependencies. - -1. Create pod file by running the following command in your project's base level: +1. Create a Podfile in your project root: -```ruby Swift +```bash pod init ``` -2. Add CometChat SDKs to Your Podfile: +2. Add CometChat to your Podfile: -```ruby Swift +```ruby title="Podfile" platform :ios, '13.0' use_frameworks! target 'YourApp' do - # CometChat UI Kit for Swift pod 'CometChatUIKitSwift', '5.1.7' - - # Optional: Include if you're using Audio/Video Calling + + # Optional: Voice/Video Calling pod 'CometChatCallsSDK', '4.2.2' end ``` -3. Install the CometChat UI Kit framework through CocoaPods: +3. Install dependencies: -```ruby Swift +```bash pod install ``` -If you're facing any issues while installing pods, use the following command: - -```ruby Swift -pod install --repo-update -``` - -To get the latest version of CometChat UI Kit, use: - -```ruby Swift -pod update CometChatUIKitSwift -pod update CometChatCallsSDK -``` - - -Always ensure to open the XCFramework file after adding the dependencies. - +If you hit issues, run `pod install --repo-update`. Always open the `.xcworkspace` file after installing pods. - - -**Swift Package Manager** (SPM) is Apple's built-in tool for managing dependencies in Swift projects. It allows developers to integrate and manage third-party libraries seamlessly. - -1. Go to **File** tab and select **Add Package Dependencies.** + +1. Go to **File → Add Package Dependencies** -2. Enter the repository URL of the Swift package: +2. Enter the repository URL: ``` https://github.com/cometchat/cometchat-uikit-ios ``` -3. To add the package, select Version Rules, enter Up to Exact Version and click Add package. - - Exact Version: +3. Select **Up to Exact Version** and enter: - ``` - 5.1.7 - ``` - -4. Add `CometChatSDK` repeating the above steps for following link and exact version: - - Link: - - ``` - https://github.com/cometchat/chat-sdk-ios - ``` +``` +5.1.7 +``` - Exact Version: +4. Add the Chat SDK separately using: - ``` - 4.1.0 - ``` +``` +https://github.com/cometchat/chat-sdk-ios +``` + Exact Version: `4.1.0` - -*** - -### **Configure Privacy Permissions** - -1. To enable media messaging in your app, you must allow **Camera**, **Microphone**, and **Photo Library** access in `Info.plist`. These permissions are required for sending and receiving media files. - - ```ruby Info.plist - NSCameraUsageDescription - Allow access to the camera to capture photos and videos. - - NSMicrophoneUsageDescription - Enable microphone access for voice and video communication. - - NSPhotoLibraryAddUsageDescription - Allow saving photos and videos to your device's photo library. - - NSPhotoLibraryUsageDescription - Grant access to select and upload photos from your library. - ``` - - - - - -2. Navigate to your Build Settings and disable the User Script Sandboxing option. - - Disabling User Script Sandboxing ensures that WebView can load and execute scripts necessary for collaborative tools. - - - - - -*** - -### **Step 4: Initialize & Login to CometChat UI Kit** +--- -To authenticate a user, you need a **`UID`**. You can either: +## Step 3 — Configure Permissions -1. **Create new users** on the **[CometChat Dashboard](https://app.cometchat.com)**, **[CometChat SDK Method](/ui-kit/react/methods#create-user)** or **[via the API](https://api-explorer.cometchat.com/reference/creates-user)**. +Add these keys to your `Info.plist` for media messaging: -2. **Use pre-generated test users**: +```xml title="Info.plist" +NSCameraUsageDescription +Allow access to the camera to capture photos and videos. - * `cometchat-uid-1` - * `cometchat-uid-2` - * `cometchat-uid-3` - * `cometchat-uid-4` - * `cometchat-uid-5` +NSMicrophoneUsageDescription +Enable microphone access for voice and video communication. -The **Login** method returns a **User object** containing all relevant details of the logged-in user. +NSPhotoLibraryAddUsageDescription +Allow saving photos and videos to your device's photo library. -*** +NSPhotoLibraryUsageDescription +Grant access to select and upload photos from your library. +``` - + + + -**Security Best Practices** +Also disable **User Script Sandboxing** in Build Settings to ensure WebView can load scripts for collaborative tools. -* The **Auth Key** method is recommended for **proof-of-concept (POC) development** and early-stage testing. -* For **production environments**, it is strongly advised to use an **[Auth Token](/ui-kit/ios/methods#login-using-auth-token)** instead of an **Auth Key** to enhance security and prevent unauthorized access. + + + - +--- -You can initialize CometChat and log in a user in your `SceneDelegate.swift` file: +## Step 4 — Initialize & Login -> ⚠️ **Important:** Initialization and login are independent steps. However, the CometChat SDK **must be initialized before** you call the login method. +Add this to your `SceneDelegate.swift`. Init must complete before login, and login must complete before rendering any UI. -```swift SceneDelegate.swift highlight={13-15} lines +```swift title="SceneDelegate.swift" import UIKit import CometChatUIKitSwift @@ -286,191 +166,166 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - guard let windowScene = (scene as? UIWindowScene) else { return } let uikitSettings = UIKitSettings() - .set(appID: "<#Enter Your App ID Here#>") - .set(region: "<#Enter Your Region Code Here#>") - .set(authKey: "<#Enter Your AuthKey Here#>") + .set(appID: "APP_ID") // Replace with your App ID + .set(region: "REGION") // Replace with your Region + .set(authKey: "AUTH_KEY") // Replace with your Auth Key (dev only) .subscribePresenceForAllUsers() .build() CometChatUIKit.init(uiKitSettings: uikitSettings) { result in switch result { case .success: - debugPrint("CometChat UI Kit initialization succeeded") - - let uid = "cometchat-uid-1" - + debugPrint("CometChat initialized") + + let uid = "cometchat-uid-1" // Test user + CometChatUIKit.login(uid: uid) { loginResult in switch loginResult { case .success: - debugPrint("CometChat UI Kit login succeeded") - - // ✅ Option 1: Launch One-to-One or Group Chat Screen - // DispatchQueue.main.async { - // self.setUpOneOneOrGroupConversation(windowScene: windowScene, uid: "cometchat-uid-2") - // } - - // ✅ Option 2: Launch Conversation List + Message View (Split-Screen Style) - // DispatchQueue.main.async { - // self.setupConversationsView(windowScene: windowScene) - // } - - // ✅ Option 3: Launch Tab-Based Chat Experience (Chats, Calls, Users, Groups) - // DispatchQueue.main.async { - // self.setupTabbedView(windowScene: windowScene) - // } - + debugPrint("Login successful") + + // ✅ Option 1: Launch One-to-One or Group Chat Screen + // DispatchQueue.main.async { + // self.setUpOneOneOrGroupConversation(windowScene: windowScene, uid: "cometchat-uid-2") + // } + + // ✅ Option 2: Launch Conversation List + Message View + // DispatchQueue.main.async { + // self.setupConversationsView(windowScene: windowScene) + // } + + // ✅ Option 3: Launch Tab-Based Chat Experience + // DispatchQueue.main.async { + // self.setupTabbedView(windowScene: windowScene) + // } + case .onError(let error): - debugPrint("CometChat UI Kit login failed with error: \(error.description)") + debugPrint("Login failed: \(error.description)") @unknown default: break } } - + case .failure(let error): - debugPrint("CometChat UI Kit initialization failed with error: \(error.localizedDescription)") + debugPrint("Init failed: \(error.localizedDescription)") } } } } ``` - - -Ensure you replace the following placeholders with your actual CometChat credentials: - -* App ID → Your CometChat App ID -* Auth Key → Your CometChat Auth Key -* Region → Your App Region +For development, use one of the pre-created test UIDs: -These values are required for proper authentication and seamless integration. +`cometchat-uid-1` · `cometchat-uid-2` · `cometchat-uid-3` · `cometchat-uid-4` · `cometchat-uid-5` - +Or create new users via the [CometChat Dashboard](https://app.cometchat.com), [SDK method](/ui-kit/ios/methods#create-user), or [REST API](https://api-explorer.cometchat.com/reference/creates-user). -After running the app, you should see the following log message: +After running the app, you should see: -```sh Console -"CometChat UI Kit initialization succeeded" -"CometChat UI Kit login succeeded" +```sh +"CometChat initialized" +"Login successful" ``` -*** + +`init()` must complete before you call `login()`. If you call `login()` before init completes, it will fail silently. + -### **Step 5: Choose a Chat Experience** + +For production, use [`loginWithAuthToken()`](/ui-kit/ios/methods#login-using-auth-token) instead of Auth Key. Generate tokens server-side via the REST API. + -Integrate a conversation view that suits your application's **UX requirements**. Below are the available options: +--- -*** +## Step 5 — Choose a Chat Experience -### **1️⃣ Conversation List + Message View** +Integrate a conversation view that suits your app's UX. Each option below includes a step-by-step guide. -**Best for:** Native iOS apps using **stack-based navigation** to switch between conversations and messages. +### Conversation List + Message View -**Highlights:** +Two-panel layout — conversation list with push navigation to messages. Think iMessage or WhatsApp. -* **Push-Based Navigation** – Taps on conversations open full message views. -* **Supports One-to-One & Group Chats** – Handles all CometChat conversation types. -* **Real-Time Sync** – Messages auto-refresh using live CometChat event listeners. -* **Session-Aware** – Message states persist across app sessions and devices. -* **Customizable UI** – Modify styling, actions, or behavior using CometChat UI Kit. +- Push-based navigation between conversations and messages +- Supports one-to-one and group chats +- Real-time sync with CometChat event listeners +- Session-aware — message states persist across app sessions -**Use When:** + + Step-by-step guide to build this layout + -* You need a **native iOS chat experience** with clean transitions. -* Your app supports **private and group messaging**. -* You want **seamless sync and navigation** between list and messages. - -[Integrate Conversation List + Message View](./ios-conversation) - -*** - -### **2️⃣ One-to-One / Group Chat** +--- -**Best for:** iOS apps that launch **directly into a conversation screen** without showing a list. +### One-to-One / Group Chat -**Highlights:** +Single chat window — no sidebar. Good for support chat, contextual messaging, or focused conversations. -* **Single View Chat** – Use `CometChatMessages` with a passed user or group object. -* **No Sidebar or List** – Ideal for contextual entry points (support, match, invite, etc.). -* **Works with UINavigationController & SwiftUI NavigationStack** -* **Lightweight** – Launches faster and uses minimal memory. -* **Full-Screen Messaging** – Clear, immersive chat UI. +- Dedicated chat window for one-on-one or group messaging +- No conversation list — users go directly into the chat +- Full-screen experience optimized for mobile +- Ideal for support workflows, community replies, or invitations -**Use When:** - -* Your app starts directly with a **specific user or group chat**. -* You want a **clean, distraction-free** chat experience. -* Ideal for **support workflows, community replies, or invitations.** - -[Integrate One-to-One / Group Chat](./ios-one-to-one-chat) + + Step-by-step guide to build this layout + -*** - -### **3️⃣ Tab-Based Messaging UI (All-in-One)** +--- -**Best for:** iOS apps needing a **multi-tab interface** with seamless transitions between Chats, Users, Calls, and Settings. +### Tab-Based Chat -**Highlights:** +Tabbed navigation — Chats, Calls, Users, Groups in separate tabs. Good for full-featured apps. -* **UITabBarController or SwiftUI TabView** – Native navigation pattern for iOS. -* **Modular UI** – Isolated controllers or views for each tab. -* **Full-Screen Messaging** – Dedicated message views within the Chat tab. -* **Extensible** – Add future tabs like Notifications, Search, or Profile. -* **Responsive Layouts** – Works across iPhones and iPads. -* **Great for SuperApps & Enterprise Tools** +- UITabBarController or SwiftUI TabView navigation +- Full-screen messaging within each tab +- Modular UI — isolated controllers for each tab +- Scales well for adding future features like notifications or settings -**Use When:** - -* You need a **structured layout** for navigating chat, calls, and contacts. -* Your app supports **multiple modules** (e.g., user directory, history, chat). -* Designed for **enterprise, support, or social use cases**. - -[Integrate Tab-Based Chat](./ios-tab-based-chat) - -*** - -## **Build Your Own Chat Experience** + + Step-by-step guide to build this layout + -**Best for:** Developers who need complete control over their chat interface, allowing customization of components, themes, and features to align with their app’s design and functionality. Whether you're enhancing an existing chat experience or building from scratch, this approach provides the flexibility to tailor every aspect to your needs. - -**Recommended for:** - -* Apps that require **a fully customized chat experience**. -* Developers who want to **extend functionalities and modify UI components**. -* Businesses integrating chat seamlessly into **existing platforms**. - -**Key Areas to Explore:** - -* **[iOS Sample App](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp)** – Fully functional sample applications to accelerate your development. -* **[Core Features](./core-features)** – Learn about messaging, real-time updates, and other essential capabilities. -* **[Components](./components-overview)** – Utilize prebuilt UI elements or customize them to fit your design. -* **[Themes](./theme-introduction)** – Adjust colors, fonts, and styles to match your branding. -* **[Build Your Own UI](/sdk/javascript/overview)** – Prefer a custom UI over our UI Kits? Explore our SDKs to create a tailored chat experience. +--- -*** +## Build Your Own Chat Experience -## **Next Steps** +Need full control over the UI? Use individual components, customize themes, and wire up your own layouts. -Now that you’ve selected your **chat experience**, proceed to the **integration guide**: +- [Sample App](https://github.com/cometchat/cometchat-uikit-ios/tree/v5/SampleApp) — Working reference app to compare against +- [Components](/ui-kit/ios/components-overview) — All prebuilt UI elements with customization options +- [Core Features](/ui-kit/ios/core-features) — Messaging, real-time updates, and other capabilities +- [Theming](/ui-kit/ios/theme-introduction) — Colors, fonts, dark mode, and custom styling +- [Build Your Own UI](/sdk/ios/overview) — Skip the UI Kit entirely and build on the raw SDK -* **[Integrate Conversation List + Message](/ui-kit/ios/ios-conversation)** -* **[Integrate One-to-One Chat](/ui-kit/ios/ios-one-to-one-chat)** -* **[Integrate Tab-Based Chat](/ui-kit/ios/ios-tab-based-chat)** -* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** +--- -*** +## Next Steps + + + + Browse all prebuilt UI components + + + Customize colors, fonts, and styles + + + Chat features included out of the box + + + SDK methods and API reference + + From 13027c3c33ad66e0e141e722a921fa4a298241a9 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 13:14:20 +0530 Subject: [PATCH 061/106] three examples --- ui-kit/ios/ios-conversation.mdx | 151 +++++++++++++---------- ui-kit/ios/ios-one-to-one-chat.mdx | 187 ++++++++++++++++++----------- ui-kit/ios/ios-tab-based-chat.mdx | 154 +++++++++++++----------- 3 files changed, 282 insertions(+), 210 deletions(-) diff --git a/ui-kit/ios/ios-conversation.mdx b/ui-kit/ios/ios-conversation.mdx index 6124c475c..cb98e06be 100644 --- a/ui-kit/ios/ios-conversation.mdx +++ b/ui-kit/ios/ios-conversation.mdx @@ -1,68 +1,79 @@ --- -title: "Building A Conversation List + Message View" +title: "Conversation List + Message View" sidebarTitle: "Conversation List + Message View" +description: "Build a two-panel conversation list + message view layout in iOS with CometChat UI Kit." --- -The **Conversation List + Message View** layout offers a modern two-panel chat experience. It's ideal for applications needing seamless switching between multiple conversations and chat windows—similar to **WhatsApp Web**, **Slack**, or **Microsoft Teams**. + -*** +| Field | Value | +| --- | --- | +| Package | `CometChatUIKitSwift` | +| Framework | UIKit / SwiftUI | +| Components | `CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Push navigation — conversation list → message view | +| Prerequisite | Complete [iOS Integration](/ui-kit/ios/getting-started) Steps 1–4 first | +| Pattern | iMessage, WhatsApp, Slack | -## **User Interface Preview** + + +This guide builds a conversation list with push navigation to messages. Users tap a conversation to open the chat view. + +This assumes you've already completed [iOS Integration](/ui-kit/ios/getting-started) (project created, UI Kit installed, init + login working, permissions configured). -### **Key Components** +--- -1. **Chat Header** – Displays user or group name, avatar, and back button. -2. **Message List** – Displays chat messages and real-time updates. -3. **Message Composer** – Allows sending of text, media, and reactions. +## What You're Building -*** +Three components working together: -## **Step-by-Step Guide** +1. **Conversation list** — shows all active conversations (users and groups) +2. **Message view** — displays chat messages for the selected conversation in real time +3. **Message composer** — text input with support for media, emojis, and reactions + +--- -### **Step 1: Setup SceneDelegate.swift** +## Step 1 — Setup SceneDelegate -Ensure UIKit is initialized and the user is logged in before presenting the conversation view. +Wire up the conversation list after successful login. When a user taps a conversation, push to the messages view. -```swift SceneDelegate.swift highlight={15-17} lines +```swift title="SceneDelegate.swift" highlight={13-15} lines import UIKit import CometChatUIKitSwift import CometChatSDK -import CometChatCallsSDK class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - guard let windowScene = (scene as? UIWindowScene) else { return } let uikitSettings = UIKitSettings() - .set(appID: "<#Enter Your App ID Here#>") - .set(region: "<#Enter Your Region Code Here#>") - .set(authKey: "<#Enter Your AuthKey Here#>") + .set(appID: "APP_ID") // Replace with your App ID + .set(region: "REGION") // Replace with your Region + .set(authKey: "AUTH_KEY") // Replace with your Auth Key (dev only) .subscribePresenceForAllUsers() .build() CometChatUIKit.init(uiKitSettings: uikitSettings) { result in switch result { case .success: - debugPrint("CometChatUIKit initialization succeeded") + debugPrint("CometChat initialized") let uid = "cometchat-uid-1" CometChatUIKit.login(uid: uid) { loginResult in switch loginResult { case .success: - debugPrint("CometChatUIKit login succeeded") + debugPrint("Login successful") DispatchQueue.main.async { [weak self] in - guard let self = self else { return } - self.setupConversationsView(windowScene: windowScene) + self?.setupConversationsView(windowScene: windowScene) } case .onError(let error): @@ -72,7 +83,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } case .failure(let error): - debugPrint("Initialization failed: \(error.localizedDescription)") + debugPrint("Init failed: \(error.localizedDescription)") } } } @@ -95,35 +106,32 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } ``` -*** +Key points: +- `CometChatConversations` displays the conversation list +- `onItemClick` fires when a user taps a conversation, passing the `Conversation` object +- Extract `User` or `Group` from `conversation.conversationWith` and pass to the messages view + +--- -### **Step 2: Create MessagesVC.swift** +## Step 2 — Create MessagesVC -This view controller handles chat between users or within groups. +Create a new file `MessagesVC.swift`. This view controller assembles the header, message list, and composer. -```swift MessagesVC.swift lines +```swift title="MessagesVC.swift" lines import UIKit import CometChatSDK import CometChatUIKitSwift -/// A view controller that displays a chat interface using CometChat components class MessagesVC: UIViewController { // MARK: - Properties - - /// The user entity for one-on-one chats var user: User? - - /// The group entity for group chats var group: Group? // MARK: - UI Components - - /// Header view displaying user/group information private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { @@ -133,25 +141,9 @@ class MessagesVC: UIViewController { return view }() - /// Message input composer view - private lazy var composerView: CometChatMessageComposer = { - let composer = CometChatMessageComposer() - composer.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type - if let user = user { - composer.set(user: user) - } else if let group = group { - composer.set(group: group) - } - composer.set(controller: self) - return composer - }() - - /// List view displaying chat messages private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { @@ -161,8 +153,19 @@ class MessagesVC: UIViewController { return listView }() - // MARK: - Lifecycle Methods + private lazy var composerView: CometChatMessageComposer = { + let composer = CometChatMessageComposer() + composer.translatesAutoresizingMaskIntoConstraints = false + if let user = user { + composer.set(user: user) + } else if let group = group { + composer.set(group: group) + } + composer.set(controller: self) + return composer + }() + // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() configureView() @@ -174,34 +177,29 @@ class MessagesVC: UIViewController { navigationController?.setNavigationBarHidden(false, animated: true) } - // MARK: - Private Methods - - /// Configure basic view properties + // MARK: - Setup private func configureView() { view.backgroundColor = .systemBackground navigationController?.setNavigationBarHidden(true, animated: false) } - /// Set up view hierarchy and constraints private func setupLayout() { - // Add subviews to the view hierarchy [headerView, messageListView, composerView].forEach { view.addSubview($0) } - // Set up constraints NSLayoutConstraint.activate([ - // Header view constraints + // Header headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), headerView.heightAnchor.constraint(equalToConstant: 50), - // Message list view constraints + // Message list messageListView.topAnchor.constraint(equalTo: headerView.bottomAnchor), messageListView.leadingAnchor.constraint(equalTo: view.leadingAnchor), messageListView.trailingAnchor.constraint(equalTo: view.trailingAnchor), messageListView.bottomAnchor.constraint(equalTo: composerView.topAnchor), - // Composer view constraints + // Composer composerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), composerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), composerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) @@ -210,12 +208,33 @@ class MessagesVC: UIViewController { } ``` -*** +How it works: +- `CometChatMessageHeader` shows user/group info and back button +- `CometChatMessageList` displays messages with real-time updates +- `CometChatMessageComposer` handles text input, media, and reactions +- Pass either `user` or `group` to each component, never both + +--- -## **Next Steps** +## Step 3 — Run the Project -### **Enhance the User Experience** +Build and run in Xcode. You should see the conversation list. Tap any conversation to push to the messages view. -* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. +--- -*** +## Next Steps + + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + diff --git a/ui-kit/ios/ios-one-to-one-chat.mdx b/ui-kit/ios/ios-one-to-one-chat.mdx index ae1c160d6..7cdc680f2 100644 --- a/ui-kit/ios/ios-one-to-one-chat.mdx +++ b/ui-kit/ios/ios-one-to-one-chat.mdx @@ -1,68 +1,82 @@ --- -title: "Building A One To One/Group Chat Experience" -sidebarTitle: "One To One/Group Chat" +title: "One-to-One / Group Chat" +sidebarTitle: "One-to-One / Group Chat" +description: "Build a focused one-to-one or group chat experience in iOS with CometChat UI Kit." --- -The **One-to-One Chat** feature provides a streamlined **direct messaging interface**, making it ideal for **support chats, dating apps, and private messaging platforms**. This setup eliminates distractions by focusing solely on a **dedicated chat window**. + -*** +| Field | Value | +| --- | --- | +| Package | `CometChatUIKitSwift` | +| Framework | UIKit / SwiftUI | +| Components | `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Single chat window — no sidebar, no conversation list | +| Prerequisite | Complete [iOS Integration](/ui-kit/ios/getting-started) Steps 1–4 first | +| Pattern | Support chat, embedded widgets, focused messaging | -## **User Interface Preview** + + +This guide builds a single chat window — no sidebar, no conversation list. Users go directly into a one-to-one or group chat. Good for support chat, contextual messaging, or any focused messaging experience. + +This assumes you've already completed [iOS Integration](/ui-kit/ios/getting-started) (project created, UI Kit installed, init + login working, permissions configured). -### **Key Components** +--- -1. **Chat Header** – Displays recipient details and optional call/video call buttons. -2. **Message View** – Shows real-time chat history. -3. **Message Input Box** – Enables users to send messages, media, and reactions. +## What You're Building -*** +Three components stacked vertically: -## **Step-by-Step Guide** +1. **Chat header** — displays recipient name, avatar, online status, and optional call buttons +2. **Message list** — real-time chat history with scrolling +3. **Message composer** — text input with media, emojis, and reactions -### **Step 1: Setup SceneDelegate.swift** +--- -Ensure UI Kit is initialized and the user is logged in before presenting the message view. +## Step 1 — Setup SceneDelegate -```swift SceneDelegate.swift highlight={15-17} lines +Fetch the user (or group) after login and launch directly into the messages view. + +```swift title="SceneDelegate.swift" highlight={13-15,34} lines import UIKit import CometChatUIKitSwift import CometChatSDK -import CometChatCallsSDK class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - guard let windowScene = (scene as? UIWindowScene) else { return } let uikitSettings = UIKitSettings() - .set(appID: "<#Enter Your App ID Here#>") - .set(region: "<#Enter Your Region Code Here#>") - .set(authKey: "<#Enter Your AuthKey Here#>") + .set(appID: "APP_ID") // Replace with your App ID + .set(region: "REGION") // Replace with your Region + .set(authKey: "AUTH_KEY") // Replace with your Auth Key (dev only) .subscribePresenceForAllUsers() .build() CometChatUIKit.init(uiKitSettings: uikitSettings) { result in switch result { case .success: - debugPrint("CometChat UI Kit initialization succeeded") + debugPrint("CometChat initialized") let uid = "cometchat-uid-1" CometChatUIKit.login(uid: uid) { loginResult in switch loginResult { case .success: - debugPrint("CometChat UI Kit login succeeded") + debugPrint("Login successful") DispatchQueue.main.async { [weak self] in - guard let self = self else { return } - self.setUpOneOneOrGroupConversation(windowScene: windowScene, uid: "cometchat-uid-2") + self?.setUpOneOneOrGroupConversation( + windowScene: windowScene, + uid: "cometchat-uid-2" // The user to chat with + ) } case .onError(let error): @@ -72,60 +86,78 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { } case .failure(let error): - debugPrint("Initialization failed: \(error.localizedDescription)") + debugPrint("Init failed: \(error.localizedDescription)") } } } - func setUpOneOneOrGroupConversation(windowScene: UIWindowScene, uid : String) { + func setUpOneOneOrGroupConversation(windowScene: UIWindowScene, uid: String) { CometChat.getUser(UID: uid) { user in - DispatchQueue.main.async { let messagesVC = MessagesVC() - let navController = UINavigationController(rootViewController: messagesVC) messagesVC.user = user + + let navController = UINavigationController(rootViewController: messagesVC) self.window = UIWindow(windowScene: windowScene) self.window?.rootViewController = navController self.window?.makeKeyAndVisible() } } onError: { error in - + debugPrint("Failed to fetch user: \(error?.description ?? "")") } + } +} +``` +Key points: +- `CometChat.getUser(UID:)` fetches the user object from the SDK — you need a real user object, not a manually constructed one. +- The highlighted lines show where to set the credentials and the UID of the user to chat with. + +--- + +## Switching Between User and Group Chat + +To load a group chat instead of one-to-one, replace `getUser` with `getGroup`: + +```swift highlight={2} lines +func setUpGroupConversation(windowScene: UIWindowScene, guid: String) { + CometChat.getGroup(GUID: guid) { group in + DispatchQueue.main.async { + let messagesVC = MessagesVC() + messagesVC.group = group + + let navController = UINavigationController(rootViewController: messagesVC) + self.window = UIWindow(windowScene: windowScene) + self.window?.rootViewController = navController + self.window?.makeKeyAndVisible() + } + } onError: { error in + debugPrint("Failed to fetch group: \(error?.description ?? "")") } - } ``` -*** +--- -### **Step 2: Create MessagesVC.swift** +## Step 2 — Create MessagesVC -This view controller handles chat between users or within groups. +Create a new file `MessagesVC.swift`. This view controller assembles the header, message list, and composer. -```swift MessagesVC.swift lines +```swift title="MessagesVC.swift" lines import UIKit import CometChatSDK import CometChatUIKitSwift -/// A view controller that displays a chat interface using CometChat components class MessagesVC: UIViewController { // MARK: - Properties - - /// The user entity for one-on-one chats var user: User? - - /// The group entity for group chats var group: Group? // MARK: - UI Components - - /// Header view displaying user/group information private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { @@ -135,25 +167,9 @@ class MessagesVC: UIViewController { return view }() - /// Message input composer view - private lazy var composerView: CometChatMessageComposer = { - let composer = CometChatMessageComposer() - composer.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type - if let user = user { - composer.set(user: user) - } else if let group = group { - composer.set(group: group) - } - composer.set(controller: self) - return composer - }() - - /// List view displaying chat messages private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { @@ -163,8 +179,19 @@ class MessagesVC: UIViewController { return listView }() - // MARK: - Lifecycle Methods + private lazy var composerView: CometChatMessageComposer = { + let composer = CometChatMessageComposer() + composer.translatesAutoresizingMaskIntoConstraints = false + if let user = user { + composer.set(user: user) + } else if let group = group { + composer.set(group: group) + } + composer.set(controller: self) + return composer + }() + // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() configureView() @@ -176,34 +203,29 @@ class MessagesVC: UIViewController { navigationController?.setNavigationBarHidden(false, animated: true) } - // MARK: - Private Methods - - /// Configure basic view properties + // MARK: - Setup private func configureView() { view.backgroundColor = .systemBackground navigationController?.setNavigationBarHidden(true, animated: false) } - /// Set up view hierarchy and constraints private func setupLayout() { - // Add subviews to the view hierarchy [headerView, messageListView, composerView].forEach { view.addSubview($0) } - // Set up constraints NSLayoutConstraint.activate([ - // Header view constraints + // Header headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), headerView.heightAnchor.constraint(equalToConstant: 50), - // Message list view constraints + // Message list messageListView.topAnchor.constraint(equalTo: headerView.bottomAnchor), messageListView.leadingAnchor.constraint(equalTo: view.leadingAnchor), messageListView.trailingAnchor.constraint(equalTo: view.trailingAnchor), messageListView.bottomAnchor.constraint(equalTo: composerView.topAnchor), - // Composer view constraints + // Composer composerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), composerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), composerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) @@ -212,12 +234,33 @@ class MessagesVC: UIViewController { } ``` -*** +How it works: +- `CometChatMessageHeader` shows user/group info and back button +- `CometChatMessageList` displays messages with real-time updates +- `CometChatMessageComposer` handles text input, media, and reactions +- Pass either `user` or `group` to each component, never both -## **Next Steps** +--- + +## Step 3 — Run the Project -### **Enhance the User Experience** +Build and run in Xcode. You should see the chat window load directly with the conversation for the UID you set. -* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. +--- -*** +## Next Steps + + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + diff --git a/ui-kit/ios/ios-tab-based-chat.mdx b/ui-kit/ios/ios-tab-based-chat.mdx index 8c6d7b047..a596f5168 100644 --- a/ui-kit/ios/ios-tab-based-chat.mdx +++ b/ui-kit/ios/ios-tab-based-chat.mdx @@ -1,41 +1,55 @@ --- -title: "Building A Tab Based Messaging UI In iOS" -sidebarTitle: "Tab Based Chat Experience" +title: "Tab-Based Chat" +sidebarTitle: "Tab-Based Chat" +description: "Build a tab-based messaging UI with chats, calls, users, and groups in iOS with CometChat UI Kit." --- -This guide walks you through creating a **tab-based messaging interface** in your **iOS application** using **CometChat UI Kit for iOS**. The UI includes tabs for **Chats**, **Calls**, **Users**, and **Groups**, offering an organized and fluid experience. + -*** +| Field | Value | +| --- | --- | +| Package | `CometChatUIKitSwift` | +| Framework | UIKit / SwiftUI | +| Components | `CometChatConversations`, `CometChatCallLogs`, `CometChatUsers`, `CometChatGroups`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | UITabBarController with Chats, Calls, Users, Groups tabs | +| Prerequisite | Complete [iOS Integration](/ui-kit/ios/getting-started) Steps 1–4 first | +| Pattern | Full-featured messaging app with multiple sections | -## **User Interface Preview** + + +This guide builds a tabbed messaging UI — Chats, Calls, Users, and Groups tabs using `UITabBarController`. Good for full-featured apps that need more than just conversations. + +This assumes you've already completed [iOS Integration](/ui-kit/ios/getting-started) (project created, UI Kit installed, init + login working, permissions configured). -This layout contains: +--- -1. **Conversations** – Lists all recent chats. -2. **Calls** – Displays call logs. -3. **Users** – Lists available users. -4. **Groups** – Lists available groups. +## What You're Building -*** +Four tabs working together: -## **Step-by-Step Guide** +1. **Chats** — conversation list with push navigation to messages +2. **Calls** — call logs history +3. **Users** — list of available users +4. **Groups** — list of available groups + +--- -### **Step 1: Initialize UIKit in `SceneDelegate.swift`** +## Step 1 — Setup SceneDelegate -Ensure UIKit is initialized and the user is logged in before presenting the tabbed view. +Initialize CometChat and launch the tabbed view after login. -```swift SceneDelegate.swift highlight={5-7} lines +```swift title="SceneDelegate.swift" highlight={5-7} lines func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } let uikitSettings = UIKitSettings() - .set(appID: "<#Enter Your App ID Here#>") - .set(region: "<#Enter Your Region Code Here#>") - .set(authKey: "<#Enter Your AuthKey Here#>") + .set(appID: "APP_ID") // Replace with your App ID + .set(region: "REGION") // Replace with your Region + .set(authKey: "AUTH_KEY") // Replace with your Auth Key (dev only) .subscribePresenceForAllUsers() .build() @@ -59,16 +73,14 @@ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options conn } ``` -*** +--- -### **Step 2: Setup Tab Bar** +## Step 2 — Setup Tab Bar -Create a method to display the tab layout. +Create the `UITabBarController` with all four tabs. Each tab has its own navigation controller. -```swift SceneDelegate.swift lines +```swift title="SceneDelegate.swift" lines func setupTabbedView(windowScene: UIWindowScene) { - - // Create the main Tab Bar Controller let tabBarController = UITabBarController() tabBarController.tabBar.backgroundColor = .white @@ -81,7 +93,6 @@ func setupTabbedView(windowScene: UIWindowScene) { tag: 0 ) - // Handle item click inside conversation list conversationsVC.set(onItemClick: { [weak conversationsNav] conversation, indexPath in let messagesVC = MessagesVC() messagesVC.group = conversation.conversationWith as? Group @@ -117,7 +128,6 @@ func setupTabbedView(windowScene: UIWindowScene) { tag: 3 ) - // Assign all navigation controllers to the Tab Bar tabBarController.viewControllers = [ conversationsNav, callLogsNav, @@ -125,46 +135,41 @@ func setupTabbedView(windowScene: UIWindowScene) { groupsNav ] - // Ensures layout includes space for opaque bars like the navigation bar tabBarController.extendedLayoutIncludesOpaqueBars = true - // Setup and display main window with tabBarController as root window = UIWindow(windowScene: windowScene) window?.rootViewController = tabBarController window?.makeKeyAndVisible() - } ``` -*** +Key points: +- Each tab wraps its view controller in a `UINavigationController` for push navigation +- `onItemClick` on conversations pushes to the messages view +- `hidesBottomBarWhenPushed = true` hides the tab bar when viewing messages +- SF Symbols are used for tab icons — customize as needed + +--- -### **Step 3: Create `MessagesVC.swift`** +## Step 3 — Create MessagesVC -This view controller handles chat between users or within groups. +Create a new file `MessagesVC.swift`. This view controller assembles the header, message list, and composer. -```swift MessagesVC.swift lines +```swift title="MessagesVC.swift" lines import UIKit import CometChatSDK import CometChatUIKitSwift -/// A view controller that displays a chat interface using CometChat components class MessagesVC: UIViewController { // MARK: - Properties - - /// The user entity for one-on-one chats var user: User? - - /// The group entity for group chats var group: Group? // MARK: - UI Components - - /// Header view displaying user/group information private lazy var headerView: CometChatMessageHeader = { let view = CometChatMessageHeader() view.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { view.set(user: user) } else if let group = group { @@ -174,25 +179,9 @@ class MessagesVC: UIViewController { return view }() - /// Message input composer view - private lazy var composerView: CometChatMessageComposer = { - let composer = CometChatMessageComposer() - composer.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type - if let user = user { - composer.set(user: user) - } else if let group = group { - composer.set(group: group) - } - composer.set(controller: self) - return composer - }() - - /// List view displaying chat messages private lazy var messageListView: CometChatMessageList = { let listView = CometChatMessageList() listView.translatesAutoresizingMaskIntoConstraints = false - // Configure for the appropriate conversation type if let user = user { listView.set(user: user) } else if let group = group { @@ -202,8 +191,19 @@ class MessagesVC: UIViewController { return listView }() - // MARK: - Lifecycle Methods + private lazy var composerView: CometChatMessageComposer = { + let composer = CometChatMessageComposer() + composer.translatesAutoresizingMaskIntoConstraints = false + if let user = user { + composer.set(user: user) + } else if let group = group { + composer.set(group: group) + } + composer.set(controller: self) + return composer + }() + // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() configureView() @@ -215,34 +215,29 @@ class MessagesVC: UIViewController { navigationController?.setNavigationBarHidden(false, animated: true) } - // MARK: - Private Methods - - /// Configure basic view properties + // MARK: - Setup private func configureView() { view.backgroundColor = .systemBackground navigationController?.setNavigationBarHidden(true, animated: false) } - /// Set up view hierarchy and constraints private func setupLayout() { - // Add subviews to the view hierarchy [headerView, messageListView, composerView].forEach { view.addSubview($0) } - // Set up constraints NSLayoutConstraint.activate([ - // Header view constraints + // Header headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), headerView.heightAnchor.constraint(equalToConstant: 50), - // Message list view constraints + // Message list messageListView.topAnchor.constraint(equalTo: headerView.bottomAnchor), messageListView.leadingAnchor.constraint(equalTo: view.leadingAnchor), messageListView.trailingAnchor.constraint(equalTo: view.trailingAnchor), messageListView.bottomAnchor.constraint(equalTo: composerView.topAnchor), - // Composer view constraints + // Composer composerView.leadingAnchor.constraint(equalTo: view.leadingAnchor), composerView.trailingAnchor.constraint(equalTo: view.trailingAnchor), composerView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) @@ -251,12 +246,27 @@ class MessagesVC: UIViewController { } ``` -*** +--- -## **Next Steps** +## Step 4 — Run the Project -### **Enhance the User Experience** +Build and run in Xcode. You should see the tab bar at the bottom with Chats, Calls, Users, and Groups. Tap any conversation to push to the messages view. + +--- -* **[Advanced Customizations](/ui-kit/ios/theme-introduction)** – Personalize the chat UI to align with your brand. +## Next Steps -*** + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + From 4881cd565e9a699af94b026a440005cc3237b641 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 13:15:03 +0530 Subject: [PATCH 062/106] Update ai-features.mdx --- ui-kit/ios/ai-features.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/ios/ai-features.mdx b/ui-kit/ios/ai-features.mdx index 0c4f01b71..be1e15569 100644 --- a/ui-kit/ios/ai-features.mdx +++ b/ui-kit/ios/ai-features.mdx @@ -1,6 +1,6 @@ --- title: "AI Features" -sidebarTitle: "AI" +sidebarTitle: "Smart Chat Features" description: "Complete guide to AI-powered chat features in iOS apps - conversation starters, smart replies, and summaries" --- From 8445bec2f651ac7083f00fe55109a8269183eda1 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 13:35:39 +0530 Subject: [PATCH 063/106] theming --- ui-kit/ios/color-resources.mdx | 29 +++++++++++++-- ui-kit/ios/component-styling.mdx | 28 ++++++++++++-- ui-kit/ios/localize.mdx | 31 +++++++++++++--- ui-kit/ios/message-bubble-styling.mdx | 29 ++++++++++++--- ui-kit/ios/sound-manager.mdx | 30 +++++++++++++++ ui-kit/ios/theme-introduction.mdx | 53 ++++++++++++++------------- 6 files changed, 159 insertions(+), 41 deletions(-) diff --git a/ui-kit/ios/color-resources.mdx b/ui-kit/ios/color-resources.mdx index deb771630..25f2e3c81 100644 --- a/ui-kit/ios/color-resources.mdx +++ b/ui-kit/ios/color-resources.mdx @@ -4,6 +4,21 @@ sidebarTitle: "Color Resources" description: "Complete guide to customizing colors in CometChat iOS UI Kit - themes, dark mode, and branding" --- + + +| Field | Value | +| --- | --- | +| Platform | iOS UI Kit | +| Theme Class | `CometChatTheme` | +| Primary Color | `CometChatTheme.primaryColor` — Main brand color (#6852D6 default) | +| Background Colors | `backgroundColor01`, `backgroundColor02`, `backgroundColor03` | +| Text Colors | `textColorPrimary`, `textColorSecondary`, `textColorTertiary` | +| Alert Colors | `successColor`, `errorColor`, `warningColor`, `infoColor` | +| Dark Mode | Use `UIColor { traitCollection in }` for dynamic colors | +| Apply Timing | Set theme before `CometChatUIKit.init()` | + + + ## Overview CometChat UI Kit uses `CometChatTheme` to manage colors across all components. Colors automatically adapt to Light and Dark mode, ensuring a consistent experience. @@ -315,6 +330,14 @@ extension UIColor { ## Related -- [Component Styling](/ui-kit/ios/component-styling) - Style individual components -- [Theme Introduction](/ui-kit/ios/theme-introduction) - Complete theming guide -- [Getting Started](/ui-kit/ios/getting-started) - Initial setup + + + Style individual components + + + Complete theming guide + + + Initial setup + + diff --git a/ui-kit/ios/component-styling.mdx b/ui-kit/ios/component-styling.mdx index f3308ea0a..840811fb0 100644 --- a/ui-kit/ios/component-styling.mdx +++ b/ui-kit/ios/component-styling.mdx @@ -4,6 +4,20 @@ sidebarTitle: "Component Styling" description: "Complete guide to styling CometChat iOS UI Kit components - colors, fonts, and custom appearances" --- + + +| Field | Value | +| --- | --- | +| Platform | iOS UI Kit | +| Global Styling | `CometChatConversations.style.titleColor = UIColor` | +| Instance Styling | `let style = ConversationsStyle(); conversations.style = style` | +| Style Classes | `ConversationsStyle`, `UsersStyle`, `GroupsStyle`, `MessageListStyle`, etc. | +| Base Styles | `AvatarStyle`, `BadgeStyle`, `StatusIndicatorStyle`, `ReceiptStyle` | +| Apply Timing | Global styles before `CometChatUIKit.init()` | +| Precedence | Instance styles override global styles | + + + ## Overview Every CometChat component can be styled to match your app's design. You can apply styles globally (affects all instances) or per-instance (affects one component). @@ -547,6 +561,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate { ## Related -- [Color Resources](/ui-kit/ios/color-resources) - Theme colors -- [Theme Introduction](/ui-kit/ios/theme-introduction) - Complete theming -- [Components Overview](/ui-kit/ios/components-overview) - All components + + + Theme colors + + + Complete theming + + + All components + + diff --git a/ui-kit/ios/localize.mdx b/ui-kit/ios/localize.mdx index af0ef6c2a..04f624f00 100644 --- a/ui-kit/ios/localize.mdx +++ b/ui-kit/ios/localize.mdx @@ -4,6 +4,21 @@ sidebarTitle: "Localization" description: "Adapt CometChat UI Kit to different languages and customize date/time formatting for your iOS application" --- + + +| Field | Value | +| --- | --- | +| Platform | iOS UI Kit | +| Localize Class | `CometChatLocalize` | +| Set Locale | `CometChatLocalize.set(locale: .french)` | +| Get Locale | `CometChatLocalize.getLocale()` | +| Supported Languages | 17 languages (en, fr, de, es, hi, ru, pt, zh, ja, ko, tr, ms, sv, lt, hu, nl) | +| Override Strings | Define same key in app's `Localizable.strings` | +| DateTime Formatter | `CometChatUIKit.dateTimeFormatter` or component-level | +| DateTime Closures | `time`, `today`, `yesterday`, `lastweek`, `otherDay`, `minute`, `minutes`, `hour`, `hours` | + + + ## Overview CometChat UI Kit provides language localization to adapt to the language of a specific country or region. The `CometChatLocalize` class allows you to detect the language of your users based on their browser or device settings, and set the language accordingly. @@ -241,8 +256,14 @@ The `CometChatDateTimeFormatter` gives developers fine-grained control over how ## Next Steps -- [Theme Introduction](/ui-kit/ios/theme-introduction) — Customize the visual appearance of UI components -- [Color Resources](/ui-kit/ios/color-resources) — Configure color schemes for your app -- [Component Styling](/ui-kit/ios/component-styling) — Apply custom styles to individual components - ---- + + + Customize the visual appearance of UI components + + + Configure color schemes for your app + + + Apply custom styles to individual components + + diff --git a/ui-kit/ios/message-bubble-styling.mdx b/ui-kit/ios/message-bubble-styling.mdx index f4ba87a39..c7a60e5d9 100644 --- a/ui-kit/ios/message-bubble-styling.mdx +++ b/ui-kit/ios/message-bubble-styling.mdx @@ -4,6 +4,19 @@ sidebarTitle: "Message Bubble Styling" description: "Customize the appearance of incoming and outgoing message bubbles in CometChat UI Kit for iOS" --- + + +| Field | Value | +| --- | --- | +| Platform | iOS UI Kit | +| Incoming Style | `CometChatMessageBubble.style.incoming` | +| Outgoing Style | `CometChatMessageBubble.style.outgoing` | +| Global Properties | `backgroundColor`, `borderWidth`, `borderColor`, `cornerRadius` | +| Bubble Types | `textBubbleStyle`, `imageBubbleStyle`, `videoBubbleStyle`, `audioBubbleStyle`, `fileBubbleStyle`, `pollBubbleStyle`, `linkPreviewBubbleStyle`, `deleteBubbleStyle`, `aiAssistantBubbleStyle` | +| Action Bubble | `CometChatMessageBubble.actionBubbleStyle` | + + + ## Overview The MessageBubble styling API allows developers to customize the appearance of incoming and outgoing message bubbles globally or at the component level. This includes various message types such as text, image, video, audio, file, and document bubbles. @@ -374,8 +387,14 @@ CometChatMessageBubble.style.outgoing.aiAssistantBubbleStyle.backgroundColor = U ## Next Steps -- [Message List](/ui-kit/ios/message-list) — Display and customize the message list component -- [Message Composer](/ui-kit/ios/message-composer) — Customize the message input component -- [Component Styling](/ui-kit/ios/component-styling) — Learn about global styling options - ---- + + + Display and customize the message list component + + + Customize the message input component + + + Learn about global styling options + + diff --git a/ui-kit/ios/sound-manager.mdx b/ui-kit/ios/sound-manager.mdx index ea6bc926a..00ce47729 100644 --- a/ui-kit/ios/sound-manager.mdx +++ b/ui-kit/ios/sound-manager.mdx @@ -4,6 +4,20 @@ sidebarTitle: "Sound Manager" description: "Manage and play audio for messages and calls in CometChat UI Kit for iOS" --- + + +| Field | Value | +| --- | --- | +| Platform | iOS UI Kit | +| Class | `CometChatSoundManager` | +| Purpose | Manages audio playback for messages and calls | +| Play Method | `play(sound: Sound, customSound: URL?)` | +| Pause Method | `pause()` | +| Sound Types | `.incomingMessage`, `.outgoingMessage`, `.incomingCall`, `.outgoingCall` | +| Custom Sound | Pass `URL` to override default sounds | + + + ## Overview `CometChatSoundManager` is a helper class that manages audio playback in the CometChat UI Kit. It handles sound events for incoming and outgoing messages and calls, supporting both default sounds and custom audio files. @@ -94,3 +108,19 @@ The `Sound` enum provides the following options: --- By using `CometChatSoundManager`, you can enhance the user experience in your chat application by integrating audible cues for chat interactions. + +--- + +## Next Steps + + + + Customize the visual appearance + + + Adapt to different languages + + + Style individual components + + diff --git a/ui-kit/ios/theme-introduction.mdx b/ui-kit/ios/theme-introduction.mdx index f9b13b700..2b9500cdf 100644 --- a/ui-kit/ios/theme-introduction.mdx +++ b/ui-kit/ios/theme-introduction.mdx @@ -4,31 +4,20 @@ sidebarTitle: "Introduction" description: "Create visually consistent and customizable user interfaces with CometChat theming for iOS" --- - -```json -{ - "platform": "iOS UI Kit", - "package": "CometChatUIKitSwift", - "themeSystem": { - "class": "CometChatTheme", - "description": "Global theming system for all CometChat components" - }, - "globalStyles": { - "primaryColor": "UIColor - Main accent color", - "backgroundColor": "UIColor - Background color", - "borderColor": "UIColor - Border color" - }, - "colorCustomization": { - "method": "CometChatTheme.primaryColor = UIColor", - "example": "CometChatTheme.primaryColor = UIColor(hex: \"#F76808\")" - }, - "typographyCustomization": { - "class": "CometChatTypography", - "properties": ["Body.regular", "Body.bold", "Heading.regular"], - "example": "CometChatTypography.Body.regular = UIFont.systemFont(ofSize: 18, weight: .bold)" - } -} -``` + + +| Field | Value | +| --- | --- | +| Platform | iOS UI Kit | +| Package | `CometChatUIKitSwift` | +| Theme Class | `CometChatTheme` — Global theming system for all CometChat components | +| Primary Color | `CometChatTheme.primaryColor = UIColor` | +| Background Color | `CometChatTheme.backgroundColor` | +| Border Color | `CometChatTheme.borderColor` | +| Typography Class | `CometChatTypography` | +| Typography Properties | `Body.regular`, `Body.bold`, `Heading.regular` | +| Example | `CometChatTheme.primaryColor = UIColor(hex: "#F76808")` | + ## Overview @@ -99,3 +88,17 @@ CometChatTheme.primaryColor = UIColor(hex: "#F76808") --- + +## Next Steps + + + + Customize theme colors and dark mode + + + Style individual components + + + Customize message bubbles + + From 2b81268e470a9f0183c9460be13e93bca0d290cb Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 13:38:41 +0530 Subject: [PATCH 064/106] migrations guides --- docs.json | 7 +- ui-kit/ios/property-changes.mdx | 729 ------------------------------- ui-kit/ios/upgrading-from-v4.mdx | 530 ++++++++++++++++++++-- 3 files changed, 490 insertions(+), 776 deletions(-) delete mode 100644 ui-kit/ios/property-changes.mdx diff --git a/docs.json b/docs.json index 30be5bb91..883c4c1c4 100644 --- a/docs.json +++ b/docs.json @@ -1266,8 +1266,7 @@ { "group": "Migration Guide", "pages": [ - "ui-kit/ios/upgrading-from-v4", - "ui-kit/ios/property-changes" + "ui-kit/ios/upgrading-from-v4" ] }, "ui-kit/ios/link/sample", @@ -5211,6 +5210,10 @@ "source": "/ui-kit/android/property-changes", "destination": "/ui-kit/android/upgrading-from-v4" }, + { + "source": "/ui-kit/ios/property-changes", + "destination": "/ui-kit/ios/upgrading-from-v4" + }, { "source": "/ai/overview", "destination": "/fundamentals/ai-user-copilot/overview" diff --git a/ui-kit/ios/property-changes.mdx b/ui-kit/ios/property-changes.mdx deleted file mode 100644 index 695f1d34a..000000000 --- a/ui-kit/ios/property-changes.mdx +++ /dev/null @@ -1,729 +0,0 @@ ---- -title: "Property Changes" -sidebarTitle: "Property Changes" -description: "Migration guide for property changes between UI Kit versions for iOS" ---- - -This document outlines the property changes between v4 and v5 of the CometChat UI Kit for iOS. Use this guide to update your implementation when migrating to the latest version. - ---- - -## Conversations - -### New Properties - -| Name | Type | Description | -| --------------------------- | ------------- | ----------------------------------------------------------------------------------- | -| hideNavigationBar | Bool | Hides or shows the navigation bar in the conversations screen. | -| hideSearch | Bool | Hides the search bar in the conversations screen. | -| hideLoadingState | Bool | Hides the loading state indicator. | -| hideDeleteConversationOption | Bool | Hides the option to delete a conversation. | -| hideGroupType | Bool | Hides the group type indicator (private/public). | -| backgroundDrawable | UIImage | Sets a background image for the conversation screen. | -| separatorColor | UIColor | Sets the color of separators in the conversation list. | -| separatorWidth | CGFloat | Sets the width of separators in the conversation list. | -| errorTextColor | UIColor | Sets the color of error messages in the conversation UI. | -| lastMessageTextColor | UIColor | Sets the color of the last message text in the conversation list. | -| typingIndicatorColor | UIColor | Sets the color of the typing indicator in the conversation UI. | -| lastMessageAppearance | UIFont | Customizes the appearance of the last message text in the list. | -| threadIndicatorAppearance | UIFont | Customizes the appearance of thread indicators in the list. | -| dateTimeFormatter.time | Closure | Formats a timestamp as a standard time (e.g., "12:30 PM"). | -| dateTimeFormatter.today | Closure | Formats messages sent today. | -| dateTimeFormatter.yesterday | Closure | Formats yesterday's messages. | -| dateTimeFormatter.lastweek | Closure | Formats messages within the last week. | -| dateTimeFormatter.otherDay | Closure | Formats dates older than last week. | -| dateTimeFormatter.minute | Closure | Formats "a minute ago". | -| dateTimeFormatter.minutes | Closure | Formats "x minutes ago". | -| dateTimeFormatter.hour | Closure | Formats "an hour ago". | -| dateTimeFormatter.hours | Closure | Formats "x hours ago". | -| set(OnItemLongClick:) | Method | Triggered when you long press on a ListItem of the Conversations component. | -| set(onEmpty:) | Method | Triggered when the conversations list is empty. | - -### Renamed Properties - -| v4 Name | v5 Name | Type | Description | -| ----------------------- | ------------------ | -------- | ------------------------------------------------------------------------------------ | -| hide(error: Bool) | hideErrorView | Bool | Hides the error state view. | -| show(backButton: Bool) | hideBackButton | Bool | Controls visibility of the back button (logic inverted). | -| hide(receipt: Bool) | hideReceipts | Bool | Hides message read/delivery receipts. | -| disable(userPresence: Bool) | hideUserStatus | Bool | Hides the online/offline status of users. | -| setOnItemClick | set(OnItemClick:) | Method | Triggered when clicking on a ListItem. | -| setOnBack | set(onBack:) | Method | Override action when back button is pressed. | -| setOnSelection | set(onSelection:) | Method | Triggered upon completion of selection. | -| setOnError | set(onError:) | Method | Override action when an error occurs. | - - -### Removed Properties - -| Name | Type | Description | -| -------------------- | ------------ | ----------------------------------------------------------------------------------- | -| hide(separator: Bool) | Bool | Controlled visibility of separators (replaced by style properties). | -| disable(typing: Bool) | Bool | Toggled visibility of typing indicator. | -| setDatePattern | Method | Set custom date pattern (replaced by dateTimeFormatter object). | -| protectedGroupIcon | UIImage | Icon shown for password protected groups. | -| sentIcon | UIImage | Receipt icon shown when message status is sent. | -| deliveredIcon | UIImage | Receipt icon shown when message status is delivered. | -| readIcon | UIImage | Receipt icon shown when message status is read. | - ---- - -## Users - -### New Properties - -| Name | Type | Description | -| -------------------------------- | --------------------------------- | -------------------------------------------------------------------------------------------------- | -| set(options:) | (User) -> [CometChatUserOption] | Defines custom options for each user. | -| add(options:) | [CometChatUserOption] | Dynamically adds options to users. | -| set(leadingView:) | (User) -> UIView | Custom leading view for each user in the fetched list. | -| set(titleView:) | (User) -> UIView | Custom title view for each user in the fetched list. | -| set(trailView:) | (User) -> UIView | Custom trailing view for each user in the fetched list. | -| set(onEmpty:) | () -> Void | Triggered when the users list is empty. | -| hideErrorView | Bool | Hides the error state view. | -| hideNavigationBar | Bool | Hides or shows the navigation bar. | -| hideBackButton | Bool | Hides the back button. | -| hideLoadingState | Bool | Hides the loading state indicator. | -| hideUserStatus | Bool | Hides the online/offline status of users. | -| hideSectionHeader | Bool | Hides the section header indicating initials of users. | -| hideSearch | Bool | Hides the search bar. | -| set(searchKeyword:) | String | Sets a search keyword for filtering users. | -| set(userRequestBuilder:) | UsersRequest.UsersRequestBuilder | Sets a custom request builder for fetching users. | -| set(searchRequestBuilder:) | UsersRequest.UsersRequestBuilder | Sets a custom request builder for searching users. | -| listItemSelectedImage | UIImage | Image shown when a list item is selected. | -| listItemDeSelectedImage | UIImage | Image shown when a list item is deselected. | -| searchIconTintColor | UIColor | Tint color for the search icon. | -| searchBarStyle | UISearchBar.Style | Style of the search bar. | -| searchTintColor | UIColor? | Tint color for the search bar elements. | -| searchBarTintColor | UIColor? | Background color for the search bar (excluding text input). | -| searchBarPlaceholderTextColor | UIColor? | Color of the placeholder text in the search bar. | -| searchBarPlaceholderTextFont | UIFont? | Font of the placeholder text in the search bar. | -| searchBarTextColor | UIColor? | Color of the entered text in the search bar. | -| searchBarTextFont | UIFont? | Font of the entered text in the search bar. | -| searchBarBackgroundColor | UIColor? | Background color of the search bar's text input area. | -| searchBarCancelIconTintColor | UIColor? | Tint color for the cancel button in the search bar. | -| searchBarCrossIconTintColor | UIColor? | Tint color for the clear (cross) button in the search bar. | -| backgroundColor | UIColor | Background color for the entire screen or view. | -| borderWidth | CGFloat | Border width for the search bar or container. | -| borderColor | UIColor | Color of the border. | -| cornerRadius | CometChatCornerStyle | Corner radius for search bar or other elements. | -| titleColor | UIColor | Text color for title elements. | -| titleFont | UIFont | Font for title text. | -| largeTitleColor | UIColor | Text color for large titles. | -| largeTitleFont | UIFont? | Font for large titles. | -| navigationBarTintColor | UIColor | Tint color for the navigation bar background. | -| navigationBarItemsTintColor | UIColor | Tint color for navigation bar items. | -| errorTitleTextFont | UIFont | Font for the error title. | -| errorTitleTextColor | UIColor | Text color for the error title. | -| errorSubTitleFont | UIFont | Font for the subtitle of error messages. | -| errorSubTitleTextColor | UIColor | Text color for the subtitle of error messages. | -| retryButtonTextColor | UIColor | Text color for the retry button. | -| retryButtonTextFont | UIFont | Font for the retry button text. | -| retryButtonBackgroundColor | UIColor | Background color for the retry button. | -| retryButtonBorderColor | UIColor | Border color for the retry button. | -| retryButtonBorderWidth | CGFloat | Border width for the retry button. | -| retryButtonCornerRadius | CometChatCornerStyle? | Corner radius for the retry button. | -| emptyTitleTextFont | UIFont | Font for the empty state title. | -| emptyTitleTextColor | UIColor | Text color for the empty state title. | -| emptySubTitleFont | UIFont | Font for the subtitle in the empty state. | -| emptySubTitleTextColor | UIColor | Text color for the subtitle in the empty state. | -| tableViewSeparator | UIColor | Color for the table view separator. | -| listItemTitleTextColor | UIColor | Text color for list item titles. | -| listItemTitleFont | UIFont | Font for list item titles. | -| listItemSubTitleTextColor | UIColor | Text color for list item subtitles. | -| listItemSubTitleFont | UIFont | Font for list item subtitles. | -| listItemBackground | UIColor | Background color for individual list items. | -| listItemBorderWidth | CGFloat | Border width for individual list items. | -| listItemBorderColor | UIColor | Border color for individual list items. | -| listItemCornerRadius | CometChatCornerStyle | Corner radius for list items. | -| listItemSelectionImageTint | UIColor | Tint color for selection indicator in list items. | -| listItemSelectedBackground | UIColor | Background color for selected list items. | -| listItemDeSelectedImageTint | UIColor | Tint color for the deselected state image. | -| headerTitleColor | UIColor | Text color for section header titles. | -| headerTitleFont | UIFont | Font for section header titles. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| ---------------------- | ------------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------- | -| set(listItemView:) | (User) -> UIView | Custom list item view for each user in the list. | setListItemView | -| set(subtitleView:) | (User) -> UIView | Custom subtitle view for each user in the fetched list. | setSubtitleView | -| set(emptyView:) | UIView | Custom empty state view when the user list is empty. | setEmptyStateView | -| set(errorView:) | UIView | Custom error state view when an error occurs while fetching users. | setErrorStateView | -| set(onItemClick:) | (User) -> Void | Triggered when you click on a ListItem. | setOnItemClick | -| set(onItemLongClick:) | (User) -> Void | Triggered when you long press on a ListItem. | setOnItemLongClick | -| set(onBack:) | () -> Void | Triggered when the back button is pressed. | setOnBack | -| set(onSelection:) | ([User]) -> Void | Triggered on every selection when selection mode is set. | setOnSelection | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | setOnError | - -### Removed Properties - -| Name | Type | Description | -| ------------------------ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------- | -| set(loadingStateView:) | UIActivityIndicatorView.Style | Set size of loading view icon while fetching users. | -| hide(errorText:) | Bool | Hide error text on fetching users. | -| show(backButton:) | Bool | Toggle visibility for back button. | -| set(searchIcon:) | UIImage? | Set search icon in the search field. | -| hide(search:) | Bool | Toggle visibility for search box. | -| hide(separator:) | Bool | Hide the divider separating user items. | -| disable(userPresence:) | Bool | Control visibility of user online indicator. | -| set(emptyStateText:) | String | Set custom text when fetching users returns an empty list. | -| set(errorStateText:) | String | Set custom text when an error occurs fetching users. | -| set(searchPlaceholder:) | String | Set search placeholder text. | -| set(title:mode:) | String, UINavigationItem.LargeTitleDisplayMode | Set title with display mode. | -| setOnLoad | ([User]) -> Void | Triggered when a user list is fully fetched and displayed. | - - ---- - -## Groups - -### New Properties - -| Name | Type | Description | -| --------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -| set(onSelection:) | Closure | Triggered when selection mode is set. Returns the list of selected groups. | -| set(onEmpty:) | Closure | Triggered when the groups list is empty. | -| setOnLoad | Closure | Triggered when a group list is fully fetched and displayed. | -| listItemSelectedImage | UIImage | Check box image when a list item is selected. | -| listItemDeSelectedImage | UIImage | Check box image when a list item is deselected. | -| searchIconTintColor | UIColor | Tint color for the search icon. | -| searchBarStyle | UISearchBarStyle | Style of the search bar. | -| searchTintColor | UIColor | Tint color for the search bar. | -| searchBarTintColor | UIColor | Background color of the search bar. | -| searchBarPlaceholderTextColor | UIColor | Placeholder text color for the search bar. | -| searchBarPlaceholderTextFont | UIFont | Font for the placeholder text in the search bar. | -| searchBarTextColor | UIColor | Color of the text entered in the search bar. | -| searchBarTextFont | UIFont | Font for the text in the search bar. | -| searchBarBackgroundColor | UIColor | Background color of the search bar. | -| searchBarCancelIconTintColor | UIColor | Tint color for the cancel icon in the search bar. | -| searchBarCrossIconTintColor | UIColor | Tint color for the cross icon in the search bar. | -| backgroundColor | UIColor | Background color of the overall view. | -| borderWidth | CGFloat | Width of the border around the view. | -| borderColor | UIColor | Color of the border around the view. | -| cornerRadius | CometChatCornerStyle | Corner radius settings for the view. | -| titleColor | UIColor | Color for the title text. | -| titleFont | UIFont | Font for the title text. | -| largeTitleColor | UIColor | Color for the large title text. | -| largeTitleFont | UIFont | Font for the large title text. | -| navigationBarTintColor | UIColor | Background color of the navigation bar. | -| navigationBarItemsTintColor | UIColor | Tint color for items in the navigation bar. | -| errorTitleTextFont | UIFont | Font for the error title text. | -| errorTitleTextColor | UIColor | Color of the error title text. | -| errorSubTitleFont | UIFont | Font for the error subtitle text. | -| errorSubTitleTextColor | UIColor | Color of the error subtitle text. | -| retryButtonTextColor | UIColor | Color for the retry button text. | -| retryButtonTextFont | UIFont | Font for the retry button text. | -| retryButtonBackgroundColor | UIColor | Background color for the retry button. | -| retryButtonBorderColor | UIColor | Border color for the retry button. | -| retryButtonBorderWidth | CGFloat | Width of the border around the retry button. | -| retryButtonCornerRadius | CometChatCornerStyle | Corner radius settings for the retry button. | -| emptyTitleTextFont | UIFont | Font for the empty state title text. | -| emptyTitleTextColor | UIColor | Color of the empty state title text. | -| emptySubTitleFont | UIFont | Font for the empty state subtitle text. | -| emptySubTitleTextColor | UIColor | Color of the empty state subtitle text. | -| tableViewSeparator | UIColor | Color of the table view separator. | -| listItemTitleTextColor | UIColor | Color of the title text in list items. | -| listItemTitleFont | UIFont | Font for the title text in list items. | -| listItemSubTitleTextColor | UIColor | Color of the subtitle text in list items. | -| listItemSubTitleFont | UIFont | Font for the subtitle text in list items. | -| listItemBackground | UIColor | Background color for list items. | -| listItemSelectedBackground | UIColor | Background color for selected list items. | -| listItemBorderWidth | CGFloat | Width of the border around list items. | -| listItemBorderColor | UIColor | Color of the border around list items. | -| listItemCornerRadius | CometChatCornerStyle | Corner radius settings for list items. | -| listItemSelectionImageTint | UIColor | Tint color for the selection image in list items. | -| listItemDeSelectedImageTint | UIColor | Tint color for the deselected image in list items. | -| passwordGroupImageTintColor | UIColor | Tint color for the password group image. | -| passwordGroupImageBackgroundColor | UIColor | Background color for the password group image. | -| privateGroupImageTintColor | UIColor | Tint color for the private group image. | -| privateGroupImageBackgroundColor | UIColor | Background color for the private group image. | -| privateGroupIcon | UIImage | Image for a private group icon. | -| protectedGroupIcon | UIImage | Image for a protected group icon. | -| set(groupsRequestBuilder:) | GroupsRequest.GroupsRequestBuilder | Sets the request builder for fetching groups. | -| set(searchRequestBuilder:) | GroupsRequest.GroupsRequestBuilder | Sets the request builder for searching groups. | -| set(searchKeyword:) | String | Sets the search keyword to filter groups. | -| hideErrorView | Bool | Hides the error state view. | -| hideNavigationBar | Bool | Hides or shows the navigation bar. | -| hideSearch | Bool | Hides the search bar. | -| hideBackButton | Bool | Hides the back button. | -| hideLoadingState | Bool | Hides the loading state indicator. | -| hideReceipts | Bool | Hides message read/delivery receipts. | -| hideDeleteConversationOption | Bool | Hides the option to delete a conversation. | -| hideUserStatus | Bool | Hides the online/offline status of users. | -| hideGroupType | Bool | Hides the group type (private/public). | -| set(options:) | (Group?) -> [CometChatGroupOption] | Defines custom options for each group. | -| add(options:) | (Group?) -> [CometChatGroupOption] | Dynamically adds options to groups. | -| set(leadingView:) | (Group?) -> UIView | Modifies the leading view of a group cell. | -| set(titleView:) | (Group?) -> UIView | Customizes the title view of a group cell. | -| set(trailView:) | (Group?) -> UIView | Modifies the trailing view of a group cell. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| --------------------- | --------------------- | ------------------------------------------------------------------- | --------------------- | -| set(onItemClick:) | Closure | Triggered when you click on a ListItem. | SetOnItemClick | -| set(OnItemLongClick:) | Closure | Triggered when you long press on a ListItem. | SetOnItemLongClick | -| set(onError:) | Closure | Triggered when an error occurs. | SetOnError | -| set(onBack:) | Closure | Triggered when the back button is pressed. | SetOnBack | -| SetListItemView | (Group?) -> UIView | Assigns a custom ListItem to the Groups Component. | setListItemView | -| SetSubTitleView | (Group?) -> UIView | Customizes the subtitle view for each group item. | setSubtitleView | - -### Removed Properties - -No properties were removed in v5. All v4 properties have been retained (with some renamed) and additional functionality has been added. - - ---- - -## Group Members - -### New Properties - -| Name | Type | Description | -| ---------------------------------------- | ---------------------- | -------------------------------------------------------------------- | -| retryButtonTextColor | UIColor | Sets the text color for the retry button. | -| retryButtonTextFont | UIFont | Sets the text font for the retry button. | -| retryButtonBackgroundColor | UIColor | Sets the background color for the retry button. | -| retryButtonBorderColor | UIColor | Sets the border color for the retry button. | -| retryButtonBorderWidth | CGFloat | Sets the border width for the retry button. | -| retryButtonCornerRadius | CometChatCornerStyle | Sets the corner radius for the retry button. | -| listItemSelectedBackground | UIColor | Sets the background color for selected list items. | -| listItemDeSelectedImageTint | UIColor | Sets the tint color for deselected list item images. | -| listItemSelectionImageTint | UIColor | Sets the tint color for selected list item images. | -| listItemSelectedImage | UIImage | Sets the image for selected list items. | -| listItemDeSelectedImage | UIImage | Sets the image for deselected list items. | -| largeTitleColor | UIColor? | Sets the color for the large title text. | -| navigationBarTintColor | UIColor? | Sets the tint color for the navigation bar. | -| navigationBarItemsTintColor | UIColor? | Sets the tint color for navigation bar items. | -| errorTitleTextFont | UIFont | Sets the font for the error title text. | -| errorTitleTextColor | UIColor | Sets the color for the error title text. | -| errorSubTitleFont | UIFont | Sets the font for the error subtitle text. | -| errorSubTitleTextColor | UIColor | Sets the color for the error subtitle text. | -| emptyTitleTextFont | UIFont | Sets the font for the empty state title text. | -| emptyTitleTextColor | UIColor | Sets the color for the empty state title text. | -| emptySubTitleFont | UIFont | Sets the font for the empty state subtitle text. | -| emptySubTitleTextColor | UIColor | Sets the color for the empty state subtitle text. | -| tableViewSeparator | UIColor | Sets the color for the table view separator. | -| listItemTitleTextColor | UIColor | Sets the text color for list item titles. | -| listItemTitleFont | UIFont | Sets the font for list item titles. | -| listItemSubTitleTextColor | UIColor | Sets the text color for list item subtitles. | -| listItemSubTitleFont | UIFont | Sets the font for list item subtitles. | -| listItemBackground | UIColor | Sets the background color for list items. | -| listItemBorderWidth | CGFloat | Sets the border width for list items. | -| listItemBorderColor | UIColor | Sets the border color for list items. | -| listItemCornerRadius | CometChatCornerStyle | Sets the corner radius for list items. | -| messageTypeImageTint | UIColor | Sets the tint color for message type icons. | -| passwordGroupImageTintColor | UIColor | Sets the tint color for password group icons. | -| passwordGroupImageBackgroundColor | UIColor | Sets the background color for password group icons. | -| privateGroupImageTintColor | UIColor | Sets the tint color for private group icons. | -| privateGroupImageBackgroundColor | UIColor | Sets the background color for private group icons. | -| backgroundColor | UIColor | Sets the background color for the component. | -| set(groupMembersRequestBuilder:) | GroupMembersRequest.GroupMembersRequestBuilder | Sets the request builder for fetching group members. | -| set(searchRequestBuilder:) | GroupMembersRequest.GroupMembersRequestBuilder | Sets the request builder for searching group members. | -| set(searchKeyword:) | String | Sets the search keyword to filter group members. | -| hideError | Bool | Hides the error state view. | -| hideUserStatus | Bool | Hides the online/offline status of users. | -| hideNavigationBar | Bool | Hides or shows the navigation bar. | -| hideLoadingState | Bool | Hides the loading state indicator. | -| hideBackIcon | Bool | Hides the back button/icon. | -| hideKickMemberOption | Bool | Hides the option to kick a member from the group. | -| hideBanMemberOption | Bool | Hides the option to ban a member from the group. | -| hideScopeChangeOption | Bool | Hides the option to change a member's scope (role). | -| hideSearch | Bool | Hides the search bar. | -| set(onSelection:) | ([GroupMember]) -> Void | Triggers on every selection and returns the list of selected group members. | -| set(onEmpty:) | () -> Void | Triggers when the groups list is empty. | -| set(onLoad:) | ([GroupMember]) -> Void | Triggers when group members list is fully fetched and displayed. | -| set(onItemClick:) | (GroupMember, IndexPath) -> Void | Triggered when you click on a ListItem. | -| set(onItemLongClick:) | (GroupMember, IndexPath) -> Void | Triggered when you long press on a ListItem. | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | -| set(onBack:) | () -> Void | Triggered when back button is pressed. | -| set(leadingView:) | (GroupMember?) -> UIView | Sets a custom leading view for group member cells. | -| set(titleView:) | (GroupMember?) -> UIView | Sets a custom title view for group member cells. | -| set(loadingView:) | UIView | Sets a custom loading view displayed while data is being fetched. | -| set(errorView:) | UIView | Sets a custom error view that appears when an error occurs. | -| set(emptyView:) | UIView | Sets a custom empty state view when no group members are available. | -| setListItemView | (GroupMember?) -> UIView | Assigns a custom ListItem to the GroupMembers component. | -| setSubtitleView | (GroupMember?) -> UIView | Sets a custom subtitle view for each GroupMembers item. | -| setTailView | (GroupMember?) -> UIView | Sets a custom tail view for group member cells. | -| setOptions | [CometChatGroupMemberOption] | Sets custom options for swipe actions. | -| set(menus:) | UIView | Sets custom menus to add more options. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| -------------------- | -------------- | ----------------------------------------------- | ----------- | -| backgroundColor | UIColor | Sets the background color for the component. | background | -| hideUserStatus | Bool | Hides/disables the online/offline status of users. | disable(userPresence:) | -| hideSearch | Bool | Hides the search bar. | hide(search:) | -| set(onItemClick:) | (GroupMember, IndexPath) -> Void | Triggered when you click on a ListItem. | setOnItemClick | -| set(onItemLongClick:) | (GroupMember, IndexPath) -> Void | Triggered when you long press on a ListItem. | setOnItemLongClick | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | setOnError | -| set(onBack:) | () -> Void | Triggered when back button is pressed. | setOnBack | - -### Removed Properties - -| Name | Type | Description | -| ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| backIconTint | UIColor | Back button tint color. | -| searchIconTint | UIColor | Search icon tint color. | -| searchTextFont | UIFont | Search text font. | -| searchTextColor | UIColor | Search text color. | -| searchCancelButtonTint | UIColor | Search cancel icon tint. | -| searchPlaceholderFont | UIFont | Search placeholder font. | -| searchPlaceholderColor | UIColor | Search placeholder color. | -| addButtonTint | UIColor | Add button color. | -| addButtonFont | UIFont | Add button font. | -| avatarStyle | AvatarStyle | Styles for the avatar component. | -| statusIndicatorStyle | CSSProperties | Styles for the status indicator component. | -| listItemStyle | ListItemStyle | Styles for the default list item view. | -| groupScopeStyle | ChangeScopeStyle | Styles for the change scope component. | -| groupMembersStyle | GroupMembersStyle | Styles for this component. | -| set(title:mode:) | String, UINavigationItem.LargeTitleDisplayMode | Custom title for the component. | -| set(backButtonTitle:) | String? | Custom text for the back button. | -| set(searchPlaceholder:) | String | Custom placeholder text for search field. | -| show(backButton:) | Bool | Whether to show the back button. | -| set(errorStateText:) | String | Custom error state text. | -| set(backButtonIcon:) | UIImage | Custom back button icon. | -| set(passwordPlaceholderText:) | String | Custom placeholder text for password. | -| hide(continueButton:) | Bool | Whether to hide the continue button. | -| set(searchIcon:) | UIImage | Icon for the search bar. | -| set(searchClearIcon:) | UIImage | Clear icon for the search bar. | -| set(searchBarHeight:) | CGFloat | Height for the search bar. | -| selectionMode(mode:) | SelectionMode | Enables selection mode (.single, .multiple). | -| hide(separator:) | Bool | Hide/unhide the separator. | -| clearList() | - | Clears the users locally. | -| update(groupMember:) | GroupMember | Updates member object locally. | -| remove(groupMember:) | GroupMember | Removes member object locally. | -| size() | - | Returns the count of members displayed. | -| title | String | Title of the component. | -| searchPlaceholder | String | Text displayed when search input has no value. | -| fetchTimeOut | any | Timeout reference for fetching users. | -| userPresencePlacement | UserPresencePlacement | Placement of user presence information. | -| backButtonIconURL | String | Image URL for the back button. | -| showBackButton | Bool | Show back button. | -| closeButtonIconURL | String | Image URL for the close button. | -| dropDownIconURL | String | Image URL for the change scope component's arrowIconURL prop. | -| emptyStateText | String | Text to display in the default empty view. | -| errorStateText | String | Text to display in the default error view. | -| loadingIconURL | String | Image URL for the default loading view. | -| hideSeparator | Bool | Hide the separator at the bottom of the default list item view. | -| titleAlignment | TitleAlignment | Alignment of the title text. | -| searchIconURL | String | Image URL for the search icon. | -| fetchingUsers | Bool | Flag to indicate whether users are currently being fetched. | -| onClose | () -> Void | Function to call when the close button is clicked. | -| headerView | UIView | Custom header view which will replace the title. | - - ---- - -## Message Header - -### New Properties - -| Name | Type | Description | -| ---------------------------------------- | --------- | -------------------------------------------------------------------- | -| titleTextColor | UIColor | Text color of the header title. | -| titleTextFont | UIFont | Font style of the header title. | -| subtitleTextColor | UIColor | Text color of the subtitle in the header. | -| subtitleTextFont | UIFont | Font style of the subtitle in the header. | -| backButtonImageTintColor | UIColor | Tint color of the back button image in the header. | -| privateGroupBadgeImageTintColor | UIColor | Tint color of the private group badge in the header. | -| passwordProtectedGroupBadgeImageTintColor | UIColor | Tint color of the password-protected group badge in the header. | -| privateGroupImageBackgroundColor | UIColor | Background color of the private group badge. | -| passwordGroupImageBackgroundColor | UIColor | Background color of the password-protected group badge. | -| groupImageBackgroundColor | UIColor | Background color for group icons in the header. | -| avatarStyle | AvatarStyle | Customizes the appearance of the avatar in the header. | -| backgroundColor | UIColor | Background color of the header. | -| cornerRadius | CometChatCornerStyle | Corner radius of the header. | -| borderWidth | CGFloat | Border width of the header. | -| borderColor | UIColor | Border color of the header. | -| backButtonIcon | UIImage | Custom icon for the back button. | -| privateGroupIcon | UIImage | Custom icon for private groups. | -| protectedGroupIcon | UIImage | Custom icon for password-protected groups. | -| backgroundImage | UIImage | Background image for the header. | -| hideBackButton | Bool | Hides the back button of message header. | -| hideUserStatus | Bool | Hides or shows the user status (online/offline/last active at). | -| hideVideoCallButton | Bool | Hides the video call button. | -| hideVoiceCallButton | Bool | Hides the voice call button. | -| set(onBack:) | () -> Void | Triggered when back button is pressed. | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | -| set(listItemView:) | (User?, Group?) -> UIView | Assigns a custom ListItem to the message header component. | -| set(leadingView:) | (User?, Group?) -> UIView | Sets a custom leading view for message header. | -| set(titleView:) | (User?, Group?) -> UIView | Sets a custom title view for message header. | -| set(trailView:) | (User?, Group?) -> UIView | Sets a custom trailing view for message header. | -| set(subtitleView:) | (User?, Group?) -> UIView | Sets a custom subtitle view for message header. | -| dateTimeFormatter | CometChatDateTimeFormatter | Supports full customization of how date and time are displayed. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| -------------------- | -------------- | ----------------------------------------------- | ----------- | -| backgroundColor | UIColor | Background color for the component. | background | -| backButtonImageTintColor | UIColor | Tint color of the back button image in the header. | backIconTint | -| hideBackButton | Bool | Hides the back button of message header. | hide(backButton:) | -| hideUserStatus | Bool | Hides or shows the user status. | set(disableUsersPresence:) | -| set(menus:) | (User?, Group?) -> UIView | Sets custom menus to add more options. | setMenus | -| set(subtitleView:) | (User?, Group?) -> UIView | Sets a custom subtitle view for message header. | setSubtitleView | - -### Removed Properties - -| Name | Type | Description | -| ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| typingIndicatorTextFont | UIFont | Typing indicator text font. | -| typingIndicatorTextColor | UIColor | Typing indicator text color. | -| detailIconTint | UIColor | Tint color for detail icon. | -| onlineStatusColor | UIColor | Online status color. | -| privateGroupIconBackgroundColor | UIColor | Private group background color (replaced by privateGroupImageBackgroundColor). | -| protectedGroupIconBackgroundColor | UIColor | Protected group background color (replaced by passwordGroupImageBackgroundColor). | -| set(protectedGroupIcon:) | UIImage | Custom protected group icon. | -| set(privateGroupIcon:) | UIImage | Custom private group icon. | -| disable(typing:) | Bool | Enable/disable typing indicators. | - - ---- - -## Message List - -### New Properties - -| Name | Type | Description | -| ---------------------------------------- | --------- | -------------------------------------------------------------------- | -| hideAvatar | Bool | Hides the avatar of the sender. | -| hideGroupActionMessages | Bool | Hides group action messages (like join/leave notifications). | -| hideReplyInThreadOption | Bool | Hides the reply in thread option. | -| hideTranslateMessageOption | Bool | Hides the message translation option. | -| hideEditMessageOption | Bool | Hides the edit message option. | -| hideDeleteMessageOption | Bool | Hides the delete message option. | -| hideReactionOption | Bool | Hides the reaction option on messages. | -| hideMessagePrivatelyOption | Bool | Hides the option to message privately. | -| hideCopyMessageOption | Bool | Hides the option to copy a message. | -| hideMessageInfoOption | Bool | Hides the message info option. | -| hideHeaderView | Bool | Hides the header view of the message list. | -| hideFooterView | Bool | Hides the footer view of the message list. | -| hideDateSeparator | Bool | Hides the date separator between messages. | -| scrollToBottomOnNewMessages | Bool | Scrolls to the bottom when new messages arrive. | -| hideReceipts | Bool | Hides the message read receipts (ticks). | -| disableSoundForMessages | Bool | Disables the sound when a new message arrives. | -| hideEmptyView | Bool | Hides the empty state view when no messages are available. | -| hideErrorView | Bool | Hides the error view when an error occurs. | -| hideLoadingView | Bool | Hides the loading view when fetching messages. | -| hideNewMessageIndicator | Bool | Hides the "new message" indicator. | -| backgroundColor | UIColor | Background color with dynamic support for light and dark mode. | -| borderWidth | CGFloat | Border width for the component. | -| borderColor | UIColor | Border color for the component. | -| cornerRadius | CometChatCornerStyle | Corner radius for the component. | -| shimmerGradientColor1 | UIColor | First color of the shimmer gradient. | -| shimmerGradientColor2 | UIColor | Second color of the shimmer gradient. | -| emptyStateTitleColor | UIColor | Text color for the title in the empty state. | -| emptyStateTitleFont | UIFont | Font for the title in the empty state. | -| emptyStateSubtitleColor | UIColor | Text color for the subtitle in the empty state. | -| emptyStateSubtitleFont | UIFont | Font for the subtitle in the empty state. | -| errorStateTitleColor | UIColor | Text color for the title in the error state. | -| errorStateTitleFont | UIFont | Font for the title in the error state. | -| errorStateSubtitleColor | UIColor | Text color for the subtitle in the error state. | -| errorStateSubtitleFont | UIFont | Font for the subtitle in the error state. | -| threadedMessageImage | UIImage | Icon image for threaded messages. | -| errorImage | UIImage | Icon image for error state. | -| emptyImage | UIImage | Icon image for empty state. | -| newMessageIndicatorImage | UIImage | Icon image for new message indicator. | -| backgroundImage | UIImage | Background image for the component. | -| scrollToBottom(isAnimated:) | Bool | Scrolls to the bottom of the message list. | -| set(messageAlignment:) | MessageListAlignment | Sets the alignment of messages in the list. | -| set(smartRepliesKeywords:) | [String] | Sets keywords for smart replies. | -| set(smartRepliesDelayDuration:) | Int | Sets the delay duration for smart replies. | -| set(user:parentMessage:) | User, BaseMessage? | Sets the user and an optional parent message. | -| set(group:parentMessage:) | Group, BaseMessage? | Sets the group and an optional parent message. | -| set(messagesRequestBuilder:) | MessagesRequest.MessageRequestBuilder | Sets the message request builder. | -| set(reactionsRequestBuilder:) | ReactionsRequest.ReactionsRequestBuilder | Sets the reactions request builder. | -| set(parentMessageId:) | Int | Sets the parent message ID. | -| set(onThreadRepliesClick:) | (BaseMessage, CometChatMessageTemplate) -> Void | Triggered when you click on the thread indicator. | -| set(onReactionClick:) | (CometChat.ReactionCount, BaseMessage) -> Void | Triggered when you click on a reaction. | -| set(onReactionListItemClick:) | (CometChat.Reaction, BaseMessage) -> Void | Triggered when you click on the list item of CometChatReactionList. | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | -| set(onEmpty:) | () -> Void | Triggers when the message list is empty. | -| set(onLoad:) | ([BaseMessage]) -> Void | Triggers when message list is fully fetched and displayed. | -| set(headerView:) | UIView | Sets a custom header view for message list. | -| set(footerView:) | UIView | Sets a custom footer view for message list. | -| set(dateSeparatorPattern:) | (Int?) -> String | Sets the date separator pattern using a closure. | -| set(datePattern:) | (Int?) -> String | Sets the date pattern using a closure. | -| set(timePattern:) | (Int?) -> String | Sets the time pattern using a closure. | -| set(textFormatter:) | [CometChatTextFormatter] | Sets the list of text formatters. | -| set(loadingView:) | UIView | Sets a custom loading view. | -| set(errorView:) | UIView | Sets a custom error view. | -| set(emptyView:) | UIView | Sets a custom empty state view. | -| set(templates:) | [CometChatMessageTemplate] | Sets message templates to MessageList. | -| dateTimeFormatter | CometChatDateTimeFormatter | Supports full customization of how date and time are displayed. | -| set(controller:) | UIViewController | Sets the controller (mandatory for proper configuration). | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| -------------------- | -------------- | ----------------------------------------------- | ----------- | -| hideReceipts | Bool | Hides the message read receipts. | hide(receipt:) | -| hideAvatar | Bool | Shows/hides the avatar of the sender. | show(avatar:) | -| backgroundColor | UIColor | Background color for the component. | background | -| set(messageAlignment:) | MessageListAlignment | Sets the alignment of messages in the list. | alignment | - -### Removed Properties - -| Name | Type | Description | -| ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| loadingIconTint | UIColor | Loading icon tint. | -| emptyTextFont | UIFont | Empty state text font. | -| errorTextFont | UIFont | Error text font. | -| emptyTextColor | UIColor | Empty state text color. | -| errorTextColor | UIColor | Error state text color. | -| nameTextColor | UIColor | Sender/receiver name text color on a message bubble. | -| nameTextFont | UIFont | Sender/receiver name text appearance on a message bubble. | -| timestampTextColor | UIColor | Time stamp text color. | -| threadReplySeperatorColor | UIColor | Thread reply separator color. | -| threadReplyTextColor | UIColor | Thread reply text color. | -| threadReplyTextFont | UIFont | Thread reply text appearance. | -| hide(error:) | Bool | Hide the error view. | -| messageInformationConfiguration | MessageInformationConfiguration | Configuration for message information component. | -| reactionsConfiguration | ReactionsConfiguration | Configuration for reactions component. | -| setDateSeparatorPattern | (Int?) -> String | Modify the date pattern of the message list date separator. | -| setDatePattern | (Int?) -> String | Modify the date pattern. | -| setHeaderView | UIView | Set custom header view (now set(headerView:)). | -| setFooterView | UIView | Set custom footer view (now set(footerView:)). | -| setTextFormatters | [CometChatTextFormatter] | Set text formatters (now set(textFormatter:)). | -| setMentionsFormatters | [CometChatTextFormatter] | Set mentions formatters (merged into set(textFormatter:)). | -| setErrorStateView | UIView | Set custom error view (now set(errorView:)). | -| setEmptyStateView | UIView | Set custom empty state view (now set(emptyView:)). | -| setOnThreadRepliesClick | Closure | Callback for thread replies click (now set(onThreadRepliesClick:)). | - - ---- - -## Message Composer - -### New Properties - -| Name | Type | Description | -| ---------------------------------------- | --------- | -------------------------------------------------------------------- | -| placeHolderTextFont | UIFont | Font for the placeholder text in the input field. | -| placeHolderTextColor | UIColor | Color for the placeholder text in the input field. | -| textFiledColor | UIColor | Text color for the input field. | -| textFiledFont | UIFont | Font for the input field text. | -| backgroundColor | UIColor | Background color with dynamic support for light and dark mode. | -| cornerRadius | CometChatCornerStyle | Corner radius for the composer. | -| borderWidth | CGFloat | Border width for the composer. | -| borderColor | UIColor | Border color for the composer. | -| sendButtonImage | UIImage | Icon for the send button. | -| sendButtonImageTint | UIColor | Tint color for the send button image. | -| activeSendButtonImageBackgroundColor | UIColor | Background color for the send button when active. | -| inactiveSendButtonImageBackgroundColor | UIColor | Background color for the send button when inactive. | -| composeBoxBackgroundColor | UIColor | Background color for the compose box. | -| composeBoxBorderColor | UIColor | Border color for the compose box. | -| composeBoxBorderWidth | CGFloat | Border width for the compose box. | -| composerBoxCornerRadius | CometChatCornerStyle | Corner radius for the compose box. | -| composerSeparatorColor | UIColor | Color for the separator in the compose box. | -| attachmentImage | UIImage | Icon for the attachment button. | -| attachmentImageTint | UIColor | Tint color for the attachment image. | -| voiceRecordingImage | UIImage | Icon for the voice recording button. | -| voiceRecordingImageTint | UIColor | Tint color for the voice recording image. | -| aiImage | UIImage | Icon for the AI button. | -| aiImageTint | UIColor | Tint color for the AI image. | -| stickerImage | UIImage | Icon for the sticker button. | -| stickerTint | UIColor | Tint color for the sticker image. | -| editPreviewTitleTextFont | UIFont | Font for the title in the edit preview. | -| editPreviewMessageTextFont | UIFont | Font for the message text in the edit preview. | -| editPreviewTitleTextColor | UIColor | Text color for the title in the edit preview. | -| editPreviewMessageTextColor | UIColor | Text color for the message in the edit preview. | -| editPreviewBackgroundColor | UIColor | Background color for the edit preview. | -| editPreviewCornerRadius | CometChatCornerStyle | Corner radius for the edit preview. | -| editPreviewBorderColor | UIColor | Border color for the edit preview. | -| editPreviewBorderWidth | CGFloat | Border width for the edit preview. | -| editPreviewCloseIcon | UIImage | Icon for closing the edit preview. | -| editPreviewCloseIconTint | UIColor | Tint color for the close icon in the edit preview. | -| infoIcon | UIImage | Icon for the info button. | -| infoIconTint | UIColor | Tint color for the info icon. | -| infoTextColor | UIColor | Text color for the info text. | -| infoTextFont | UIFont | Font for the info text. | -| infoSeparatorColor | UIColor | Color for the separator in the info section. | -| infoBackgroundColor | UIColor | Background color for the info section. | -| infoCornerRadius | CometChatCornerStyle | Corner radius for the info section. | -| infoBorderColor | UIColor | Border color for the info section. | -| infoBorderWidth | CGFloat | Border width for the info section. | -| setInitialComposerText | String | Sets the initial text in the composer when it loads. | -| disableTypingEvents | Bool | Disables sending typing indicators when the user types. | -| disableMentions | Bool | Disables the mention feature in the composer. | -| hideImageAttachmentOption | Bool | Hides the option to attach images. | -| hideVideoAttachmentOption | Bool | Hides the option to attach videos. | -| hideAudioAttachmentOption | Bool | Hides the option to attach audio files. | -| hideFileAttachmentOption | Bool | Hides the option to attach files. | -| hidePollsOption | Bool | Hides the option to create polls. | -| hideCollaborativeDocumentOption | Bool | Hides the option for collaborative documents. | -| hideCollaborativeWhiteboardOption | Bool | Hides the option for collaborative whiteboards. | -| hideAttachmentButton | Bool | Hides the attachment button in the composer. | -| hideVoiceRecordingButton | Bool | Hides the voice recording button. | -| hideStickersButton | Bool | Hides the stickers button. | -| hideSendButton | Bool | Hides the send button. | -| set(user:) | User | Sets the user for direct messaging. | -| set(group:) | Group | Sets the group for group messaging. | -| set(parentMessageId:) | Int | Sets the parent message ID for replying in a thread. | -| set(maxLine:) | Int | Sets the maximum number of lines for the composer input. | -| set(customSoundForMessages:) | URL? | Sets a custom sound for sending messages. | -| disableSoundForMessages | Bool | Disables sound while sending messages. | -| set(onSendButtonClick:) | (BaseMessage) -> Void | Override the action triggered upon pressing the send button. | -| set(onTextChanged:) | (String) -> Void | Activated when the user starts typing in message composer. | -| set(onError:) | (CometChatException) -> Void | Triggered when an error occurs. | -| set(attachmentOptions:) | (User?, Group?, UIViewController?) -> [CometChatMessageComposerAction] | Sets a list of custom MessageComposerActions. | -| set(sendButtonView:) | (User?, Group?) -> UIView | Sets a custom send button for the MessageComposer Component. | -| set(headerView:) | (User?, Group?) -> UIView | Sets a custom header view for the MessageComposer Component. | -| set(footerView:) | (User?, Group?) -> UIView | Sets a custom footer view for the MessageComposer Component. | -| set(textFormatter:) | [CometChatTextFormatter] | Assigns the list of text formatters. | -| set(controller:) | UIViewController | Sets the controller (mandatory for proper configuration). | -| mediaRecorderStyle | MediaRecorderStyle | Customizes the media recording styling. | -| aiOptionsStyle | AIOptionsStyle | Customizes the AI options styling. | - -### Renamed Properties - -| Name | Type | Description | Old Name | -| -------------------- | -------------- | ----------------------------------------------- | ----------- | -| backgroundColor | UIColor | Background color for the component. | background | -| hideVoiceRecordingButton | Bool | Hides the voice recording button. | hide(voiceRecording:) | -| disableTypingEvents | Bool | Disables sending typing indicators. | disable(disableTypingEvents:) | -| disableSoundForMessages | Bool | Disables sound while sending messages. | disable(disableSoundForMessages:) | -| set(textFormatter:) | [CometChatTextFormatter] | Assigns the list of text formatters. | setMentionsFormatters | - -### Removed Properties - -| Name | Type | Description | -| ----------------------------- | ----------------------------------- | -------------------------------------------------- | -| inputBackground | UIColor | Input background color of message composer. | -| textFont | UIFont | Input text font of message composer. | -| inputBoxPlaceholderFont | UIFont | Placeholder text font for message composer input field. | -| attachmentIconTint | UIColor | Attachment icon tint color. | -| sendIconTint | UIColor | Send button icon tint color. | -| separatorTint | UIColor | Separator color for message composer. | -| inputBorderWidth | CGFloat | Border width for message composer input view. | -| inputBorderColor | UIColor | Border color for message composer input view. | -| actionSheetTitleColor | UIColor | Title color for action sheet of message composer. | -| actionSheetTitleFont | UIFont | Title font for action sheet of message composer. | -| actionSheetLayoutModelIconTint | UIColor | Action sheet layout mode icon tint color. | -| actionSheetCancelButtonIconTint | UIColor | Action sheet cancel button icon tint color. | -| actionSheetCancelButtonIconFont | UIFont | Action sheet cancel button icon font color. | -| actionSheetSeparatorTint | UIColor | Separator color for action sheet items. | -| actionSheetBackground | UIColor | Background color of action sheet. | -| voiceRecordingIconTint | UIColor | Voice recorder icon tint color. | -| aiIconTint | UIColor | AI icon tint color. | -| set(background:) | UIColor | Background color for message composer. | -| set(placeholderText:) | String | Message composer's placeholder text. | -| set(maxLines:) | Int | Limit for lines of text in input field. | -| set(auxiliaryButtonAlignment:) | AuxiliaryButtonAlignment | Position for auxiliary buttons view. | -| set(customSoundForMessage:) | URL | Custom sounds for outgoing messages. | -| set(liveReactionIconURL:) | UIImage | Custom live reaction icon. | -| set(disableMentions:) | Bool | Enables/Disables user mentions in message composer input field. | -| set(infoIcon:) | UIImage | Image for info icon (now part of style). | -| set(attachmentIcon:) | UIImage | Image for attachment button on message composer. | -| set(aiAuxiliaryIcon:) | UIImage | Image for AI auxiliary button. | -| setOnSendButtonClick | Closure | Custom actions for send button click. | -| hide(liveReaction:) | Bool | Toggles visibility for live reaction component. | -| hide(footerView:) | Bool | Toggles visibility for footer view of message composer. | -| hide(headerView:) | Bool | Toggles visibility for header view of message composer. | -| hide(sendButton:) | Bool | Toggles visibility for send button. | -| setAttachmentOptions | Closure | List of custom MessageComposerActions. | -| setAuxilaryButtonView | Closure | Custom auxiliary button view. | -| setSecondaryButtonView | Closure | Custom secondary button view. | -| setSendButtonView | Closure | Custom send button view. | \ No newline at end of file diff --git a/ui-kit/ios/upgrading-from-v4.mdx b/ui-kit/ios/upgrading-from-v4.mdx index d4f8fc6f9..2375d8b33 100644 --- a/ui-kit/ios/upgrading-from-v4.mdx +++ b/ui-kit/ios/upgrading-from-v4.mdx @@ -1,55 +1,90 @@ --- -title: "Upgrading From V4" +title: "Upgrading from V4 to V5" +sidebarTitle: "Upgrading from V4" +description: "Migration guide for upgrading from CometChat iOS UI Kit v4 to v5 with breaking changes, property updates, and new patterns." --- -## Introduction + -The **CometChat v5 iOS UI Kit** streamlines the integration of in-app chat functionality into your iOS applications. Packed with prebuilt, modular UI components built natively in Swift, it supports essential messaging features for both one-to-one and group conversations. With built-in theming options, including light and dark modes, customizable fonts, colors, and extensive configuration possibilities, developers can create chat experiences tailored to their application's needs. +| Field | Value | +| --- | --- | +| Package | `CometChatUIKitSwift` | +| Architecture | Composite components replaced with modular components | +| Theming | Direct static property assignment on `CometChatTheme` and `CometChatTypography` | +| Key changes | `CometChatConversationsWithMessages` → Individual components (`CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer`) | +| Style props | Removed — use native theming system with direct property access | +| Config props | Removed — direct control over each component | + + + +The CometChat v5 iOS UI Kit introduces a modular architecture with smaller, focused components replacing composite components. This guide outlines the key differences and provides migration steps from v4 to v5. + +--- + +## Overview of Changes + +| Feature | v4 | v5 | +| --- | --- | --- | +| Architecture | Composite components (e.g., `CometChatConversationsWithMessages`) | Modular components (`CometChatConversations`, `CometChatMessageList`, etc.) | +| Theming | `CometChatTheme` with `Palette` and `Typography` classes | Direct static property assignment | +| Customization | Complex configuration objects | Direct component properties and Swift APIs | +| Style Props | Inline style properties | Native theming system | +| Custom Views | `itemView`, `leadingView`, `trailingView`, `subtitleView`, `titleView` | Unified naming convention across components | + +--- ## Integration -In **v4**, integration was straightforward due to the availability of composite components like `CometChatConversationsWithMessages`. This single component provided end-to-end functionality, including listing conversations, handling conversation clicks, loading messages (message header, list, composer), displaying user or group details, and supporting threaded messages. Developers could achieve all these features with minimal setup. However, customization posed significant challenges. Customizing the UI or adding custom views required a deep understanding of the internal flow of the composite component. Additionally, configurations were a mix of custom view props, behavioral props, and style props, which often led to confusion. Styling deeply nested components also proved cumbersome, limiting the developer's ability to make meaningful changes. +In v4, integration was straightforward due to composite components like `CometChatConversationsWithMessages`. This single component provided end-to-end functionality including listing conversations, handling clicks, loading messages, and supporting threaded messages. However, customization required deep understanding of internal flows, and configurations mixed custom view props, behavioral props, and style props. -With **v5**, composite components have been replaced with smaller, modular components, such as `CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer`. This modular approach makes integration more flexible and easier to understand. Each component has a well-defined purpose, allowing developers to use them in ways that suit their specific requirements. The need for complex configurations has been eliminated, as developers can now customize behavior and styling directly via component properties and Swift APIs. +With v5, composite components are replaced with smaller, modular components: +- `CometChatConversations` +- `CometChatMessageHeader` +- `CometChatMessageList` +- `CometChatMessageComposer` -To support the transition from v4 to v5, CometChat has built a [sample app](https://github.com/cometchat/cometchat-uikit-ios/tree/v5) that replicates the functionality of v4's composite components. This sample app serves as a reference for developers looking to build additional features such as user/group details, call log details, threaded messages, and advanced messaging capabilities. By following this approach, developers can take full advantage of v5's modular design while implementing complex functionality in an organized manner. +This modular approach makes integration more flexible. Each component has a well-defined purpose, and developers can customize behavior and styling directly via component properties and Swift APIs. -Learn how to build a complete messaging UI using the **v5 UI Kit** by following the step-by-step guide [here](/ui-kit/ios/getting-started). +Learn how to build a complete messaging UI using the v5 UI Kit by following the [Getting Started guide](/ui-kit/ios/getting-started). +--- + ## Components -The **v4** UI Kit provided composite components like `CometChatConversationsWithMessages`, which offered end-to-end functionality. These components integrated features such as conversation lists, message views (header, list, composer), user/group details, and threaded messages into a single unit. However, customization of deeply nested components through configuration was challenging and resulted in a suboptimal developer experience. +### v4 Components -| Components in v4 UI Kit: | | | -| ---------------------------------- | -------------------------- | --------------------------- | +| | | | +| --- | --- | --- | | CometChatConversationsWithMessages | CometChatUsersWithMessages | CometChatGroupsWithMessages | -| CometChatMessages | CometChatMessageHeader | CometChatMessageList | -| CometChatMessageComposer | CometChatThreadedMessages | CometChatConversations | -| CometChatUsers | CometChatGroups | CometChatContacts | -| CometChatDetails | CometChatGroupMembers | CometChatAddMembers | -| CometChatBannedMembers | CometChatTransferOwnership | CometChatMessageInformation | -| CometChatIncomingCall | CometChatOngoingCall | CometChatOutgoingCall | -| CometChatCallButtons | CometChatCallLogs | CometChatCallLogDetails | -| CometChatCallLogHistory | | | +| CometChatMessages | CometChatMessageHeader | CometChatMessageList | +| CometChatMessageComposer | CometChatThreadedMessages | CometChatConversations | +| CometChatUsers | CometChatGroups | CometChatContacts | +| CometChatDetails | CometChatGroupMembers | CometChatAddMembers | +| CometChatBannedMembers | CometChatTransferOwnership | CometChatMessageInformation | +| CometChatIncomingCall | CometChatOngoingCall | CometChatOutgoingCall | +| CometChatCallButtons | CometChatCallLogs | CometChatCallLogDetails | +| CometChatCallLogHistory | | | + +### v5 Components + +| | | | +| --- | --- | --- | +| CometChatConversations | CometChatUsers | CometChatGroups | +| CometChatGroupMembers | CometChatMessageHeader | CometChatMessageList | +| CometChatMessageComposer | CometChatThreadedMessageHeader | CometChatIncomingCall | +| CometChatOutgoingCall | CometChatCallButtons | CometChatCallLogs | - -In **v5**, the composite approach is replaced with smaller, modular components like `CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer`. Developers now need to stitch these components together to build the desired functionality. This change allows for greater flexibility and easier customization via properties, significantly improving the developer experience while maintaining functionality. - -| Components in v5 UI Kit: | | | -| ------------------------ | ------------------------------- | --------------------- | -| CometChatConversations | CometChatUsers | CometChatGroups | -| CometChatGroupMembers | CometChatMessageHeader | CometChatMessageList | -| CometChatMessageComposer | CometChatThreadedMessageHeader | CometChatIncomingCall | -| CometChatOutgoingCall | CometChatCallButtons | CometChatCallLogs | +--- ## Theming -In **v4**, theming was managed using the `CometChatTheme` class along with the `Palette` and `Typography` classes. The `Palette` class provided methods like `set(background:)`, `set(accent:)`, `set(primary:)`, and similar setters for configuring colors and themes. While this approach worked, it required instantiating multiple objects and passing them through constructors, which added complexity to the theming process. Developers had to create palette and typography instances, configure them with various color and font settings, and then pass them to create a theme object. +### v4 Theming +In v4, theming required instantiating multiple objects and passing them through constructors: -```swift App.delegate +```swift title="V4 UI Kit" let palette = Palette() palette.set(background: .purple) palette.set(accent: .cyan) @@ -69,13 +104,11 @@ typography.overrideFont(family: family) let theme = CometChatTheme(typography: typography, palatte: palette) ``` -In **v5**, theming has been completely revamped for simplicity and directness. The complex theming classes and object instantiation have been replaced with direct static property assignment on `CometChatTheme` and `CometChatTypography`. This means every design token, such as colors and typography, can now be set directly as static properties. Changing the primary color, for instance, is as simple as assigning a value to `CometChatTheme.primaryColor` — no need to interact with complex theming logic or instantiate multiple objects. - -The new theming approach is declarative and lightweight, significantly enhancing both performance and developer experience. By providing direct access to theme properties, developers can now customize the look and feel of their application with minimal code and maximum clarity. - +### v5 Theming +In v5, theming uses direct static property assignment: -```swift App.delegate +```swift title="V5 UI Kit" // Apply the global theme - typically in AppDelegate or SceneDelegate CometChatTheme.primaryColor = UIColor.red CometChatTheme.backgroundColor01 = .brown @@ -85,25 +118,432 @@ CometChatTheme.backgroundColor02 = .green CometChatTypography.Body.regular = UIFont.systemFont(ofSize: 18, weight: .bold) ``` -This architectural redesign makes theming more intuitive and aligns with modern iOS development practices. Developers now have a more powerful and straightforward toolset to customize and manage themes effectively. - -For detailed guidance on theming and customizing colors in the CometChat iOS UI Kit, refer to the following resources: - -* **Theming Documentation:** [Guide to Theming](/ui-kit/ios/color-resources) -* **Color Customization:** [Customizing Colors](/ui-kit/ios/theme-introduction) +For detailed guidance on theming, refer to: +- [Theming Documentation](/ui-kit/ios/theme-introduction) +- [Color Customization](/ui-kit/ios/color-resources) +--- + ## Properties -In **v5**, the approach to properties has been significantly refined to improve clarity and ease of use. All style-related properties, previously used to customize components, have been replaced by a more efficient and native theming system based on **direct property access and configuration classes**. This change ensures a seamless and flexible styling process without requiring verbose or redundant setup within component properties. +In v5, the approach to properties has been refined: -Configuration properties, which were widely used in **v4**, have also been removed. With **v5’s modular architecture**, components are no longer deeply nested or dependent on complex configuration objects. Developers now have **direct control over each component**, reducing complexity and increasing flexibility in how components are customized, styled, and composed. +- **Style properties** — Replaced by a native theming system based on direct property access +- **Configuration properties** — Removed due to modular architecture; developers have direct control over each component +- **Custom view properties** — Restructured for consistency with unified naming: `itemView`, `leadingView`, `trailingView`, `subtitleView`, `titleView` -Custom view properties have been restructured to ensure **consistency and uniformity** across all components. For instance, components that represent list items or visual elements now share a unified set of customizable properties, allowing developers to adopt a standardized approach to component customization. These properties include `itemView`, `leadingView`, `trailingView`, `subtitleView`, and `titleView`. +--- + +## Property Changes + +### Conversations + +#### New Properties + +| Name | Type | Description | +| --- | --- | --- | +| hideNavigationBar | Bool | Hides or shows the navigation bar | +| hideSearch | Bool | Hides the search bar | +| hideLoadingState | Bool | Hides the loading state indicator | +| hideDeleteConversationOption | Bool | Hides the option to delete a conversation | +| hideGroupType | Bool | Hides the group type indicator | +| backgroundDrawable | UIImage | Sets a background image | +| separatorColor | UIColor | Sets the color of separators | +| separatorWidth | CGFloat | Sets the width of separators | +| errorTextColor | UIColor | Sets the color of error messages | +| lastMessageTextColor | UIColor | Sets the color of the last message text | +| typingIndicatorColor | UIColor | Sets the color of the typing indicator | +| dateTimeFormatter | CometChatDateTimeFormatter | Customizes date/time display | +| set(OnItemLongClick:) | Method | Triggered on long press | +| set(onEmpty:) | Method | Triggered when list is empty | + +#### Renamed Properties + +| v4 Name | v5 Name | Description | +| --- | --- | --- | +| hide(error: Bool) | hideErrorView | Hides the error state view | +| show(backButton: Bool) | hideBackButton | Controls back button visibility (logic inverted) | +| hide(receipt: Bool) | hideReceipts | Hides message receipts | +| disable(userPresence: Bool) | hideUserStatus | Hides online/offline status | +| setOnItemClick | set(OnItemClick:) | Triggered on click | +| setOnBack | set(onBack:) | Override back button action | +| setOnSelection | set(onSelection:) | Triggered on selection | +| setOnError | set(onError:) | Override error action | + +#### Removed Properties + +| Name | Description | +| --- | --- | +| hide(separator: Bool) | Replaced by style properties | +| disable(typing: Bool) | Toggled typing indicator visibility | +| setDatePattern | Replaced by dateTimeFormatter | +| protectedGroupIcon | Icon for password protected groups | +| sentIcon, deliveredIcon, readIcon | Receipt icons | + +--- + +### Users + +#### New Properties + +| Name | Type | Description | +| --- | --- | --- | +| set(options:) | (User) -> [CometChatUserOption] | Custom options for each user | +| set(leadingView:) | (User) -> UIView | Custom leading view | +| set(titleView:) | (User) -> UIView | Custom title view | +| set(trailView:) | (User) -> UIView | Custom trailing view | +| set(onEmpty:) | () -> Void | Triggered when list is empty | +| hideErrorView | Bool | Hides the error state view | +| hideNavigationBar | Bool | Hides the navigation bar | +| hideBackButton | Bool | Hides the back button | +| hideLoadingState | Bool | Hides loading indicator | +| hideUserStatus | Bool | Hides online/offline status | +| hideSectionHeader | Bool | Hides section headers | +| hideSearch | Bool | Hides the search bar | + +#### Renamed Properties + +| v4 Name | v5 Name | Description | +| --- | --- | --- | +| setListItemView | set(listItemView:) | Custom list item view | +| setSubtitleView | set(subtitleView:) | Custom subtitle view | +| setEmptyStateView | set(emptyView:) | Custom empty state view | +| setErrorStateView | set(errorView:) | Custom error state view | +| setOnItemClick | set(onItemClick:) | Triggered on click | +| setOnItemLongClick | set(onItemLongClick:) | Triggered on long press | +| setOnBack | set(onBack:) | Triggered on back press | +| setOnSelection | set(onSelection:) | Triggered on selection | +| setOnError | set(onError:) | Triggered on error | + +#### Removed Properties + +| Name | Description | +| --- | --- | +| set(loadingStateView:) | Set loading view icon size | +| hide(errorText:) | Hide error text | +| show(backButton:) | Toggle back button | +| set(searchIcon:) | Set search icon | +| hide(search:) | Toggle search box | +| hide(separator:) | Hide divider | +| disable(userPresence:) | Control online indicator | +| set(emptyStateText:) | Custom empty text | +| set(errorStateText:) | Custom error text | +| set(searchPlaceholder:) | Search placeholder | +| set(title:mode:) | Set title with display mode | +| setOnLoad | Triggered when list is fetched | -This consistent naming convention provides developers with a predictable customization model across multiple components, simplifying the development process and ensuring UI consistency throughout the app. +--- -For a comprehensive overview of newly added, renamed, and removed properties, refer to the [Property Changes](/ui-kit/ios/property-changes) documentation. +### Groups + +#### New Properties + +| Name | Type | Description | +| --- | --- | --- | +| set(onSelection:) | Closure | Returns selected groups | +| set(onEmpty:) | Closure | Triggered when list is empty | +| setOnLoad | Closure | Triggered when list is fetched | +| listItemSelectedImage | UIImage | Selected checkbox image | +| listItemDeSelectedImage | UIImage | Deselected checkbox image | +| hideErrorView | Bool | Hides error state view | +| hideNavigationBar | Bool | Hides navigation bar | +| hideSearch | Bool | Hides search bar | +| hideBackButton | Bool | Hides back button | +| hideLoadingState | Bool | Hides loading indicator | +| set(leadingView:) | (Group?) -> UIView | Custom leading view | +| set(titleView:) | (Group?) -> UIView | Custom title view | +| set(trailView:) | (Group?) -> UIView | Custom trailing view | + +#### Renamed Properties + +| v4 Name | v5 Name | Description | +| --- | --- | --- | +| SetOnItemClick | set(onItemClick:) | Triggered on click | +| SetOnItemLongClick | set(OnItemLongClick:) | Triggered on long press | +| SetOnError | set(onError:) | Triggered on error | +| SetOnBack | set(onBack:) | Triggered on back press | +| setListItemView | SetListItemView | Custom list item | +| setSubtitleView | SetSubTitleView | Custom subtitle view | --- + +### Group Members + +#### New Properties + +| Name | Type | Description | +| --- | --- | --- | +| hideError | Bool | Hides error state view | +| hideUserStatus | Bool | Hides online/offline status | +| hideNavigationBar | Bool | Hides navigation bar | +| hideLoadingState | Bool | Hides loading indicator | +| hideBackIcon | Bool | Hides back button | +| hideKickMemberOption | Bool | Hides kick member option | +| hideBanMemberOption | Bool | Hides ban member option | +| hideScopeChangeOption | Bool | Hides scope change option | +| hideSearch | Bool | Hides search bar | +| set(onSelection:) | ([GroupMember]) -> Void | Returns selected members | +| set(onEmpty:) | () -> Void | Triggered when list is empty | +| set(onLoad:) | ([GroupMember]) -> Void | Triggered when list is fetched | +| set(leadingView:) | (GroupMember?) -> UIView | Custom leading view | +| set(titleView:) | (GroupMember?) -> UIView | Custom title view | + +#### Renamed Properties + +| v4 Name | v5 Name | Description | +| --- | --- | --- | +| background | backgroundColor | Background color | +| disable(userPresence:) | hideUserStatus | Hides online/offline status | +| hide(search:) | hideSearch | Hides search bar | +| setOnItemClick | set(onItemClick:) | Triggered on click | +| setOnItemLongClick | set(onItemLongClick:) | Triggered on long press | +| setOnError | set(onError:) | Triggered on error | +| setOnBack | set(onBack:) | Triggered on back press | + +#### Removed Properties + +| Name | Description | +| --- | --- | +| backIconTint | Back button tint color | +| searchIconTint | Search icon tint color | +| avatarStyle | Avatar component styles | +| statusIndicatorStyle | Status indicator styles | +| listItemStyle | List item view styles | +| groupScopeStyle | Change scope component styles | +| groupMembersStyle | Component styles | +| set(title:mode:) | Custom title | +| set(backButtonTitle:) | Back button text | +| set(searchPlaceholder:) | Search placeholder | +| show(backButton:) | Show back button | +| set(errorStateText:) | Error state text | +| selectionMode(mode:) | Selection mode | +| hide(separator:) | Hide separator | + +--- + +### Message Header + +#### New Properties + +| Name | Type | Description | +| --- | --- | --- | +| titleTextColor | UIColor | Header title text color | +| titleTextFont | UIFont | Header title font | +| subtitleTextColor | UIColor | Subtitle text color | +| subtitleTextFont | UIFont | Subtitle font | +| backButtonImageTintColor | UIColor | Back button tint | +| hideBackButton | Bool | Hides back button | +| hideUserStatus | Bool | Hides user status | +| hideVideoCallButton | Bool | Hides video call button | +| hideVoiceCallButton | Bool | Hides voice call button | +| set(onBack:) | () -> Void | Triggered on back press | +| set(onError:) | (CometChatException) -> Void | Triggered on error | +| set(listItemView:) | (User?, Group?) -> UIView | Custom list item | +| set(leadingView:) | (User?, Group?) -> UIView | Custom leading view | +| set(titleView:) | (User?, Group?) -> UIView | Custom title view | +| set(trailView:) | (User?, Group?) -> UIView | Custom trailing view | +| set(subtitleView:) | (User?, Group?) -> UIView | Custom subtitle view | +| dateTimeFormatter | CometChatDateTimeFormatter | Date/time formatting | + +#### Renamed Properties + +| v4 Name | v5 Name | Description | +| --- | --- | --- | +| background | backgroundColor | Background color | +| backIconTint | backButtonImageTintColor | Back button tint | +| hide(backButton:) | hideBackButton | Hides back button | +| set(disableUsersPresence:) | hideUserStatus | Hides user status | +| setMenus | set(menus:) | Custom menus | +| setSubtitleView | set(subtitleView:) | Custom subtitle view | + +#### Removed Properties + +| Name | Description | +| --- | --- | +| typingIndicatorTextFont | Typing indicator font | +| typingIndicatorTextColor | Typing indicator color | +| detailIconTint | Detail icon tint | +| onlineStatusColor | Online status color | +| set(protectedGroupIcon:) | Protected group icon | +| set(privateGroupIcon:) | Private group icon | +| disable(typing:) | Enable/disable typing indicators | + +--- + +### Message List + +#### New Properties + +| Name | Type | Description | +| --- | --- | --- | +| hideAvatar | Bool | Hides sender avatar | +| hideGroupActionMessages | Bool | Hides group action messages | +| hideReplyInThreadOption | Bool | Hides reply in thread option | +| hideTranslateMessageOption | Bool | Hides translation option | +| hideEditMessageOption | Bool | Hides edit option | +| hideDeleteMessageOption | Bool | Hides delete option | +| hideReactionOption | Bool | Hides reaction option | +| hideMessagePrivatelyOption | Bool | Hides message privately option | +| hideCopyMessageOption | Bool | Hides copy option | +| hideMessageInfoOption | Bool | Hides message info option | +| hideHeaderView | Bool | Hides header view | +| hideFooterView | Bool | Hides footer view | +| hideDateSeparator | Bool | Hides date separator | +| scrollToBottomOnNewMessages | Bool | Scrolls to bottom on new messages | +| hideReceipts | Bool | Hides read receipts | +| disableSoundForMessages | Bool | Disables message sound | +| hideEmptyView | Bool | Hides empty state view | +| hideErrorView | Bool | Hides error view | +| hideLoadingView | Bool | Hides loading view | +| hideNewMessageIndicator | Bool | Hides new message indicator | +| set(onThreadRepliesClick:) | (BaseMessage, CometChatMessageTemplate) -> Void | Thread click callback | +| set(onReactionClick:) | (CometChat.ReactionCount, BaseMessage) -> Void | Reaction click callback | +| set(onError:) | (CometChatException) -> Void | Error callback | +| set(onEmpty:) | () -> Void | Empty state callback | +| set(onLoad:) | ([BaseMessage]) -> Void | Load callback | +| set(headerView:) | UIView | Custom header view | +| set(footerView:) | UIView | Custom footer view | +| set(textFormatter:) | [CometChatTextFormatter] | Text formatters | +| dateTimeFormatter | CometChatDateTimeFormatter | Date/time formatting | + +#### Renamed Properties + +| v4 Name | v5 Name | Description | +| --- | --- | --- | +| hide(receipt:) | hideReceipts | Hides receipts | +| show(avatar:) | hideAvatar | Shows/hides avatar | +| background | backgroundColor | Background color | +| alignment | set(messageAlignment:) | Message alignment | + +#### Removed Properties + +| Name | Description | +| --- | --- | +| loadingIconTint | Loading icon tint | +| emptyTextFont | Empty state text font | +| errorTextFont | Error text font | +| emptyTextColor | Empty state text color | +| errorTextColor | Error state text color | +| nameTextColor | Sender name text color | +| nameTextFont | Sender name font | +| timestampTextColor | Timestamp text color | +| threadReplySeperatorColor | Thread reply separator color | +| threadReplyTextColor | Thread reply text color | +| threadReplyTextFont | Thread reply font | +| hide(error:) | Hide error view | +| messageInformationConfiguration | Message info configuration | +| reactionsConfiguration | Reactions configuration | +| setDateSeparatorPattern | Date separator pattern | +| setDatePattern | Date pattern | + +--- + +### Message Composer + +#### New Properties + +| Name | Type | Description | +| --- | --- | --- | +| placeHolderTextFont | UIFont | Placeholder font | +| placeHolderTextColor | UIColor | Placeholder color | +| textFiledColor | UIColor | Input text color | +| textFiledFont | UIFont | Input text font | +| sendButtonImage | UIImage | Send button icon | +| sendButtonImageTint | UIColor | Send button tint | +| activeSendButtonImageBackgroundColor | UIColor | Active send button background | +| inactiveSendButtonImageBackgroundColor | UIColor | Inactive send button background | +| attachmentImage | UIImage | Attachment button icon | +| attachmentImageTint | UIColor | Attachment button tint | +| voiceRecordingImage | UIImage | Voice recording icon | +| voiceRecordingImageTint | UIColor | Voice recording tint | +| aiImage | UIImage | AI button icon | +| aiImageTint | UIColor | AI button tint | +| stickerImage | UIImage | Sticker button icon | +| stickerTint | UIColor | Sticker button tint | +| disableTypingEvents | Bool | Disables typing indicators | +| disableMentions | Bool | Disables mentions | +| hideImageAttachmentOption | Bool | Hides image attachment | +| hideVideoAttachmentOption | Bool | Hides video attachment | +| hideAudioAttachmentOption | Bool | Hides audio attachment | +| hideFileAttachmentOption | Bool | Hides file attachment | +| hidePollsOption | Bool | Hides polls option | +| hideCollaborativeDocumentOption | Bool | Hides collaborative document | +| hideCollaborativeWhiteboardOption | Bool | Hides collaborative whiteboard | +| hideAttachmentButton | Bool | Hides attachment button | +| hideVoiceRecordingButton | Bool | Hides voice recording button | +| hideStickersButton | Bool | Hides stickers button | +| hideSendButton | Bool | Hides send button | +| set(onSendButtonClick:) | (BaseMessage) -> Void | Send button callback | +| set(onTextChanged:) | (String) -> Void | Text change callback | +| set(onError:) | (CometChatException) -> Void | Error callback | +| set(attachmentOptions:) | (User?, Group?, UIViewController?) -> [CometChatMessageComposerAction] | Custom attachment options | +| set(sendButtonView:) | (User?, Group?) -> UIView | Custom send button | +| set(headerView:) | (User?, Group?) -> UIView | Custom header view | +| set(footerView:) | (User?, Group?) -> UIView | Custom footer view | +| set(textFormatter:) | [CometChatTextFormatter] | Text formatters | +| mediaRecorderStyle | MediaRecorderStyle | Media recording styling | +| aiOptionsStyle | AIOptionsStyle | AI options styling | + +#### Renamed Properties + +| v4 Name | v5 Name | Description | +| --- | --- | --- | +| background | backgroundColor | Background color | +| hide(voiceRecording:) | hideVoiceRecordingButton | Hides voice recording | +| disable(disableTypingEvents:) | disableTypingEvents | Disables typing events | +| disable(disableSoundForMessages:) | disableSoundForMessages | Disables message sound | +| setMentionsFormatters | set(textFormatter:) | Text formatters | + +#### Removed Properties + +| Name | Description | +| --- | --- | +| inputBackground | Input background color | +| textFont | Input text font | +| inputBoxPlaceholderFont | Placeholder font | +| attachmentIconTint | Attachment icon tint | +| sendIconTint | Send icon tint | +| separatorTint | Separator color | +| inputBorderWidth | Input border width | +| inputBorderColor | Input border color | +| actionSheetTitleColor | Action sheet title color | +| actionSheetTitleFont | Action sheet title font | +| voiceRecordingIconTint | Voice recording icon tint | +| aiIconTint | AI icon tint | +| set(background:) | Background color | +| set(placeholderText:) | Placeholder text | +| set(maxLines:) | Max lines | +| set(auxiliaryButtonAlignment:) | Auxiliary button position | +| set(customSoundForMessage:) | Custom message sound | +| set(liveReactionIconURL:) | Live reaction icon | +| set(disableMentions:) | Disable mentions | +| setOnSendButtonClick | Send button callback | +| hide(liveReaction:) | Hide live reaction | +| hide(footerView:) | Hide footer view | +| hide(headerView:) | Hide header view | +| hide(sendButton:) | Hide send button | +| setAttachmentOptions | Attachment options | +| setAuxilaryButtonView | Auxiliary button view | +| setSecondaryButtonView | Secondary button view | +| setSendButtonView | Send button view | + +--- + +## Next Steps + + + + Fresh v5 setup guide for iOS + + + Explore all v5 prebuilt UI components + + + New direct property-based theming system + + + Customize colors and dark mode + + From c205c5777517f8c49ec961d395e71ae9d09bf8ef Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 13:44:30 +0530 Subject: [PATCH 065/106] troubleshooting --- docs.json | 1 + ui-kit/ios/ai-assistant-chat-history.mdx | 10 - ui-kit/ios/ai-features.mdx | 10 - ui-kit/ios/call-features.mdx | 10 - ui-kit/ios/color-resources.mdx | 8 - ui-kit/ios/component-styling.mdx | 9 - ui-kit/ios/conversations.mdx | 10 - ui-kit/ios/events.mdx | 10 - ui-kit/ios/group-members.mdx | 10 - ui-kit/ios/groups.mdx | 10 - ui-kit/ios/guide-ai-agent.mdx | 10 - ui-kit/ios/guide-block-unblock-user.mdx | 9 - ui-kit/ios/message-composer.mdx | 10 - ui-kit/ios/message-header.mdx | 10 - ui-kit/ios/message-list.mdx | 11 -- ui-kit/ios/troubleshooting.mdx | 235 +++++++++++++++++++++++ ui-kit/ios/users.mdx | 10 - 17 files changed, 236 insertions(+), 147 deletions(-) create mode 100644 ui-kit/ios/troubleshooting.mdx diff --git a/docs.json b/docs.json index 883c4c1c4..539c65555 100644 --- a/docs.json +++ b/docs.json @@ -1269,6 +1269,7 @@ "ui-kit/ios/upgrading-from-v4" ] }, + "ui-kit/ios/troubleshooting", "ui-kit/ios/link/sample", "ui-kit/ios/link/figma", "ui-kit/ios/link/changelog" diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index 3ecf42158..2321f9e61 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -740,16 +740,6 @@ class ProfileViewController: UIViewController { --- -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Only loading indicator shows | Set `user` or `group` property | -| No messages displayed | Enable AI features in CometChat Dashboard | -| Styling not applied | Apply style before presenting view | -| Callbacks not firing | Set callbacks before pushing to navigation | -| Empty state not showing | Check `set(onEmpty:)` callback | - --- ## Related diff --git a/ui-kit/ios/ai-features.mdx b/ui-kit/ios/ai-features.mdx index be1e15569..f79b32825 100644 --- a/ui-kit/ios/ai-features.mdx +++ b/ui-kit/ios/ai-features.mdx @@ -505,16 +505,6 @@ extension AIAssistantListViewController: UITableViewDelegate, UITableViewDataSou --- -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| AI features not appearing | Enable them in CometChat Dashboard → AI | -| Conversation starters not showing | Only appear for new conversations with no messages | -| Smart replies not appearing | Ensure feature is enabled and messages exist | -| Summary not generating | Need sufficient messages in conversation | -| AI Assistant empty | Verify user has AI chat history | - --- ## Related diff --git a/ui-kit/ios/call-features.mdx b/ui-kit/ios/call-features.mdx index d39515839..cbe5486a8 100644 --- a/ui-kit/ios/call-features.mdx +++ b/ui-kit/ios/call-features.mdx @@ -620,16 +620,6 @@ callLogs.set(onItemClick: { callLog, indexPath in }) --- -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Call buttons not showing | Verify `CometChatCallsSDK` is in Podfile and run `pod install` | -| "Permission denied" error | Add camera/microphone permissions to Info.plist | -| Calls not connecting | Check network connection and CometChat credentials | -| No incoming call UI | Ensure `CometChatCallsSDK` is initialized before login | -| Audio not working | Check device is not on silent mode | - --- ## Related diff --git a/ui-kit/ios/color-resources.mdx b/ui-kit/ios/color-resources.mdx index 25f2e3c81..79d12bc23 100644 --- a/ui-kit/ios/color-resources.mdx +++ b/ui-kit/ios/color-resources.mdx @@ -318,14 +318,6 @@ extension UIColor { --- -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Colors not applying | Apply theme before `CometChatUIKit.init()` | -| Dark mode not working | Use `UIColor { traitCollection in }` for dynamic colors | -| Inconsistent colors | Set all related colors (text, background, border) together | - --- ## Related diff --git a/ui-kit/ios/component-styling.mdx b/ui-kit/ios/component-styling.mdx index 840811fb0..e6d47a9d0 100644 --- a/ui-kit/ios/component-styling.mdx +++ b/ui-kit/ios/component-styling.mdx @@ -548,15 +548,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate { --- -## Troubleshooting - -| Problem | Solution | -|---------|----------| -| Styles not applying | Apply global styles before `CometChatUIKit.init()` | -| Instance style overridden | Instance styles take precedence over global | -| Colors look wrong in dark mode | Use dynamic colors with `UIColor { traitCollection in }` | -| Font not loading | Verify font name is correct and font is added to project | - --- ## Related diff --git a/ui-kit/ios/conversations.mdx b/ui-kit/ios/conversations.mdx index f572914fc..2c5394ca3 100644 --- a/ui-kit/ios/conversations.mdx +++ b/ui-kit/ios/conversations.mdx @@ -1529,16 +1529,6 @@ class ConversationsContainerViewController: UINavigationController { --- -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Empty conversation list | Ensure user is logged in and has existing conversations | -| Conversations not updating in real-time | Check that CometChat SDK is properly initialized and connected | -| Navigation not working | Verify `navigationController` is not nil; embed in UINavigationController | -| Custom views not appearing | Ensure custom view has proper constraints and non-zero frame | -| Typing indicator not showing | Verify `hideTypingIndicator` is not set to true | - --- ## Related Components diff --git a/ui-kit/ios/events.mdx b/ui-kit/ios/events.mdx index 0bedb41ff..89a6ca93d 100644 --- a/ui-kit/ios/events.mdx +++ b/ui-kit/ios/events.mdx @@ -775,13 +775,3 @@ class MyViewController: UIViewController { 4. **Don't emit unnecessarily** - Only emit events when state actually changes 5. **Use a central manager** - For app-wide event handling, create a singleton manager - -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Events not firing | Verify listener is added before the action occurs | -| Duplicate events | Check you're not adding the same listener multiple times | -| Memory leaks | Ensure `removeListener` is called in `viewWillDisappear` | -| UI not updating | Dispatch UI updates to main thread with `DispatchQueue.main.async` | -| Listener ID conflicts | Use unique, descriptive IDs for each listener | diff --git a/ui-kit/ios/group-members.mdx b/ui-kit/ios/group-members.mdx index 88630ebf5..cf5067b5d 100644 --- a/ui-kit/ios/group-members.mdx +++ b/ui-kit/ios/group-members.mdx @@ -1237,16 +1237,6 @@ class GroupMembersViewController: UIViewController { --- -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Empty member list | Ensure group object is valid and has members | -| Management options not showing | Check logged-in user's permissions (must be admin/owner) | -| Search not working | Verify `hideSearch` is not set to true | -| Status not showing | Check that `hideUserStatus` is not set to true | -| Custom views not appearing | Ensure custom view has proper constraints | - --- ## Related Components diff --git a/ui-kit/ios/groups.mdx b/ui-kit/ios/groups.mdx index 5f67dbd23..770af13c6 100644 --- a/ui-kit/ios/groups.mdx +++ b/ui-kit/ios/groups.mdx @@ -1286,16 +1286,6 @@ groups.set(statusIndicatorStyle: statusIndicatorStyle) --- -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Empty group list | Ensure SDK is initialized and user is logged in | -| Groups not updating in real-time | Check SDK connection and group listeners | -| Search not working | Verify `hideSearch` is not set to true | -| Group type icons not showing | Check that `hideGroupType` is not set to true | -| Custom views not appearing | Ensure custom view has proper constraints | - --- ## Related Components diff --git a/ui-kit/ios/guide-ai-agent.mdx b/ui-kit/ios/guide-ai-agent.mdx index ec3a6f5f3..0a18bb6b2 100644 --- a/ui-kit/ios/guide-ai-agent.mdx +++ b/ui-kit/ios/guide-ai-agent.mdx @@ -516,16 +516,6 @@ class ChatHistoryViewController: UIViewController { | `CometChatAIAssistantChatHistory` | Browse previous AI conversations | | `CometChatAiAssistantBubble` | AI message bubble styling | -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| AI not responding | Verify AI features are enabled in dashboard | -| Chat history empty | Ensure conversations are saved properly | -| Streaming not working | Check network connectivity | -| Styling not applied | Apply styles before presenting components | -| Agent not detected | Verify user role contains "agentic" | - ## Related Guides diff --git a/ui-kit/ios/guide-block-unblock-user.mdx b/ui-kit/ios/guide-block-unblock-user.mdx index 820ef4401..0484e14d8 100644 --- a/ui-kit/ios/guide-block-unblock-user.mdx +++ b/ui-kit/ios/guide-block-unblock-user.mdx @@ -679,15 +679,6 @@ avatar.set(style: avatarStyle) | Call initiation failed | Check permissions and call SDK setup | | Delete conversation failed | Verify conversation exists | -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Status not updating | Verify event listeners are added | -| Block state incorrect | Fetch blocked users list on load | -| Call buttons missing | Import CometChatCallsSDK | -| Avatar not loading | Check user has valid avatar URL | - ## Related Guides diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index 5465cf9c4..2cb097db8 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -1049,16 +1049,6 @@ The MessageComposer component does not emit any global UI events. --- -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Send button not working | Ensure user or group is set on the composer | -| Attachments not showing | Check that attachment options are not hidden | -| Voice recording not working | Verify microphone permissions are granted | -| Mentions not working | Ensure `disableMentions` is not set to true | -| Typing indicators not sent | Check that `disableTypingEvents` is not set to true | - --- ## Related Components diff --git a/ui-kit/ios/message-header.mdx b/ui-kit/ios/message-header.mdx index 56f85b14d..5895e902e 100644 --- a/ui-kit/ios/message-header.mdx +++ b/ui-kit/ios/message-header.mdx @@ -1106,16 +1106,6 @@ messageHeader.dateTimeFormatter.otherDay = { timestamp in --- -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Header not showing user info | Ensure user or group is set on the header | -| Status not updating | Check SDK connection and user presence listeners | -| Back button not working | Verify `onBack` callback is set and `hideBackButton` is false | -| Typing indicator not showing | Ensure typing events are enabled in SDK | -| Call buttons not appearing | Check that `hideVideoCallButton` and `hideVoiceCallButton` are false | - --- ## Related Components diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index e6b63d20a..9454ec9cb 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -1967,17 +1967,6 @@ messageList.set(dateSeparatorPattern: { timestamp in --- -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Messages not loading | Ensure user/group is set and SDK is initialized | -| Real-time updates not working | Check SDK connection status and listeners | -| Reactions not showing | Verify reactions are enabled in dashboard | -| Thread replies not working | Ensure `hideReplyInThreadOption` is not set to true | -| Custom views not appearing | Ensure custom view has proper constraints and non-zero frame | -| Scroll position issues | Check `scrollToBottomOnNewMessages` setting | - --- ## Related Components diff --git a/ui-kit/ios/troubleshooting.mdx b/ui-kit/ios/troubleshooting.mdx new file mode 100644 index 000000000..e22678d56 --- /dev/null +++ b/ui-kit/ios/troubleshooting.mdx @@ -0,0 +1,235 @@ +--- +title: "Troubleshooting" +sidebarTitle: "Troubleshooting" +description: "Common issues and solutions for CometChat iOS UI Kit" +--- + + + +| Field | Value | +| --- | --- | +| Platform | iOS UI Kit | +| Common Issues | Initialization, theming, real-time updates, permissions | +| Key Checks | SDK initialization, user login, CometChatUIKit.init() order | +| Permissions | Camera, microphone (Info.plist) | +| Debug | Check SDK connection status, verify dashboard settings | + + + +This guide covers common issues and solutions when working with the CometChat iOS UI Kit. + +--- + +## Initialization Issues + +| Issue | Solution | +|-------|----------| +| SDK not initialized | Call `CometChat.init()` before any UI Kit operations | +| User not logged in | Ensure `CometChat.login()` completes successfully before showing UI | +| UIKit not initialized | Call `CometChatUIKit.init()` after SDK init and before using components | +| Credentials invalid | Verify App ID, Auth Key, and Region in CometChat Dashboard | + +--- + +## Theming & Styling + +| Issue | Solution | +|-------|----------| +| Colors not applying | Apply theme before `CometChatUIKit.init()` | +| Dark mode not working | Use `UIColor { traitCollection in }` for dynamic colors | +| Inconsistent colors | Set all related colors (text, background, border) together | +| Styles not applying | Apply global styles before `CometChatUIKit.init()` | +| Instance style overridden | Instance styles take precedence over global styles | +| Font not loading | Verify font name is correct and font is added to project | + +--- + +## Conversations + +| Issue | Solution | +|-------|----------| +| Empty conversation list | Ensure user is logged in and has existing conversations | +| Conversations not updating | Check SDK connection and real-time listeners | +| Navigation not working | Verify `navigationController` is not nil; embed in `UINavigationController` | +| Custom views not appearing | Ensure custom view has proper constraints and non-zero frame | +| Typing indicator not showing | Verify `hideTypingIndicator` is not set to true | + +--- + +## Users + +| Issue | Solution | +|-------|----------| +| Empty user list | Ensure SDK is initialized and user is logged in | +| Users not updating in real-time | Check SDK connection and presence listeners | +| Search not working | Verify `hideSearch` is not set to true | +| Status not showing | Check that `hideUserStatus` is not set to true | +| Custom views not appearing | Ensure custom view has proper constraints | + +--- + +## Groups + +| Issue | Solution | +|-------|----------| +| Empty group list | Ensure SDK is initialized and user is logged in | +| Groups not updating in real-time | Check SDK connection and group listeners | +| Search not working | Verify `hideSearch` is not set to true | +| Group type icons not showing | Check that `hideGroupType` is not set to true | +| Custom views not appearing | Ensure custom view has proper constraints | + +--- + +## Group Members + +| Issue | Solution | +|-------|----------| +| Empty member list | Ensure group object is valid and has members | +| Management options not showing | Check logged-in user's permissions (must be admin/owner) | +| Search not working | Verify `hideSearch` is not set to true | +| Status not showing | Check that `hideUserStatus` is not set to true | +| Custom views not appearing | Ensure custom view has proper constraints | + +--- + +## Message Header + +| Issue | Solution | +|-------|----------| +| Header not showing user info | Ensure user or group is set on the header | +| Status not updating | Check SDK connection and user presence listeners | +| Back button not working | Verify `onBack` callback is set and `hideBackButton` is false | +| Typing indicator not showing | Ensure typing events are enabled in SDK | +| Call buttons not appearing | Check that `hideVideoCallButton` and `hideVoiceCallButton` are false | + +--- + +## Message List + +| Issue | Solution | +|-------|----------| +| Messages not loading | Ensure user/group is set and SDK is initialized | +| Real-time updates not working | Check SDK connection status and listeners | +| Reactions not showing | Verify reactions are enabled in dashboard | +| Thread replies not working | Ensure `hideReplyInThreadOption` is not set to true | +| Custom views not appearing | Ensure custom view has proper constraints and non-zero frame | +| Scroll position issues | Check `scrollToBottomOnNewMessages` setting | + +--- + +## Message Composer + +| Issue | Solution | +|-------|----------| +| Send button not working | Ensure user or group is set on the composer | +| Attachments not showing | Check that attachment options are not hidden | +| Voice recording not working | Verify microphone permissions are granted in Info.plist | +| Mentions not working | Ensure `disableMentions` is not set to true | +| Typing indicators not sent | Check that `disableTypingEvents` is not set to true | + +--- + +## Calling + +| Issue | Solution | +|-------|----------| +| Call buttons not showing | Verify `CometChatCallsSDK` is in Podfile and run `pod install` | +| "Permission denied" error | Add camera/microphone permissions to Info.plist | +| Calls not connecting | Check network connection and CometChat credentials | +| No incoming call UI | Ensure `CometChatCallsSDK` is initialized before login | +| Audio not working | Check device is not on silent mode | + +--- + +## AI Features + +| Issue | Solution | +|-------|----------| +| AI features not appearing | Enable them in CometChat Dashboard → AI | +| Conversation starters not showing | Only appear for new conversations with no messages | +| Smart replies not appearing | Ensure feature is enabled and messages exist | +| Summary not generating | Need sufficient messages in conversation | +| AI Assistant empty | Verify user has AI chat history | +| Only loading indicator shows | Set `user` or `group` property | +| Styling not applied | Apply style before presenting view | +| Callbacks not firing | Set callbacks before pushing to navigation | +| AI not responding | Verify AI features are enabled in dashboard | +| Streaming not working | Check network connectivity | +| Agent not detected | Verify user role contains "agentic" | + +--- + +## Events + +| Issue | Solution | +|-------|----------| +| Events not firing | Verify listener is added before the action occurs | +| Duplicate events | Check you're not adding the same listener multiple times | +| Memory leaks | Ensure `removeListener` is called in `viewWillDisappear` | +| UI not updating | Dispatch UI updates to main thread with `DispatchQueue.main.async` | +| Listener ID conflicts | Use unique, descriptive IDs for each listener | + +--- + +## Permissions (Info.plist) + +Add these keys to your `Info.plist` for full functionality: + +```xml + +NSCameraUsageDescription +Camera access is required for video calls and capturing photos + + +NSMicrophoneUsageDescription +Microphone access is required for voice calls and audio messages + + +NSPhotoLibraryUsageDescription +Photo library access is required to send images +``` + +--- + +## Debug Checklist + +When troubleshooting issues, verify the following: + +1. **SDK Initialization** + - `CometChat.init()` called with correct App ID and Region + - `CometChatUIKit.init()` called after SDK init + +2. **User Authentication** + - User is logged in via `CometChat.login()` + - Auth token is valid and not expired + +3. **Dashboard Settings** + - Features are enabled (AI, Reactions, etc.) + - API keys have correct permissions + +4. **Network** + - Device has internet connectivity + - WebSocket connection is established + +5. **Permissions** + - Required permissions added to Info.plist + - User has granted permissions at runtime + +--- + +## Getting Help + + + + Complete implementation example + + + CometChat UIKit iOS repository + + + Complete list of error codes + + + Contact CometChat support + + diff --git a/ui-kit/ios/users.mdx b/ui-kit/ios/users.mdx index ac98c622d..e62adda9a 100644 --- a/ui-kit/ios/users.mdx +++ b/ui-kit/ios/users.mdx @@ -1350,16 +1350,6 @@ Custom request builder for filtering users. --- -## Troubleshooting - -| Issue | Solution | -|-------|----------| -| Empty user list | Ensure SDK is initialized and user is logged in | -| Users not updating in real-time | Check SDK connection and presence listeners | -| Search not working | Verify `hideSearch` is not set to true | -| Status not showing | Check that `hideUserStatus` is not set to true | -| Custom views not appearing | Ensure custom view has proper constraints | - --- ## Related Components From e2826378d9621d44ec386a7133a698f796ce5cc5 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 13:58:43 +0530 Subject: [PATCH 066/106] AI Integration Quick Reference --- ui-kit/ios/ai-assistant-chat-history.mdx | 2 +- ui-kit/ios/ai-features.mdx | 2 +- ui-kit/ios/call-buttons.mdx | 2 +- ui-kit/ios/call-features.mdx | 2 +- ui-kit/ios/call-logs.mdx | 2 +- ui-kit/ios/components-overview.mdx | 2 +- ui-kit/ios/conversations.mdx | 2 +- ui-kit/ios/core-features.mdx | 2 +- ui-kit/ios/events.mdx | 2 +- ui-kit/ios/extensions.mdx | 2 +- ui-kit/ios/group-members.mdx | 2 +- ui-kit/ios/groups.mdx | 2 +- ui-kit/ios/incoming-call.mdx | 2 +- ui-kit/ios/message-composer.mdx | 2 +- ui-kit/ios/message-header.mdx | 2 +- ui-kit/ios/message-list.mdx | 2 +- ui-kit/ios/methods.mdx | 2 +- ui-kit/ios/ongoing-call.mdx | 2 +- ui-kit/ios/outgoing-call.mdx | 2 +- ui-kit/ios/overview.mdx | 2 +- ui-kit/ios/search.mdx | 2 +- ui-kit/ios/threaded-messages-header.mdx | 2 +- ui-kit/ios/users.mdx | 2 +- 23 files changed, 23 insertions(+), 23 deletions(-) diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index 2321f9e61..723b710a5 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -10,7 +10,7 @@ The `CometChatAIAssistanceChatHistory` component displays past conversations bet - + ```json { "component": "CometChatAIAssistanceChatHistory", diff --git a/ui-kit/ios/ai-features.mdx b/ui-kit/ios/ai-features.mdx index f79b32825..a299c6973 100644 --- a/ui-kit/ios/ai-features.mdx +++ b/ui-kit/ios/ai-features.mdx @@ -4,7 +4,7 @@ sidebarTitle: "Smart Chat Features" description: "Complete guide to AI-powered chat features in iOS apps - conversation starters, smart replies, and summaries" --- - + ```json { "category": "ai", diff --git a/ui-kit/ios/call-buttons.mdx b/ui-kit/ios/call-buttons.mdx index 24010862a..831026ab1 100644 --- a/ui-kit/ios/call-buttons.mdx +++ b/ui-kit/ios/call-buttons.mdx @@ -9,7 +9,7 @@ The `CometChatCallButtons` component provides users with the ability to make cal CometChatCallButtons showing voice and video call buttons for initiating calls - + ```json { "component": "CometChatCallButtons", diff --git a/ui-kit/ios/call-features.mdx b/ui-kit/ios/call-features.mdx index cbe5486a8..5d2200516 100644 --- a/ui-kit/ios/call-features.mdx +++ b/ui-kit/ios/call-features.mdx @@ -4,7 +4,7 @@ sidebarTitle: "Call" description: "Complete guide to adding voice and video calling to iOS apps with CometChat UI Kit - production-ready code included" --- - + ```json { "category": "calling", diff --git a/ui-kit/ios/call-logs.mdx b/ui-kit/ios/call-logs.mdx index 503e71e94..0b4010081 100644 --- a/ui-kit/ios/call-logs.mdx +++ b/ui-kit/ios/call-logs.mdx @@ -9,7 +9,7 @@ The `CometChatCallLogs` component shows the list of call logs available. By defa CometChatCallLogs showing a list of call history with caller names, call types, and timestamps - + ```json { "component": "CometChatCallLogs", diff --git a/ui-kit/ios/components-overview.mdx b/ui-kit/ios/components-overview.mdx index e0cba4d8d..420828875 100644 --- a/ui-kit/ios/components-overview.mdx +++ b/ui-kit/ios/components-overview.mdx @@ -4,7 +4,7 @@ sidebarTitle: "Overview" description: "Understanding CometChat iOS UI Kit components - types, actions, events, and customization" --- - + ```json { "platform": "iOS UI Kit", diff --git a/ui-kit/ios/conversations.mdx b/ui-kit/ios/conversations.mdx index 2c5394ca3..e057ff3e3 100644 --- a/ui-kit/ios/conversations.mdx +++ b/ui-kit/ios/conversations.mdx @@ -9,7 +9,7 @@ The `CometChatConversations` component displays a list of all conversations (one CometChatConversations showing a list of recent conversations with user avatars, last message previews, timestamps, and unread message badges - + ```json { "component": "CometChatConversations", diff --git a/ui-kit/ios/core-features.mdx b/ui-kit/ios/core-features.mdx index 7754c5a85..9405a0790 100644 --- a/ui-kit/ios/core-features.mdx +++ b/ui-kit/ios/core-features.mdx @@ -3,7 +3,7 @@ title: "Core Features" description: "Essential chat features built into CometChat UI Kit for iOS" --- - + ```json { "category": "messaging", diff --git a/ui-kit/ios/events.mdx b/ui-kit/ios/events.mdx index 89a6ca93d..cdbcf7ad8 100644 --- a/ui-kit/ios/events.mdx +++ b/ui-kit/ios/events.mdx @@ -3,7 +3,7 @@ title: "Events" description: "Listen and respond to user actions and state changes in CometChat UI Kit" --- - + ```json { "category": "events", diff --git a/ui-kit/ios/extensions.mdx b/ui-kit/ios/extensions.mdx index ef5fcd9cf..74426fb4d 100644 --- a/ui-kit/ios/extensions.mdx +++ b/ui-kit/ios/extensions.mdx @@ -3,7 +3,7 @@ title: "Extensions" description: "Enable powerful chat features with zero code using CometChat extensions" --- - + ```json { "category": "extensions", diff --git a/ui-kit/ios/group-members.mdx b/ui-kit/ios/group-members.mdx index cf5067b5d..907a84bb9 100644 --- a/ui-kit/ios/group-members.mdx +++ b/ui-kit/ios/group-members.mdx @@ -9,7 +9,7 @@ The `CometChatGroupMembers` component displays all members of a group with their CometChatGroupMembers showing a list of group members with their avatars, names, and role badges indicating owner, admin, moderator, and participant status - + ```json { "component": "CometChatGroupMembers", diff --git a/ui-kit/ios/groups.mdx b/ui-kit/ios/groups.mdx index 770af13c6..d0a118569 100644 --- a/ui-kit/ios/groups.mdx +++ b/ui-kit/ios/groups.mdx @@ -9,7 +9,7 @@ The `CometChatGroups` component displays a searchable list of all available grou CometChatGroups showing a searchable list of groups with avatars, names, member counts, and group type indicators - + ```json { "component": "CometChatGroups", diff --git a/ui-kit/ios/incoming-call.mdx b/ui-kit/ios/incoming-call.mdx index dbf566017..63d6ced5c 100644 --- a/ui-kit/ios/incoming-call.mdx +++ b/ui-kit/ios/incoming-call.mdx @@ -9,7 +9,7 @@ The `CometChatIncomingCall` component serves as a visual representation when the CometChatIncomingCall showing incoming call interface with caller avatar, name, and accept/reject buttons - + ```json { "component": "CometChatIncomingCall", diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index 2cb097db8..2f685bb84 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -9,7 +9,7 @@ The `CometChatMessageComposer` component enables users to write and send message CometChatMessageComposer showing the default message input field with attachment, voice recording, and send buttons - + ```json { "component": "CometChatMessageComposer", diff --git a/ui-kit/ios/message-header.mdx b/ui-kit/ios/message-header.mdx index 5895e902e..3c50b0a72 100644 --- a/ui-kit/ios/message-header.mdx +++ b/ui-kit/ios/message-header.mdx @@ -9,7 +9,7 @@ The `CometChatMessageHeader` component displays user or group details in the too CometChatMessageHeader showing user avatar, name, online status, and call buttons in the navigation bar - + ```json { "component": "CometChatMessageHeader", diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index 9454ec9cb..aad1240ce 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -9,7 +9,7 @@ The `CometChatMessageList` component displays a scrollable list of messages in a CometChatMessageList showing a scrollable list of chat messages with text bubbles, timestamps, and read receipts in a conversation view - + ```json { "component": "CometChatMessageList", diff --git a/ui-kit/ios/methods.mdx b/ui-kit/ios/methods.mdx index d19ef0d27..adf0384c3 100644 --- a/ui-kit/ios/methods.mdx +++ b/ui-kit/ios/methods.mdx @@ -2,7 +2,7 @@ title: "Methods" --- - + ```json { "category": "methods", diff --git a/ui-kit/ios/ongoing-call.mdx b/ui-kit/ios/ongoing-call.mdx index 3f3045664..177eabb95 100644 --- a/ui-kit/ios/ongoing-call.mdx +++ b/ui-kit/ios/ongoing-call.mdx @@ -9,7 +9,7 @@ The `CometChatOngoingCall` component provides users with a dedicated interface f - + ```json { "component": "CometChatOngoingCall", diff --git a/ui-kit/ios/outgoing-call.mdx b/ui-kit/ios/outgoing-call.mdx index 642cd5e7a..eff504924 100644 --- a/ui-kit/ios/outgoing-call.mdx +++ b/ui-kit/ios/outgoing-call.mdx @@ -9,7 +9,7 @@ The `CometChatOutgoingCall` component is a visual representation of a user-initi CometChatOutgoingCall showing outgoing call interface with recipient avatar, name, and cancel button - + ```json { "component": "CometChatOutgoingCall", diff --git a/ui-kit/ios/overview.mdx b/ui-kit/ios/overview.mdx index 48985e87a..dc56ca772 100644 --- a/ui-kit/ios/overview.mdx +++ b/ui-kit/ios/overview.mdx @@ -4,7 +4,7 @@ sidebarTitle: "Overview" description: "Integrate chat functionality into iOS applications with prebuilt, modular, and customizable UI components" --- - + ```json { "platform": "iOS UI Kit", diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index a531785cf..dc9532c6d 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -10,7 +10,7 @@ The `CometChatSearch` component is a powerful and customizable search interface CometChatSearch showing the search interface with search bar, filter options, and search results displaying conversations and messages - + ```json { "component": "CometChatSearch", diff --git a/ui-kit/ios/threaded-messages-header.mdx b/ui-kit/ios/threaded-messages-header.mdx index 6f9b50893..54bdebdd3 100644 --- a/ui-kit/ios/threaded-messages-header.mdx +++ b/ui-kit/ios/threaded-messages-header.mdx @@ -10,7 +10,7 @@ The `CometChatThreadedMessageHeader` component displays the header for threaded - + ```json { "component": "CometChatThreadedMessageHeader", diff --git a/ui-kit/ios/users.mdx b/ui-kit/ios/users.mdx index e62adda9a..9a38a27c6 100644 --- a/ui-kit/ios/users.mdx +++ b/ui-kit/ios/users.mdx @@ -9,7 +9,7 @@ The `CometChatUsers` component displays a searchable list of all available users CometChatUsers showing a searchable list of users with avatars, names, and online/offline status indicators - + ```json { "component": "CometChatUsers", From 017843347912c0c117ba13ad1b006fe1f17131da Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 15:10:45 +0530 Subject: [PATCH 067/106] improves components --- ui-kit/ios/ai-assistant-chat-history.mdx | 139 ++++++++++++++++++++++- ui-kit/ios/call-buttons.mdx | 106 ++++++++++++++++- ui-kit/ios/call-logs.mdx | 131 ++++++++++++++++++++- ui-kit/ios/conversations.mdx | 54 ++++++++- ui-kit/ios/group-members.mdx | 45 ++++++++ ui-kit/ios/groups.mdx | 62 ++++++++++ ui-kit/ios/incoming-call.mdx | 83 +++++++++++++- ui-kit/ios/message-composer.mdx | 59 ++++++++++ ui-kit/ios/message-header.mdx | 53 +++++++++ ui-kit/ios/message-list.mdx | 57 ++++++++++ ui-kit/ios/ongoing-call.mdx | 99 ++++++++++++++++ ui-kit/ios/outgoing-call.mdx | 97 +++++++++++++++- ui-kit/ios/search.mdx | 129 +++++++++++++++++++++ ui-kit/ios/threaded-messages-header.mdx | 64 +++++++++++ ui-kit/ios/users.mdx | 64 +++++++++++ 15 files changed, 1223 insertions(+), 19 deletions(-) diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index 723b710a5..235d64b33 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -740,11 +740,142 @@ class ProfileViewController: UIViewController { --- +## Common Patterns + +### Present AI Chat History from Profile + +Show AI chat history when user taps a button in their profile: + + + +```swift +@objc func showAIChatHistory() { + guard let currentUser = CometChat.getLoggedInUser() else { return } + + let chatHistory = CometChatAIAssistanceChatHistory() + chatHistory.user = currentUser + + chatHistory.onNewChatButtonClicked = { [weak self] user in + let messagesVC = CometChatMessages() + messagesVC.user = user + self?.navigationController?.pushViewController(messagesVC, animated: true) + } + + navigationController?.pushViewController(chatHistory, animated: true) +} +``` + + + +### Handle Message Selection from History + +Navigate to the full conversation when a message is tapped: + + + +```swift +let chatHistory = CometChatAIAssistanceChatHistory() +chatHistory.user = user + +chatHistory.onMessageClicked = { [weak self] message in + // Open the messages view to continue the conversation + let messagesVC = CometChatMessages() + messagesVC.user = self?.user + self?.navigationController?.pushViewController(messagesVC, animated: true) +} +``` + + + +### Custom Date Formatting for AI History + +Format dates to show relative time for recent conversations: + + + +```swift +let chatHistory = CometChatAIAssistanceChatHistory() +chatHistory.user = user + +// Instance-level date formatting +chatHistory.dateTimeFormatter.today = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.timeStyle = .short + return "Today at \(formatter.string(from: date))" +} + +chatHistory.dateTimeFormatter.yesterday = { timestamp in + let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) + let formatter = DateFormatter() + formatter.timeStyle = .short + return "Yesterday at \(formatter.string(from: date))" +} + +// Or use global-level formatting +CometChatAIAssistanceChatHistory.dateTimeFormatter.otherDay = { timestamp in + let formatter = DateFormatter() + formatter.dateFormat = "MMM d, yyyy" + return formatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))) +} +``` + + + +### AI History as Tab in Main Navigation + +Add AI chat history as a dedicated tab: + + + +```swift +class MainTabBarController: UITabBarController { + + override func viewDidLoad() { + super.viewDidLoad() + + guard let currentUser = CometChat.getLoggedInUser() else { return } + + let aiHistory = CometChatAIAssistanceChatHistory() + aiHistory.user = currentUser + + aiHistory.onNewChatButtonClicked = { [weak self] user in + let messagesVC = CometChatMessages() + messagesVC.user = user + if let nav = self?.selectedViewController as? UINavigationController { + nav.pushViewController(messagesVC, animated: true) + } + } + + let aiNav = UINavigationController(rootViewController: aiHistory) + aiNav.tabBarItem = UITabBarItem( + title: "AI Assistant", + image: UIImage(systemName: "sparkles"), + selectedImage: UIImage(systemName: "sparkles") + ) + + viewControllers = [/* other tabs */, aiNav] + } +} +``` + + + --- ## Related -- [AI Features Overview](/ui-kit/ios/ai-features) - All AI features -- [Message List](/ui-kit/ios/message-list) - Chat message display -- [Message Composer](/ui-kit/ios/message-composer) - Message input -- [Components Overview](/ui-kit/ios/components-overview) - All components + + + All AI features + + + Chat message display + + + Message input + + + All components + + diff --git a/ui-kit/ios/call-buttons.mdx b/ui-kit/ios/call-buttons.mdx index 831026ab1..09e236b6c 100644 --- a/ui-kit/ios/call-buttons.mdx +++ b/ui-kit/ios/call-buttons.mdx @@ -459,10 +459,110 @@ Events emitted by the Call Buttons component: --- +## Common Patterns + +### Add Call Buttons to Message Header + +Integrate call buttons into a custom message header: + + + +```swift +class CustomMessageHeader: UIView { + + private var callButtons: CometChatCallButtons! + + func configure(with user: User) { + callButtons = CometChatCallButtons(width: 24, height: 24) + callButtons.set(user: user) + callButtons.set(controller: parentViewController) + + // Add to header view + addSubview(callButtons) + // Set up constraints... + } +} +``` + + + +### Voice-Only Call Button + +Show only the voice call button for audio-focused apps: + + + +```swift +let callButtons = CometChatCallButtons(width: 24, height: 24) +callButtons.set(user: user) +callButtons.hideVideoCallButton = true +callButtons.set(controller: self) +``` + + + +### Custom Call Initiation with Confirmation + +Show confirmation before starting a call: + + + +```swift +let callButtons = CometChatCallButtons(width: 24, height: 24) +callButtons.set(user: user) +callButtons.set(onVoiceCallClick: { [weak self] user, group in + let alert = UIAlertController( + title: "Start Voice Call", + message: "Call \(user?.name ?? group?.name ?? "")?", + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + alert.addAction(UIAlertAction(title: "Call", style: .default) { _ in + // Initiate the call + self?.initiateVoiceCall(to: user, group: group) + }) + self?.present(alert, animated: true) +}) +``` + + + +### Group Video Call Button + +Configure call buttons for group video calls: + + + +```swift +let callButtons = CometChatCallButtons(width: 24, height: 24) +callButtons.set(group: group) +callButtons.hideVoiceCallButton = true // Groups often use video calls +callButtons.set(controller: self) + +// Custom call settings for group calls +callButtons.set(callSettingBuilder: { callType, participants in + return CallSettingsBuilder() + .setDefaultLayout(true) + .setShowRecordingButton(true) +}) +``` + + + +--- + ## Related Components -- [Incoming Call](/ui-kit/ios/incoming-call) - Display incoming call interface -- [Outgoing Call](/ui-kit/ios/outgoing-call) - Display outgoing call interface -- [Call Logs](/ui-kit/ios/call-logs) - Display call history + + + Display incoming call interface + + + Display outgoing call interface + + + Display call history + + *** diff --git a/ui-kit/ios/call-logs.mdx b/ui-kit/ios/call-logs.mdx index 0b4010081..43ee06650 100644 --- a/ui-kit/ios/call-logs.mdx +++ b/ui-kit/ios/call-logs.mdx @@ -1075,10 +1075,135 @@ Ensure to pass and present `CometChatCallLogs`. If a navigation controller is al --- +## Common Patterns + +### Present Call Logs as a Tab + +Add call logs as a tab in your main navigation: + + + +```swift +class MainTabBarController: UITabBarController { + + override func viewDidLoad() { + super.viewDidLoad() + + let callLogs = CometChatCallLogs() + let callLogsNav = UINavigationController(rootViewController: callLogs) + callLogsNav.tabBarItem = UITabBarItem( + title: "Calls", + image: UIImage(systemName: "phone"), + selectedImage: UIImage(systemName: "phone.fill") + ) + + viewControllers = [/* other tabs */, callLogsNav] + } +} +``` + + + +### Callback on Call Log Selection + +Handle call log selection to initiate a callback: + + + +```swift +let callLogs = CometChatCallLogs() +callLogs.set(onItemClick: { [weak self] callLog, indexPath in + // Get the other participant + var callUser: CallUser? + if let initiator = callLog.initiator as? CallUser, + initiator.uid != CometChatUIKit.getLoggedInUser()?.uid { + callUser = initiator + } else if let receiver = callLog.receiver as? CallUser { + callUser = receiver + } + + guard let user = callUser else { return } + + // Show callback options + let alert = UIAlertController(title: "Call \(user.name ?? "")?", message: nil, preferredStyle: .actionSheet) + alert.addAction(UIAlertAction(title: "Voice Call", style: .default) { _ in + self?.initiateCall(uid: user.uid ?? "", type: .audio) + }) + alert.addAction(UIAlertAction(title: "Video Call", style: .default) { _ in + self?.initiateCall(uid: user.uid ?? "", type: .video) + }) + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + self?.present(alert, animated: true) +}) +``` + + + +### Filter Call Logs by Type + +Show only missed calls or specific call types: + + + +```swift +// Show only missed calls +let missedCallsBuilder = CallLogsRequest.CallLogsBuilder() + .set(callStatus: .unanswered) + .set(limit: 30) + +let callLogs = CometChatCallLogs() +callLogs.set(callRequestBuilder: missedCallsBuilder) + +// Show only video calls +let videoCallsBuilder = CallLogsRequest.CallLogsBuilder() + .set(callType: .video) + .set(limit: 30) +``` + + + +### Call Logs with Custom Empty State + +Show a custom view when there are no call logs: + + + +```swift +let callLogs = CometChatCallLogs() + +callLogs.set(onEmpty: { [weak self] in + // Show custom empty state or prompt user to make their first call + print("No call history yet") +}) + +// Or set a custom empty view +let emptyView = UIView() +let label = UILabel() +label.text = "No calls yet\nStart a conversation!" +label.textAlignment = .center +label.numberOfLines = 0 +emptyView.addSubview(label) +// Add constraints... + +callLogs.set(emptyView: emptyView) +``` + + + +--- + ## Related Components -- [Incoming Call](/ui-kit/ios/incoming-call) - Display incoming call interface -- [Outgoing Call](/ui-kit/ios/outgoing-call) - Display outgoing call interface -- [Call Buttons](/ui-kit/ios/call-buttons) - Voice and video call buttons + + + Display incoming call interface + + + Display outgoing call interface + + + Voice and video call buttons + + *** diff --git a/ui-kit/ios/conversations.mdx b/ui-kit/ios/conversations.mdx index e057ff3e3..ca37fb595 100644 --- a/ui-kit/ios/conversations.mdx +++ b/ui-kit/ios/conversations.mdx @@ -1457,9 +1457,11 @@ class MentionConfiguredViewController: UIViewController { --- -## Complete App Example +## Common Patterns -Here's a full implementation with tab bar integration showing how to use CometChatConversations in a real app: +### Tab bar integration + +Full implementation with tab bar showing CometChatConversations in a real app: ```swift import UIKit @@ -1527,7 +1529,53 @@ class ConversationsContainerViewController: UINavigationController { } ``` ---- +### Custom empty state with CTA + +```swift +let conversations = CometChatConversations() + +conversations.set(emptyStateView: { + let emptyView = UIView() + + let label = UILabel() + label.text = "No conversations yet" + label.textAlignment = .center + label.textColor = .secondaryLabel + + let button = UIButton(type: .system) + button.setTitle("Start a conversation", for: .normal) + button.addTarget(self, action: #selector(startNewConversation), for: .touchUpInside) + + // Add subviews and constraints... + return emptyView +}) +``` + +### Hide all chrome — minimal list + +```swift +let conversations = CometChatConversations() +conversations.hideReceipts = true +conversations.hideUserStatus = true +conversations.hideGroupType = true +conversations.hideDeleteConversationOption = true +``` + +### Filter by conversation type + +```swift +// Only user conversations +let userOnlyBuilder = ConversationRequest.ConversationRequestBuilder(limit: 30) + .set(conversationType: .user) + +let conversations = CometChatConversations(conversationRequestBuilder: userOnlyBuilder) + +// Only group conversations +let groupOnlyBuilder = ConversationRequest.ConversationRequestBuilder(limit: 30) + .set(conversationType: .group) + +let groupConversations = CometChatConversations(conversationRequestBuilder: groupOnlyBuilder) +``` --- diff --git a/ui-kit/ios/group-members.mdx b/ui-kit/ios/group-members.mdx index 907a84bb9..38e5f0420 100644 --- a/ui-kit/ios/group-members.mdx +++ b/ui-kit/ios/group-members.mdx @@ -1237,6 +1237,51 @@ class GroupMembersViewController: UIViewController { --- +## Common Patterns + +### Admins and moderators only + +```swift +let adminBuilder = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid) + .set(scopes: ["admin", "moderator"]) + +let groupMembers = CometChatGroupMembers(group: group, groupMembersRequestBuilder: adminBuilder) +``` + +### Hide management options for participants + +```swift +let groupMembers = CometChatGroupMembers(group: group) +groupMembers.hideKickMemberOption = true +groupMembers.hideBanMemberOption = true +groupMembers.hideScopeChangeOption = true +``` + +### Custom empty state + +```swift +let groupMembers = CometChatGroupMembers(group: group) + +groupMembers.set(emptyStateView: { + let label = UILabel() + label.text = "No members in this group" + label.textAlignment = .center + return label +}) +``` + +### Multi-select members + +```swift +let groupMembers = CometChatGroupMembers(group: group) +groupMembers.selectionMode = .multiple + +groupMembers.set(onSelection: { selectedMembers in + print("Selected \(selectedMembers.count) members") + // Kick selected members, change scope, etc. +}) +``` + --- ## Related Components diff --git a/ui-kit/ios/groups.mdx b/ui-kit/ios/groups.mdx index d0a118569..0c72cb3ef 100644 --- a/ui-kit/ios/groups.mdx +++ b/ui-kit/ios/groups.mdx @@ -1286,6 +1286,68 @@ groups.set(statusIndicatorStyle: statusIndicatorStyle) --- +## Common Patterns + +### Public groups only + +```swift +let publicBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) + .set(groupType: .public) + +let groups = CometChatGroups() +groups.set(groupsRequestBuilder: publicBuilder) +``` + +### Joined groups only + +```swift +let joinedBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) + .set(joinedOnly: true) + +let groups = CometChatGroups() +groups.set(groupsRequestBuilder: joinedBuilder) +``` + +### Custom empty state with CTA + +```swift +let groups = CometChatGroups() + +groups.set(emptyStateView: { + let emptyView = UIView() + + let label = UILabel() + label.text = "No groups found" + label.textAlignment = .center + + let button = UIButton(type: .system) + button.setTitle("Create a group", for: .normal) + + // Add subviews and constraints... + return emptyView +}) +``` + +### Hide all chrome — minimal list + +```swift +let groups = CometChatGroups() +groups.hideSearch = true +groups.hideGroupType = true +groups.hideSectionHeader = true +``` + +### Multi-select groups + +```swift +let groups = CometChatGroups() +groups.selectionMode = .multiple + +groups.set(onSelection: { selectedGroups in + print("Selected \(selectedGroups.count) groups") +}) +``` + --- ## Related Components diff --git a/ui-kit/ios/incoming-call.mdx b/ui-kit/ios/incoming-call.mdx index 63d6ced5c..37cc0e44f 100644 --- a/ui-kit/ios/incoming-call.mdx +++ b/ui-kit/ios/incoming-call.mdx @@ -743,8 +743,85 @@ cometChatIncomingCall.set(trailingView: { call in --- +## Common Patterns + +### Present Incoming Call Screen + +Present the incoming call screen when a call is received: + + + +```swift +// In your call listener +func onIncomingCallReceived(incomingCall: Call) { + DispatchQueue.main.async { + let incomingCallVC = CometChatIncomingCall() + incomingCallVC.set(call: incomingCall) + incomingCallVC.modalPresentationStyle = .fullScreen + + // Get the top view controller to present from + if let topVC = UIApplication.shared.keyWindow?.rootViewController { + topVC.present(incomingCallVC, animated: true) + } + } +} +``` + + + +### Handle Call Accept and Navigate to Ongoing Call + +Transition from incoming call to ongoing call when accepted: + + + +```swift +let incomingCall = CometChatIncomingCall() +incomingCall.set(call: call) +incomingCall.set(onAcceptClick: { [weak self] acceptedCall, controller in + // Dismiss incoming call screen + controller.dismiss(animated: false) { + // Present ongoing call screen + let ongoingCall = CometChatOngoingCall() + ongoingCall.set(sessionId: acceptedCall.sessionId ?? "") + ongoingCall.modalPresentationStyle = .fullScreen + self?.present(ongoingCall, animated: true) + } +}) +``` + + + +### Custom Ringtone for Incoming Calls + +Set a custom sound for incoming calls: + + + +```swift +let incomingCall = CometChatIncomingCall() +incomingCall.set(call: call) + +// Use custom ringtone +if let soundURL = Bundle.main.url(forResource: "custom_ringtone", withExtension: "mp3") { + incomingCall.set(customSoundForCalls: soundURL) +} +``` + + + +--- + ## Related Components -- [Outgoing Call](/ui-kit/ios/outgoing-call) - Display outgoing call interface -- [Ongoing Call](/ui-kit/ios/ongoing-call) - Display active call interface -- [Call Logs](/ui-kit/ios/call-logs) - Display call history + + + Display outgoing call interface + + + Display active call interface + + + Display call history + + diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index 2f685bb84..527a0ed29 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -1049,6 +1049,65 @@ The MessageComposer component does not emit any global UI events. --- +## Common Patterns + +### Hide attachment options + +```swift +let messageComposer = CometChatMessageComposer() +messageComposer.set(user: user) +messageComposer.hideImageAttachmentOption = true +messageComposer.hideVideoAttachmentOption = true +messageComposer.hideAudioAttachmentOption = true +messageComposer.hideFileAttachmentOption = true +``` + +### Hide all auxiliary buttons + +```swift +let messageComposer = CometChatMessageComposer() +messageComposer.set(user: user) +messageComposer.hideAttachmentButton = true +messageComposer.hideVoiceRecordingButton = true +messageComposer.hideStickersButton = true +``` + +### Disable typing indicators + +```swift +let messageComposer = CometChatMessageComposer() +messageComposer.set(user: user) +messageComposer.disableTypingEvents = true +``` + +### Disable mentions + +```swift +let messageComposer = CometChatMessageComposer() +messageComposer.set(user: user) +messageComposer.disableMentions = true +``` + +### Custom send button action + +```swift +let messageComposer = CometChatMessageComposer() +messageComposer.set(user: user) + +messageComposer.set(onSendButtonClick: { message in + // Custom send logic + print("Sending message: \(message)") +}) +``` + +### Disable message sounds + +```swift +let messageComposer = CometChatMessageComposer() +messageComposer.set(user: user) +messageComposer.disableSoundForMessages = true +``` + --- ## Related Components diff --git a/ui-kit/ios/message-header.mdx b/ui-kit/ios/message-header.mdx index 3c50b0a72..507785eb4 100644 --- a/ui-kit/ios/message-header.mdx +++ b/ui-kit/ios/message-header.mdx @@ -1106,6 +1106,59 @@ messageHeader.dateTimeFormatter.otherDay = { timestamp in --- +## Common Patterns + +### Hide call buttons + +```swift +let messageHeader = CometChatMessageHeader() +messageHeader.set(user: user) +messageHeader.hideVideoCallButton = true +messageHeader.hideVoiceCallButton = true +``` + +### Custom back button action + +```swift +let messageHeader = CometChatMessageHeader() +messageHeader.set(user: user) + +messageHeader.set(onBack: { [weak self] in + // Custom navigation logic + self?.dismiss(animated: true) +}) +``` + +### Custom subtitle with typing indicator + +```swift +let messageHeader = CometChatMessageHeader() +messageHeader.set(user: user) + +messageHeader.set(subtitleView: { user, group in + let label = UILabel() + label.font = UIFont.systemFont(ofSize: 12) + + if let user = user { + label.text = user.status == .online ? "Online" : "Offline" + label.textColor = user.status == .online ? .systemGreen : .secondaryLabel + } + + return label +}) +``` + +### Minimal header + +```swift +let messageHeader = CometChatMessageHeader() +messageHeader.set(user: user) +messageHeader.hideBackButton = true +messageHeader.hideUserStatus = true +messageHeader.hideVideoCallButton = true +messageHeader.hideVoiceCallButton = true +``` + --- ## Related Components diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index aad1240ce..fda8726de 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -1967,6 +1967,63 @@ messageList.set(dateSeparatorPattern: { timestamp in --- +## Common Patterns + +### Hide message options + +```swift +let messageList = CometChatMessageList() +messageList.set(user: user) +messageList.hideReplyInThreadOption = true +messageList.hideEditMessageOption = true +messageList.hideDeleteMessageOption = true +messageList.hideReactionOption = true +messageList.hideCopyMessageOption = true +``` + +### Disable sounds + +```swift +let messageList = CometChatMessageList() +messageList.set(user: user) +messageList.disableSoundForMessages = true +``` + +### Custom empty state + +```swift +let messageList = CometChatMessageList() +messageList.set(user: user) + +messageList.set(emptyStateView: { + let label = UILabel() + label.text = "Start a conversation!" + label.textAlignment = .center + label.textColor = .secondaryLabel + return label +}) +``` + +### Scroll to bottom on new messages + +```swift +let messageList = CometChatMessageList() +messageList.set(user: user) +messageList.scrollToBottomOnNewMessages = true +``` + +### Hide UI elements + +```swift +let messageList = CometChatMessageList() +messageList.set(user: user) +messageList.hideAvatar = true +messageList.hideReceipts = true +messageList.hideDateSeparator = true +messageList.hideHeaderView = true +messageList.hideFooterView = true +``` + --- ## Related Components diff --git a/ui-kit/ios/ongoing-call.mdx b/ui-kit/ios/ongoing-call.mdx index 177eabb95..749f4aa80 100644 --- a/ui-kit/ios/ongoing-call.mdx +++ b/ui-kit/ios/ongoing-call.mdx @@ -248,3 +248,102 @@ For advanced-level customization, you can set custom views to the component. Thi The `OngoingCall` component does not provide additional functionalities beyond this level of customization. --- + +## Common Patterns + +### Present Ongoing Call After Acceptance + +Show the ongoing call screen after a call is accepted: + + + +```swift +func presentOngoingCall(sessionId: String) { + let ongoingCall = CometChatOngoingCall() + ongoingCall.set(sessionId: sessionId) + ongoingCall.modalPresentationStyle = .fullScreen + + self.present(ongoingCall, animated: true) +} +``` + + + +### Configure Call Settings for Video Call + +Customize video call settings before starting: + + + +```swift +let callSettingsBuilder = CallSettingsBuilder() + .setIsAudioOnly(false) + .setDefaultAudioMode("SPEAKER") + .setShowSwitchToVideoCall(false) + .setShowRecordingButton(true) + .setStartVideoMuted(false) + .setStartAudioMuted(false) + +let ongoingCall = CometChatOngoingCall() +ongoingCall.set(sessionId: sessionId) +ongoingCall.set(callSettingsBuilder: callSettingsBuilder) +``` + + + +### Audio-Only Call Configuration + +Set up an audio-only call with speaker mode: + + + +```swift +let audioCallSettings = CallSettingsBuilder() + .setIsAudioOnly(true) + .setDefaultAudioMode("SPEAKER") + .setMuteAudioButtonDisable(false) + .setEndCallButtonDisable(false) + +let ongoingCall = CometChatOngoingCall() +ongoingCall.set(sessionId: sessionId) +ongoingCall.set(callSettingsBuilder: audioCallSettings) +ongoingCall.modalPresentationStyle = .fullScreen +self.present(ongoingCall, animated: true) +``` + + + +### Listen for Call End Events + +Use CometChatCallEvents to handle call end: + + + +```swift +// Subscribe to call events +CometChatCallEvents.addListener("ongoing_call_listener", self as CometChatCallEventListener) + +// In CometChatCallEventListener extension +func onCallEnded(call: Call) { + DispatchQueue.main.async { [weak self] in + self?.dismiss(animated: true) { + // Show call summary + let duration = call.duration ?? 0 + let minutes = duration / 60 + let seconds = duration % 60 + + let alert = UIAlertController( + title: "Call Ended", + message: "Duration: \(minutes)m \(seconds)s", + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "OK", style: .default)) + self?.present(alert, animated: true) + } + } +} +``` + + + +--- diff --git a/ui-kit/ios/outgoing-call.mdx b/ui-kit/ios/outgoing-call.mdx index eff504924..33016421e 100644 --- a/ui-kit/ios/outgoing-call.mdx +++ b/ui-kit/ios/outgoing-call.mdx @@ -691,8 +691,99 @@ cometChatOutgoingCall.set(trailingView: { call in --- +## Common Patterns + +### Initiate Call and Present Outgoing Screen + +Start a call and show the outgoing call interface: + + + +```swift +func initiateCall(to user: User, callType: CometChat.CallType) { + let call = Call(receiverId: user.uid ?? "", callType: callType, receiverType: .user) + + CometChat.initiateCall(call: call) { [weak self] initiatedCall in + DispatchQueue.main.async { + let outgoingCall = CometChatOutgoingCall() + outgoingCall.set(call: initiatedCall) + outgoingCall.modalPresentationStyle = .fullScreen + self?.present(outgoingCall, animated: true) + } + } onError: { error in + print("Call initiation failed: \(error?.errorDescription ?? "")") + } +} +``` + + + +### Handle Call Acceptance and Transition to Ongoing Call + +Navigate to ongoing call when the recipient accepts: + + + +```swift +// Subscribe to call events +CometChatCallEvents.addListener("outgoing_call_listener", self as CometChatCallEventListener) + +// In CometChatCallEventListener extension +func onOutgoingCallAccepted(call: Call) { + DispatchQueue.main.async { [weak self] in + self?.dismiss(animated: false) { + let ongoingCall = CometChatOngoingCall() + ongoingCall.set(sessionId: call.sessionId ?? "") + ongoingCall.modalPresentationStyle = .fullScreen + self?.present(ongoingCall, animated: true) + } + } +} +``` + + + +### Custom Cancel Action with Confirmation + +Show confirmation before canceling an outgoing call: + + + +```swift +let outgoingCall = CometChatOutgoingCall() +outgoingCall.set(call: call) +outgoingCall.set(onCancelClick: { [weak self] call, controller in + let alert = UIAlertController( + title: "Cancel Call", + message: "Are you sure you want to cancel this call?", + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: "No", style: .cancel)) + alert.addAction(UIAlertAction(title: "Yes", style: .destructive) { _ in + CometChat.rejectCall(sessionID: call.sessionId ?? "", status: .cancelled) { _ in + controller.dismiss(animated: true) + } onError: { error in + print("Failed to cancel: \(error?.errorDescription ?? "")") + } + }) + controller.present(alert, animated: true) +}) +``` + + + +--- + ## Related Components -- [Incoming Call](/ui-kit/ios/incoming-call) - Display incoming call interface -- [Ongoing Call](/ui-kit/ios/ongoing-call) - Display active call interface -- [Call Logs](/ui-kit/ios/call-logs) - Display call history + + + Display incoming call interface + + + Display active call interface + + + Display call history + + diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index dc9532c6d..900a1a787 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -746,3 +746,132 @@ The `setTextFormatters` method enables developers to define and apply text forma By utilizing this method, developers can enhance readability, usability, and compliance with content guidelines. See the [MentionsFormatter Guide](/ui-kit/ios/mentions-formatter-guide) for more details. --- + +## Common Patterns + +### Present Search from Conversations + +Open the search screen from a conversations list: + + + +```swift +@objc func openSearch() { + let searchVC = CometChatSearch() + + searchVC.onConversationClicked = { [weak self] conversation in + // Navigate to messages for the selected conversation + let messagesVC = CometChatMessages() + if let user = conversation.conversationWith as? User { + messagesVC.user = user + } else if let group = conversation.conversationWith as? Group { + messagesVC.group = group + } + self?.navigationController?.pushViewController(messagesVC, animated: true) + } + + searchVC.onMessageClicked = { [weak self] message in + // Navigate to the message in context + let messagesVC = CometChatMessages() + if let user = message.sender { + messagesVC.user = user + } + self?.navigationController?.pushViewController(messagesVC, animated: true) + } + + navigationController?.pushViewController(searchVC, animated: true) +} +``` + + + +### Search Within a Specific Conversation + +Limit search to messages within a specific user or group chat: + + + +```swift +// Search within a specific user's conversation +let searchVC = CometChatSearch() +searchVC.user = user +searchVC.set(searchIn: [.messages]) // Only search messages, not conversations + +// Or search within a group +let groupSearchVC = CometChatSearch() +groupSearchVC.group = group +groupSearchVC.set(searchIn: [.messages]) +``` + + + +### Filter Search by Media Type + +Show only photo or video messages in search results: + + + +```swift +let searchVC = CometChatSearch() + +// Set available filters with photos as the initial selection +searchVC.set(searchFilters: [.photos, .videos, .documents, .audio], initialFilter: .photos) + +// Or programmatically filter messages +let msgBuilder = MessagesRequest.MessageRequestBuilder() + .set(categories: ["message"]) + .set(types: ["image", "video"]) + +searchVC.set(messagesRequestBuilder: msgBuilder) +``` + + + +### Custom Search Result Actions + +Handle search result selection with custom actions: + + + +```swift +let searchVC = CometChatSearch() + +searchVC.onMessageClicked = { [weak self] message in + // Show action sheet for the selected message + let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) + + alert.addAction(UIAlertAction(title: "Go to Message", style: .default) { _ in + self?.navigateToMessage(message) + }) + + alert.addAction(UIAlertAction(title: "Reply", style: .default) { _ in + self?.replyToMessage(message) + }) + + alert.addAction(UIAlertAction(title: "Forward", style: .default) { _ in + self?.forwardMessage(message) + }) + + alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + + self?.present(alert, animated: true) +} +``` + + + +--- + +## Related Components + + + + Display conversation list + + + Display chat messages + + + Display user list + + diff --git a/ui-kit/ios/threaded-messages-header.mdx b/ui-kit/ios/threaded-messages-header.mdx index 54bdebdd3..58596d3ad 100644 --- a/ui-kit/ios/threaded-messages-header.mdx +++ b/ui-kit/ios/threaded-messages-header.mdx @@ -319,6 +319,70 @@ class MyCustomTextFormatter: CometChatTextFormatter { --- +## Common Patterns + +### Open Thread from Message List + +Present the threaded messages view when a user taps on a message's reply count: + + + +```swift +// In your message list delegate or action handler +func openThread(for parentMessage: BaseMessage) { + let threadedMessages = CometChatThreadedMessages() + threadedMessages.set(parentMessage: parentMessage) + threadedMessages.set(controller: self) + + self.navigationController?.pushViewController(threadedMessages, animated: true) +} +``` + + + +### Customize Thread Header with Parent Message Info + +Display additional context about the parent message in the thread header: + + + +```swift +let threadedHeader = CometChatThreadedMessageHeader() +threadedHeader.set(parentMessage: parentMessage) + +// Custom date formatting +threadedHeader.set(datePattern: { timestamp in + guard let timestamp = timestamp else { return "" } + let date = Date(timeIntervalSince1970: TimeInterval(timestamp / 1000)) + let formatter = DateFormatter() + formatter.dateFormat = "MMM d 'at' h:mm a" + return formatter.string(from: date) +}) +``` + + + +### Filter Thread Replies + +Show only specific types of messages in the thread: + + + +```swift +// Filter to show only text messages in thread +let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() + .set(parentMessageId: parentMessage.id) + .set(types: ["text"]) + .set(limit: 30) + +let messageList = CometChatMessageList() +messageList.set(messagesRequestBuilder: messageRequestBuilder) +``` + + + +--- + To ensure that the `ThreadedMessages` is properly configured, passing the controller is mandatory. diff --git a/ui-kit/ios/users.mdx b/ui-kit/ios/users.mdx index 9a38a27c6..51cfb5b66 100644 --- a/ui-kit/ios/users.mdx +++ b/ui-kit/ios/users.mdx @@ -1350,6 +1350,70 @@ Custom request builder for filtering users. --- +## Common Patterns + +### Friends-only list + +```swift +let friendsBuilder = UsersRequest.UsersRequestBuilder(limit: 30) + .friendsOnly(true) + +let users = CometChatUsers() +users.set(usersRequestBuilder: friendsBuilder) +``` + +### Online users only + +```swift +let onlineBuilder = UsersRequest.UsersRequestBuilder(limit: 30) + .set(status: .online) + +let users = CometChatUsers() +users.set(usersRequestBuilder: onlineBuilder) +``` + +### Custom empty state with CTA + +```swift +let users = CometChatUsers() + +users.set(emptyStateView: { + let emptyView = UIView() + + let label = UILabel() + label.text = "No users found" + label.textAlignment = .center + label.textColor = .secondaryLabel + + let button = UIButton(type: .system) + button.setTitle("Invite friends", for: .normal) + + // Add subviews and constraints... + return emptyView +}) +``` + +### Hide all chrome — minimal list + +```swift +let users = CometChatUsers() +users.hideSearch = true +users.hideUserStatus = true +users.hideSectionHeader = true +``` + +### Multi-select users + +```swift +let users = CometChatUsers() +users.selectionMode = .multiple + +users.set(onSelection: { selectedUsers in + print("Selected \(selectedUsers.count) users") + // Create group with selected users, etc. +}) +``` + --- ## Related Components From acdcc6a5fec56ad7e9ddace1d6286775f14f11de Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 15:25:09 +0530 Subject: [PATCH 068/106] references --- ui-kit/ios/events.mdx | 51 +++++++++++++++++-------- ui-kit/ios/methods.mdx | 22 ++++++++++- ui-kit/ios/shortcut-formatter-guide.mdx | 19 +++++++++ 3 files changed, 75 insertions(+), 17 deletions(-) diff --git a/ui-kit/ios/events.mdx b/ui-kit/ios/events.mdx index cdbcf7ad8..e28e3ca03 100644 --- a/ui-kit/ios/events.mdx +++ b/ui-kit/ios/events.mdx @@ -17,8 +17,8 @@ description: "Listen and respond to user actions and state changes in CometChat "listenerClass": "CometChatUserEvents", "protocol": "CometChatUserEventListener", "events": [ - {"name": "onUserBlock", "payload": "User", "description": "User was blocked"}, - {"name": "onUserUnblock", "payload": "User", "description": "User was unblocked"} + {"name": "ccUserBlocked", "payload": "User", "description": "User was blocked"}, + {"name": "ccUserUnblocked", "payload": "User", "description": "User was unblocked"} ] }, { @@ -26,13 +26,13 @@ description: "Listen and respond to user actions and state changes in CometChat "listenerClass": "CometChatGroupEvents", "protocol": "CometChatGroupEventListener", "events": [ - {"name": "onGroupCreate", "payload": "Group", "description": "New group created"}, - {"name": "onGroupDelete", "payload": "Group", "description": "Group deleted"}, - {"name": "onGroupMemberJoin", "payload": "(User, Group)", "description": "User joined group"}, - {"name": "onGroupMemberLeave", "payload": "(User, Group)", "description": "User left group"}, - {"name": "onGroupMemberKick", "payload": "(User, Group)", "description": "Member kicked"}, - {"name": "onGroupMemberBan", "payload": "(User, Group)", "description": "Member banned"}, - {"name": "onOwnershipChange", "payload": "(Group, GroupMember)", "description": "Ownership transferred"} + {"name": "ccGroupCreated", "payload": "Group", "description": "New group created"}, + {"name": "ccGroupDeleted", "payload": "Group", "description": "Group deleted"}, + {"name": "ccGroupMemberJoined", "payload": "(User, Group)", "description": "User joined group"}, + {"name": "ccGroupLeft", "payload": "(ActionMessage, User, Group)", "description": "User left group"}, + {"name": "ccGroupMemberKicked", "payload": "(ActionMessage, User, User, Group)", "description": "Member kicked"}, + {"name": "ccGroupMemberBanned", "payload": "(ActionMessage, User, User, Group)", "description": "Member banned"}, + {"name": "ccOwnershipChanged", "payload": "(Group, GroupMember)", "description": "Ownership transferred"} ] }, { @@ -137,12 +137,12 @@ class UserEventsViewController: UIViewController { extension UserEventsViewController: CometChatUserEventListener { - func onUserBlock(user: User) { + func ccUserBlocked(user: User) { print("Blocked: \(user.name ?? "")") // Update UI - hide user from lists, disable messaging } - func onUserUnblock(user: User) { + func ccUserUnblocked(user: User) { print("Unblocked: \(user.name ?? "")") // Update UI - show user in lists, enable messaging } @@ -155,18 +155,18 @@ Notify other components when you block/unblock a user: ```swift // After blocking a user -CometChatUserEvents.emitOnUserBlock(user: blockedUser) +CometChatUserEvents.ccUserBlocked(user: blockedUser) // After unblocking a user -CometChatUserEvents.emitOnUserUnblock(user: unblockedUser) +CometChatUserEvents.ccUserUnblocked(user: unblockedUser) ``` ### User Events Reference | Event | Description | |-------|-------------| -| `onUserBlock` | User was blocked by logged-in user | -| `onUserUnblock` | User was unblocked by logged-in user | +| `ccUserBlocked` | User was blocked by logged-in user | +| `ccUserUnblocked` | User was unblocked by logged-in user | ## Group Events @@ -775,3 +775,24 @@ class MyViewController: UIViewController { 4. **Don't emit unnecessarily** - Only emit events when state actually changes 5. **Use a central manager** - For app-wide event handling, create a singleton manager + +--- + +## Next Steps + + + + Reference for UI Kit wrapper methods. + + + Display and customize chat messages. + + + Manage conversation lists. + + + Work with group chat functionality. + + + +--- diff --git a/ui-kit/ios/methods.mdx b/ui-kit/ios/methods.mdx index adf0384c3..003625c2c 100644 --- a/ui-kit/ios/methods.mdx +++ b/ui-kit/ios/methods.mdx @@ -1,5 +1,6 @@ --- title: "Methods" +description: "Reference for CometChat iOS UI Kit methods including init, login, logout, and message-sending wrappers." --- @@ -44,8 +45,6 @@ title: "Methods" ``` ---- - ## Overview The UI Kit's core function is to extend the [CometChat SDK](/sdk/ios/overview), translating raw data and functionality into visually appealing, easy-to-use UI components. @@ -363,3 +362,22 @@ CometChatUIKit.sendSchedulerMessage(schedulerMessage: schedulerMessage) { schedu --- + +## Next Steps + + + + Listen and respond to UI Kit events. + + + Set up CometChat iOS UI Kit. + + + Display and customize chat messages. + + + Manage conversation lists. + + + +--- diff --git a/ui-kit/ios/shortcut-formatter-guide.mdx b/ui-kit/ios/shortcut-formatter-guide.mdx index 9c6fb844e..064e3616e 100644 --- a/ui-kit/ios/shortcut-formatter-guide.mdx +++ b/ui-kit/ios/shortcut-formatter-guide.mdx @@ -282,3 +282,22 @@ Ensure to pass and present `cometChatConversationsWithMessages`. If a navigation --- + +## Next Steps + + + + Add @mentions with styled tokens and click handling. + + + Customize the message input component. + + + Display and customize chat messages. + + + Define custom message bubble structures. + + + +--- From 3591eba84ccc50314b0b2a0ecf13676989f90770 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 15:39:02 +0530 Subject: [PATCH 069/106] updates docs --- ui-kit/ios/getting-started.mdx | 17 +++++++++++++++-- ui-kit/ios/ios-conversation.mdx | 11 +++++++++-- ui-kit/ios/ios-one-to-one-chat.mdx | 9 ++++++++- ui-kit/ios/ios-tab-based-chat.mdx | 15 +++++++++++++-- 4 files changed, 45 insertions(+), 7 deletions(-) diff --git a/ui-kit/ios/getting-started.mdx b/ui-kit/ios/getting-started.mdx index 919538ace..bd4544b07 100644 --- a/ui-kit/ios/getting-started.mdx +++ b/ui-kit/ios/getting-started.mdx @@ -91,8 +91,10 @@ end pod install ``` +4. Close the `.xcodeproj` file and open the `.xcworkspace` file instead. CocoaPods creates a workspace that includes your project and the installed pods. + -If you hit issues, run `pod install --repo-update`. Always open the `.xcworkspace` file after installing pods. +If you hit issues, run `pod install --repo-update`. Always open the `.xcworkspace` file after installing pods — opening the `.xcodeproj` will cause build errors. @@ -145,7 +147,13 @@ Add these keys to your `Info.plist` for media messaging: -Also disable **User Script Sandboxing** in Build Settings to ensure WebView can load scripts for collaborative tools. +Also disable **User Script Sandboxing** in Build Settings to ensure WebView can load scripts for collaborative tools: + +1. Select your project in the Navigator +2. Select your app target +3. Go to **Build Settings** tab +4. Search for "User Script Sandboxing" +5. Set it to **No** @@ -160,6 +168,7 @@ Add this to your `SceneDelegate.swift`. Init must complete before login, and log ```swift title="SceneDelegate.swift" import UIKit import CometChatUIKitSwift +import CometChatSDK class SceneDelegate: UIResponder, UIWindowSceneDelegate { @@ -238,6 +247,10 @@ After running the app, you should see: For production, use [`loginWithAuthToken()`](/ui-kit/ios/methods#login-using-auth-token) instead of Auth Key. Generate tokens server-side via the REST API. + +Having issues? Check the [Troubleshooting Guide](/ui-kit/ios/troubleshooting) for common problems and solutions. + + --- ## Step 5 — Choose a Chat Experience diff --git a/ui-kit/ios/ios-conversation.mdx b/ui-kit/ios/ios-conversation.mdx index cb98e06be..dcad85109 100644 --- a/ui-kit/ios/ios-conversation.mdx +++ b/ui-kit/ios/ios-conversation.mdx @@ -95,7 +95,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { conversationsVC.set(onItemClick: { [weak navController] conversation, _ in let messagesVC = MessagesVC() messagesVC.group = conversation.conversationWith as? Group - messagesVC.user = conversation.conversationWith as? CometChatSDK.User + messagesVC.user = conversation.conversationWith as? User navController?.pushViewController(messagesVC, animated: true) }) @@ -115,7 +115,14 @@ Key points: ## Step 2 — Create MessagesVC -Create a new file `MessagesVC.swift`. This view controller assembles the header, message list, and composer. +Create a new Swift file for the messages view controller: + +1. In Xcode, right-click your project folder in the Navigator +2. Select **New File...** +3. Choose **Swift File** and click Next +4. Name it `MessagesVC.swift` and click Create + +Add the following code. This view controller assembles the header, message list, and composer. ```swift title="MessagesVC.swift" lines import UIKit diff --git a/ui-kit/ios/ios-one-to-one-chat.mdx b/ui-kit/ios/ios-one-to-one-chat.mdx index 7cdc680f2..2cdb40fc4 100644 --- a/ui-kit/ios/ios-one-to-one-chat.mdx +++ b/ui-kit/ios/ios-one-to-one-chat.mdx @@ -141,7 +141,14 @@ func setUpGroupConversation(windowScene: UIWindowScene, guid: String) { ## Step 2 — Create MessagesVC -Create a new file `MessagesVC.swift`. This view controller assembles the header, message list, and composer. +Create a new Swift file for the messages view controller: + +1. In Xcode, right-click your project folder in the Navigator +2. Select **New File...** +3. Choose **Swift File** and click Next +4. Name it `MessagesVC.swift` and click Create + +Add the following code. This view controller assembles the header, message list, and composer. ```swift title="MessagesVC.swift" lines import UIKit diff --git a/ui-kit/ios/ios-tab-based-chat.mdx b/ui-kit/ios/ios-tab-based-chat.mdx index a596f5168..ca617c55e 100644 --- a/ui-kit/ios/ios-tab-based-chat.mdx +++ b/ui-kit/ios/ios-tab-based-chat.mdx @@ -43,6 +43,10 @@ Four tabs working together: Initialize CometChat and launch the tabbed view after login. ```swift title="SceneDelegate.swift" highlight={5-7} lines +import UIKit +import CometChatUIKitSwift +import CometChatSDK + func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let windowScene = (scene as? UIWindowScene) else { return } @@ -96,7 +100,7 @@ func setupTabbedView(windowScene: UIWindowScene) { conversationsVC.set(onItemClick: { [weak conversationsNav] conversation, indexPath in let messagesVC = MessagesVC() messagesVC.group = conversation.conversationWith as? Group - messagesVC.user = conversation.conversationWith as? CometChatSDK.User + messagesVC.user = conversation.conversationWith as? User messagesVC.hidesBottomBarWhenPushed = true conversationsNav?.pushViewController(messagesVC, animated: true) }) @@ -153,7 +157,14 @@ Key points: ## Step 3 — Create MessagesVC -Create a new file `MessagesVC.swift`. This view controller assembles the header, message list, and composer. +Create a new Swift file for the messages view controller: + +1. In Xcode, right-click your project folder in the Navigator +2. Select **New File...** +3. Choose **Swift File** and click Next +4. Name it `MessagesVC.swift` and click Create + +Add the following code. This view controller assembles the header, message list, and composer. ```swift title="MessagesVC.swift" lines import UIKit From 053705c5c2da44457fbbdb1886f15621cfa05499 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 15:52:11 +0530 Subject: [PATCH 070/106] pod installation --- ui-kit/ios/getting-started.mdx | 10 ++++----- ui-kit/ios/troubleshooting.mdx | 39 ++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/ui-kit/ios/getting-started.mdx b/ui-kit/ios/getting-started.mdx index bd4544b07..1d938dc54 100644 --- a/ui-kit/ios/getting-started.mdx +++ b/ui-kit/ios/getting-started.mdx @@ -9,7 +9,7 @@ description: "Add CometChat to an iOS app in 5 steps: create project, install, i | Field | Value | | --- | --- | | Package | `CometChatUIKitSwift` | -| Version | `5.1.7` | +| Version | `5.1.9` | | Requirements | Xcode 16+, iOS 13.0+, Swift 5.0+ | | Init | `CometChatUIKit.init(uiKitSettings:)` — must complete before `login()` | | Login | `CometChatUIKit.login(uid:)` — must complete before rendering components | @@ -78,7 +78,7 @@ platform :ios, '13.0' use_frameworks! target 'YourApp' do - pod 'CometChatUIKitSwift', '5.1.7' + pod 'CometChatUIKitSwift', '5.1.9' # Optional: Voice/Video Calling pod 'CometChatCallsSDK', '4.2.2' @@ -88,13 +88,13 @@ end 3. Install dependencies: ```bash -pod install +pod install --repo-update ``` 4. Close the `.xcodeproj` file and open the `.xcworkspace` file instead. CocoaPods creates a workspace that includes your project and the installed pods. -If you hit issues, run `pod install --repo-update`. Always open the `.xcworkspace` file after installing pods — opening the `.xcodeproj` will cause build errors. +Always open the `.xcworkspace` file after installing pods — opening the `.xcodeproj` will cause build errors. Having issues? See [CocoaPods Troubleshooting](/ui-kit/ios/troubleshooting#cocoapods-issues). @@ -110,7 +110,7 @@ https://github.com/cometchat/cometchat-uikit-ios 3. Select **Up to Exact Version** and enter: ``` -5.1.7 +5.1.9 ``` 4. Add the Chat SDK separately using: diff --git a/ui-kit/ios/troubleshooting.mdx b/ui-kit/ios/troubleshooting.mdx index e22678d56..c894a5753 100644 --- a/ui-kit/ios/troubleshooting.mdx +++ b/ui-kit/ios/troubleshooting.mdx @@ -20,6 +20,45 @@ This guide covers common issues and solutions when working with the CometChat iO --- +## CocoaPods Issues + +| Issue | Solution | +|-------|----------| +| "Could not find compatible versions" | Run `pod install --repo-update` to refresh spec repos | +| Pod version not found | Verify the version exists on [CocoaPods](https://cocoapods.org/pods/CometChatUIKitSwift) | +| Repo clone failures | Clean repos with commands below, then retry | +| Build errors after pod install | Open `.xcworkspace` file, not `.xcodeproj` | + +### Clean and Retry + +```bash +rm -rf Pods Podfile.lock +pod cache clean --all +pod install --repo-update +``` + +### Reset CocoaPods Completely + +If repo errors persist: + +```bash +rm -rf ~/.cocoapods/repos +pod setup +pod install --repo-update +``` + +### Fallback to Swift Package Manager + +If CocoaPods continues to fail, use SPM instead: + +1. Remove Podfile and Pods folder +2. Open your `.xcodeproj` in Xcode +3. Go to **File → Add Package Dependencies** +4. Add `https://github.com/cometchat/cometchat-uikit-ios` with version `5.1.9` +5. Add `https://github.com/cometchat/chat-sdk-ios` with version `4.1.0` + +--- + ## Initialization Issues | Issue | Solution | From 6f132e607fd6c9eb6dbe6c9b97f26a830e8e6abf Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 16:46:30 +0530 Subject: [PATCH 071/106] Update docs.json --- docs.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs.json b/docs.json index 539c65555..6f833b00f 100644 --- a/docs.json +++ b/docs.json @@ -1198,11 +1198,11 @@ "group": "Chat", "pages": [ "ui-kit/ios/core-features", - "ui-kit/ios/extensions" + "ui-kit/ios/extensions", + "ui-kit/ios/ai-features" ] }, - "ui-kit/ios/call-features", - "ui-kit/ios/ai-features" + "ui-kit/ios/call-features" ] }, { From c6054f24d077dbdd5632ba4870f5ed1002a84a10 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 18:15:13 +0530 Subject: [PATCH 072/106] bug fixes --- ui-kit/ios/message-composer.mdx | 12 ++++++------ ui-kit/ios/message-list.mdx | 7 ++++--- ui-kit/ios/upgrading-from-v4.mdx | 4 ++-- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index 527a0ed29..7145b1a2f 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -41,7 +41,7 @@ The `CometChatMessageComposer` component enables users to write and send message }, "callbacks": { "onSendButtonClick": "(BaseMessage) -> Void", - "onTextChanged": "(String) -> Void", + "onTextChangedListener": "(String) -> Void", "onError": "(CometChatException) -> Void" }, "visibility": { @@ -95,7 +95,7 @@ The `CometChatMessageComposer` component enables users to write and send message "compositionExample": { "description": "MessageComposer is typically used within CometChatMessages alongside MessageHeader and MessageList", "components": ["CometChatMessageHeader", "CometChatMessageList", "CometChatMessageComposer"], - "flow": "User types message → onTextChanged fires → User taps send → onSendButtonClick fires → Message sent" + "flow": "User types message → onTextChangedListener fires → User taps send → onSendButtonClick fires → Message sent" }, "types": { "CometChatMessageComposerAction": { @@ -141,7 +141,7 @@ class ChatViewController: UIViewController { }) // Handle text changes for typing indicators - messageComposer.set(onTextChanged: { [weak self] text in + messageComposer.set(onTextChangedListener: { [weak self] text in print("User is typing: \(text)") }) @@ -192,7 +192,7 @@ messageComposer.set(onSendButtonClick: { [weak self] message in }) ``` -#### onTextChanged +#### onTextChangedListener Fires when the user types in the composer. Use this for typing indicators or text validation. @@ -201,7 +201,7 @@ import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() -messageComposer.set(onTextChanged: { [weak self] text in +messageComposer.set(onTextChangedListener: { [weak self] text in guard let self = self else { return } print("Current text: \(text)") }) @@ -226,7 +226,7 @@ messageComposer.set(onError: { error in | Method | Description | Example | |--------|-------------|---------| | `set(onSendButtonClick:)` | Triggered when send button is clicked | Custom send handling | -| `set(onTextChanged:)` | Triggered when text changes | Typing indicators | +| `set(onTextChangedListener:)` | Triggered when text changes | Typing indicators | | `set(onError:)` | Triggered when an error occurs | Show error alert | | `set(user:)` | Sets the user for direct messaging | Configure recipient | | `set(group:)` | Sets the group for group messaging | Configure group | diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index fda8726de..303ffb02b 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -36,7 +36,7 @@ The `CometChatMessageList` component displays a scrollable list of messages in a }, "callbacks": { "onThreadRepliesClick": "(BaseMessage, MessageTemplate) -> Void", - "onReactionClick": "(ReactionCount, BaseMessage) -> Void", + "onReactionClick": "(ReactionCount, BaseMessage?) -> Void", "onReactionListItemClick": "(MessageReaction, BaseMessage) -> Void", "onError": "(CometChatException) -> Void", "onEmpty": "() -> Void", @@ -150,6 +150,7 @@ class ChatViewController: UIViewController { // Handle reactions messageList.set(onReactionClick: { [weak self] reactionCount, message in + guard let message = message else { return } self?.showReactionDetails(reactionCount, for: message) }) @@ -263,8 +264,8 @@ import CometChatSDK let messageList = CometChatMessageList() messageList.set(onReactionClick: { [weak self] reactionCount, message in - guard let self = self else { return } - print("Reaction \(reactionCount.reaction) tapped on message \(message.id)") + guard let self = self, let message = message else { return } + print("Reaction \(reactionCount.reaction ?? "") tapped on message \(message.id)") }) ``` diff --git a/ui-kit/ios/upgrading-from-v4.mdx b/ui-kit/ios/upgrading-from-v4.mdx index 2375d8b33..5bc92e1a8 100644 --- a/ui-kit/ios/upgrading-from-v4.mdx +++ b/ui-kit/ios/upgrading-from-v4.mdx @@ -399,7 +399,7 @@ In v5, the approach to properties has been refined: | hideLoadingView | Bool | Hides loading view | | hideNewMessageIndicator | Bool | Hides new message indicator | | set(onThreadRepliesClick:) | (BaseMessage, CometChatMessageTemplate) -> Void | Thread click callback | -| set(onReactionClick:) | (CometChat.ReactionCount, BaseMessage) -> Void | Reaction click callback | +| set(onReactionClick:) | (CometChat.ReactionCount, BaseMessage?) -> Void | Reaction click callback | | set(onError:) | (CometChatException) -> Void | Error callback | | set(onEmpty:) | () -> Void | Empty state callback | | set(onLoad:) | ([BaseMessage]) -> Void | Load callback | @@ -476,7 +476,7 @@ In v5, the approach to properties has been refined: | hideStickersButton | Bool | Hides stickers button | | hideSendButton | Bool | Hides send button | | set(onSendButtonClick:) | (BaseMessage) -> Void | Send button callback | -| set(onTextChanged:) | (String) -> Void | Text change callback | +| set(onTextChangedListener:) | (String) -> Void | Text change callback | | set(onError:) | (CometChatException) -> Void | Error callback | | set(attachmentOptions:) | (User?, Group?, UIViewController?) -> [CometChatMessageComposerAction] | Custom attachment options | | set(sendButtonView:) | (User?, Group?) -> UIView | Custom send button | From 20272185aaccda05178e1af0a69581e3b0e6f5c1 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 18:35:25 +0530 Subject: [PATCH 073/106] bug fixes --- ui-kit/ios/call-features.mdx | 4 +- ui-kit/ios/call-logs.mdx | 33 +++++++------ ui-kit/ios/core-features.mdx | 55 ++++++++++++++++++++-- ui-kit/ios/threaded-messages-header.mdx | 61 +++++++++++++++++++++---- 4 files changed, 125 insertions(+), 28 deletions(-) diff --git a/ui-kit/ios/call-features.mdx b/ui-kit/ios/call-features.mdx index 5d2200516..e46b0c29b 100644 --- a/ui-kit/ios/call-features.mdx +++ b/ui-kit/ios/call-features.mdx @@ -200,7 +200,7 @@ class MainTabBarController: UITabBarController { // Calls Tab - call history let callsVC = CometChatCallLogs() - callsVC.set(onItemClick: { [weak self] callLog, _ in + callsVC.set(onItemClick: { [weak self] callLog in self?.handleCallLogTap(callLog) }) let callsNav = UINavigationController(rootViewController: callsVC) @@ -615,7 +615,7 @@ Displays call history. See [Call Logs](/ui-kit/ios/call-logs) for full documenta ```swift let callLogs = CometChatCallLogs() -callLogs.set(onItemClick: { callLog, indexPath in }) +callLogs.set(onItemClick: { callLog in }) ``` --- diff --git a/ui-kit/ios/call-logs.mdx b/ui-kit/ios/call-logs.mdx index 43ee06650..8713d3c17 100644 --- a/ui-kit/ios/call-logs.mdx +++ b/ui-kit/ios/call-logs.mdx @@ -19,19 +19,20 @@ The `CometChatCallLogs` component shows the list of call logs available. By defa "inherits": "UIViewController", "primaryOutput": { "callback": "onItemClick", - "type": "(CallLog, IndexPath) -> Void" + "type": "(Any) -> Void", + "note": "CallLog is passed as Any type, cast to CometChatCallsSDK.CallLog" }, "props": { "data": { "callRequestBuilder": { "type": "CallLogsRequest.CallLogsBuilder?", "default": "nil" } }, "callbacks": { - "onItemClick": "(CallLog, IndexPath) -> Void", - "onItemLongClick": "(CallLog, IndexPath) -> Void", + "onItemClick": "(Any) -> Void", + "onItemLongClick": "(Any, IndexPath) -> Void", "onBack": "() -> Void", - "onError": "(CometChatCallException) -> Void", + "onError": "(Any) -> Void", "onEmpty": "() -> Void", - "onLoad": "([CallLog]) -> Void" + "onLoad": "([Any]) -> Void" }, "visibility": { "hideError": { "type": "Bool", "default": false }, @@ -40,10 +41,10 @@ The `CometChatCallLogs` component shows the list of call logs available. By defa "hideBackIcon": { "type": "Bool", "default": false } }, "viewSlots": { - "listItemView": "(CallLog) -> UIView", - "titleView": "(CallLog) -> UIView", - "leadingView": "(CallLog) -> UIView", - "trailView": "(CallLog) -> UIView" + "listItemView": "(Any) -> UIView", + "titleView": "(Any) -> UIView", + "leadingView": "(Any) -> UIView", + "trailView": "(Any) -> UIView" } }, "events": [], @@ -97,9 +98,12 @@ self.navigationController?.pushViewController(callLogs, animated: true) ```swift -// syntax for set(onItemClick: @escaping ((_ callLog: CometChatCallsSDK.CallLog, _ indexPath: IndexPath) -> Void)) -cometChatCallLogs.set(onItemClick: { callLogs, indexPath in +// syntax for set(onItemClick: ((_ callLog: Any) -> ())?) +// Note: callLog is of type CometChatCallsSDK.CallLog, cast it to access properties +cometChatCallLogs.set(onItemClick: { callLog in // Override on item click + guard let callLog = callLog as? CallLog else { return } + // Access callLog properties }) ``` @@ -116,9 +120,12 @@ cometChatCallLogs.set(onItemClick: { callLogs, indexPath in ```swift -// syntax for set(onItemLongClick: @escaping ((_ callLog: CometChatCallsSDK.CallLog, _ indexPath: IndexPath) -> Void)) +// syntax for set(onItemLongClick: ((_ callLog: Any, _ indexPath: IndexPath) -> ())?) +// Note: callLog is of type CometChatCallsSDK.CallLog, cast it to access properties cometChatCallLogs.set(onItemLongClick: { callLog, indexPath in - // Override on item click + // Override on item long click + guard let callLog = callLog as? CallLog else { return } + // Access callLog properties }) ``` diff --git a/ui-kit/ios/core-features.mdx b/ui-kit/ios/core-features.mdx index 9405a0790..d00343210 100644 --- a/ui-kit/ios/core-features.mdx +++ b/ui-kit/ios/core-features.mdx @@ -15,7 +15,7 @@ description: "Essential chat features built into CometChat UI Kit for iOS" {"name": "userPresence", "description": "Display online/offline status for users", "component": "CometChatConversations", "enabledByDefault": true}, {"name": "reactions", "description": "Let users react to messages with emojis", "component": "CometChatMessageList", "enabledByDefault": true}, {"name": "mentions", "description": "Tag users in messages with @mentions", "component": "CometChatMessageComposer", "enabledByDefault": true}, - {"name": "threadedConversations", "description": "Reply to specific messages in threads", "component": "CometChatThreadedMessages", "enabledByDefault": true}, + {"name": "threadedConversations", "description": "Reply to specific messages in threads", "component": "CometChatThreadedMessageHeader", "enabledByDefault": true}, {"name": "groupChat", "description": "Create and manage group conversations", "component": "CometChatGroups", "enabledByDefault": true}, {"name": "search", "description": "Search across conversations and messages", "component": "CometChatSearch", "enabledByDefault": true} ], @@ -475,11 +475,56 @@ class ThreadedMessagesViewController: UIViewController { } // Open thread view for a message + // Note: Thread replies are handled automatically by CometChatMessageList + // when user taps "Reply in thread". The thread view uses CometChatThreadedMessageHeader + // combined with CometChatMessageList and CometChatMessageComposer. func openThread(for parentMessage: BaseMessage, user: User) { - let threadedMessages = CometChatThreadedMessages() - threadedMessages.set(parentMessage: parentMessage) - threadedMessages.set(user: user) - navigationController?.pushViewController(threadedMessages, animated: true) + // Create a view controller to host the threaded messages + let threadVC = UIViewController() + threadVC.view.backgroundColor = .systemBackground + + // Create threaded message header + let threadedHeader = CometChatThreadedMessageHeader() + threadedHeader.set(parentMessage: parentMessage) + threadedHeader.set(controller: threadVC) + threadedHeader.translatesAutoresizingMaskIntoConstraints = false + + // Create message list for thread replies + let messageList = CometChatMessageList() + messageList.set(user: user) + messageList.set(parentMessage: parentMessage) + messageList.set(controller: threadVC) + messageList.translatesAutoresizingMaskIntoConstraints = false + + // Create composer for thread replies + let composer = CometChatMessageComposer() + composer.set(user: user) + composer.set(parentMessage: parentMessage) + composer.set(controller: threadVC) + composer.translatesAutoresizingMaskIntoConstraints = false + + // Add to view + threadVC.view.addSubview(threadedHeader) + threadVC.view.addSubview(messageList) + threadVC.view.addSubview(composer) + + // Layout constraints + NSLayoutConstraint.activate([ + threadedHeader.topAnchor.constraint(equalTo: threadVC.view.safeAreaLayoutGuide.topAnchor), + threadedHeader.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor), + threadedHeader.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor), + + messageList.topAnchor.constraint(equalTo: threadedHeader.bottomAnchor), + messageList.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor), + messageList.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor), + messageList.bottomAnchor.constraint(equalTo: composer.topAnchor), + + composer.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor), + composer.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor), + composer.bottomAnchor.constraint(equalTo: threadVC.view.safeAreaLayoutGuide.bottomAnchor) + ]) + + navigationController?.pushViewController(threadVC, animated: true) } // Send reply in thread programmatically diff --git a/ui-kit/ios/threaded-messages-header.mdx b/ui-kit/ios/threaded-messages-header.mdx index 58596d3ad..6b6619bf8 100644 --- a/ui-kit/ios/threaded-messages-header.mdx +++ b/ui-kit/ios/threaded-messages-header.mdx @@ -116,7 +116,7 @@ To fit your app's design requirements, you can customize the appearance of the c ### Style -`ThreadedMessagesStyle` contains various properties which can be used to customize the UI of `CometChatThreadedMessages`. +`ThreadedMessageHeaderStyle` contains various properties which can be used to customize the UI of `CometChatThreadedMessageHeader`. **Global Level Styling** @@ -330,11 +330,56 @@ Present the threaded messages view when a user taps on a message's reply count: ```swift // In your message list delegate or action handler func openThread(for parentMessage: BaseMessage) { - let threadedMessages = CometChatThreadedMessages() - threadedMessages.set(parentMessage: parentMessage) - threadedMessages.set(controller: self) + // Create a view controller to host the threaded messages + let threadVC = UIViewController() + threadVC.view.backgroundColor = .systemBackground - self.navigationController?.pushViewController(threadedMessages, animated: true) + // Create threaded message header + let threadedHeader = CometChatThreadedMessageHeader() + threadedHeader.set(parentMessage: parentMessage) + threadedHeader.set(controller: threadVC) + threadedHeader.translatesAutoresizingMaskIntoConstraints = false + + // Create message list for thread replies + let messageList = CometChatMessageList() + if let user = parentMessage.sender { + messageList.set(user: user) + } + messageList.set(parentMessage: parentMessage) + messageList.set(controller: threadVC) + messageList.translatesAutoresizingMaskIntoConstraints = false + + // Create composer for thread replies + let composer = CometChatMessageComposer() + if let user = parentMessage.sender { + composer.set(user: user) + } + composer.set(parentMessage: parentMessage) + composer.set(controller: threadVC) + composer.translatesAutoresizingMaskIntoConstraints = false + + // Add to view + threadVC.view.addSubview(threadedHeader) + threadVC.view.addSubview(messageList) + threadVC.view.addSubview(composer) + + // Layout constraints + NSLayoutConstraint.activate([ + threadedHeader.topAnchor.constraint(equalTo: threadVC.view.safeAreaLayoutGuide.topAnchor), + threadedHeader.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor), + threadedHeader.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor), + + messageList.topAnchor.constraint(equalTo: threadedHeader.bottomAnchor), + messageList.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor), + messageList.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor), + messageList.bottomAnchor.constraint(equalTo: composer.topAnchor), + + composer.leadingAnchor.constraint(equalTo: threadVC.view.leadingAnchor), + composer.trailingAnchor.constraint(equalTo: threadVC.view.trailingAnchor), + composer.bottomAnchor.constraint(equalTo: threadVC.view.safeAreaLayoutGuide.bottomAnchor) + ]) + + self.navigationController?.pushViewController(threadVC, animated: true) } ``` @@ -384,10 +429,10 @@ messageList.set(messagesRequestBuilder: messageRequestBuilder) --- -To ensure that the `ThreadedMessages` is properly configured, passing the controller is mandatory. +To ensure that the `CometChatThreadedMessageHeader` is properly configured, passing the controller is mandatory. ```swift -let threadedMessageView = CometChatThreadedMessages() -threadedMessageView.set(controller: UIViewController) // Passing the controller is required +let threadedMessageHeader = CometChatThreadedMessageHeader() +threadedMessageHeader.set(controller: UIViewController) // Passing the controller is required ``` From 74efd380af747244d76fc7595cb036c5682810e8 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 18:44:11 +0530 Subject: [PATCH 074/106] fixes --- ui-kit/ios/component-styling.mdx | 20 ++++++++++---------- ui-kit/ios/localize.mdx | 2 +- ui-kit/ios/theme-introduction.mdx | 4 ++-- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/ui-kit/ios/component-styling.mdx b/ui-kit/ios/component-styling.mdx index e6d47a9d0..e866e3b8a 100644 --- a/ui-kit/ios/component-styling.mdx +++ b/ui-kit/ios/component-styling.mdx @@ -233,14 +233,14 @@ import CometChatUIKitSwift CometChatMessageList.style.backgroundColor = UIColor(hex: "#FBAA75") // Outgoing message bubbles (your messages) -CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = UIColor(hex: "#F76808") -CometChatMessageList.messageBubbleStyle.outgoing.textColor = .white -CometChatMessageList.messageBubbleStyle.outgoing.textFont = UIFont.systemFont(ofSize: 15) +CometChatMessageBubble.style.outgoing.backgroundColor = UIColor(hex: "#F76808") +CometChatMessageBubble.style.outgoing.textBubbleStyle.textColor = .white +CometChatMessageBubble.style.outgoing.textBubbleStyle.textFont = UIFont.systemFont(ofSize: 15) // Incoming message bubbles (other's messages) -CometChatMessageList.messageBubbleStyle.incoming.backgroundColor = UIColor(hex: "#E8E8E8") -CometChatMessageList.messageBubbleStyle.incoming.textColor = UIColor(hex: "#212121") -CometChatMessageList.messageBubbleStyle.incoming.textFont = UIFont.systemFont(ofSize: 15) +CometChatMessageBubble.style.incoming.backgroundColor = UIColor(hex: "#E8E8E8") +CometChatMessageBubble.style.incoming.textBubbleStyle.textColor = UIColor(hex: "#212121") +CometChatMessageBubble.style.incoming.textBubbleStyle.textFont = UIFont.systemFont(ofSize: 15) // Timestamp style CometChatMessageList.style.timestampTextColor = UIColor(hex: "#9E9E9E") @@ -517,10 +517,10 @@ class StyleManager { // Apply to Message List CometChatMessageList.style.backgroundColor = surfaceColor - CometChatMessageList.messageBubbleStyle.outgoing.backgroundColor = primaryColor - CometChatMessageList.messageBubbleStyle.outgoing.textColor = .white - CometChatMessageList.messageBubbleStyle.incoming.backgroundColor = .white - CometChatMessageList.messageBubbleStyle.incoming.textColor = textPrimary + CometChatMessageBubble.style.outgoing.backgroundColor = primaryColor + CometChatMessageBubble.style.outgoing.textBubbleStyle.textColor = .white + CometChatMessageBubble.style.incoming.backgroundColor = .white + CometChatMessageBubble.style.incoming.textBubbleStyle.textColor = textPrimary // Apply to Message Composer CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = primaryColor diff --git a/ui-kit/ios/localize.mdx b/ui-kit/ios/localize.mdx index 04f624f00..911145fde 100644 --- a/ui-kit/ios/localize.mdx +++ b/ui-kit/ios/localize.mdx @@ -165,7 +165,7 @@ This system uses closures that you can override to provide your own custom strin | `time` | Called to format a timestamp as a standard time (e.g., "12:30 PM") | `CometChatUIKit.dateTimeFormatter.time = { ... }` | | `today` | Called when rendering messages sent today | `CometChatUIKit.dateTimeFormatter.today = { ... }` | | `yesterday` | Called for yesterday's messages | `CometChatUIKit.dateTimeFormatter.yesterday = { ... }` | -| `lastweek` | Called for messages within the last week | `CometChatUIKit.dateTimeFormatter.lastweek = { ... }` | +| `lastWeek` | Called for messages within the last week | `CometChatUIKit.dateTimeFormatter.lastWeek = { ... }` | | `otherDay` | Called for dates older than last week | `CometChatUIKit.dateTimeFormatter.otherDay = { ... }` | | `minute` | Called when referring to "a minute ago" | `CometChatUIKit.dateTimeFormatter.minute = { ... }` | | `minutes` | Called for "x minutes ago" | `CometChatUIKit.dateTimeFormatter.minutes = { ... }` | diff --git a/ui-kit/ios/theme-introduction.mdx b/ui-kit/ios/theme-introduction.mdx index 2b9500cdf..69f6db529 100644 --- a/ui-kit/ios/theme-introduction.mdx +++ b/ui-kit/ios/theme-introduction.mdx @@ -12,8 +12,8 @@ description: "Create visually consistent and customizable user interfaces with C | Package | `CometChatUIKitSwift` | | Theme Class | `CometChatTheme` — Global theming system for all CometChat components | | Primary Color | `CometChatTheme.primaryColor = UIColor` | -| Background Color | `CometChatTheme.backgroundColor` | -| Border Color | `CometChatTheme.borderColor` | +| Background Colors | `CometChatTheme.backgroundColor01`, `backgroundColor02`, `backgroundColor03` | +| Border Colors | `CometChatTheme.borderColorDefault`, `borderColorLight`, `borderColorDark` | | Typography Class | `CometChatTypography` | | Typography Properties | `Body.regular`, `Body.bold`, `Heading.regular` | | Example | `CometChatTheme.primaryColor = UIColor(hex: "#F76808")` | From fabfcc512ed54534177c58848324e7412e0ae7fb Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 19:04:19 +0530 Subject: [PATCH 075/106] Fixes --- ui-kit/ios/ai-assistant-chat-history.mdx | 10 +++++----- ui-kit/ios/search.mdx | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index 235d64b33..a0c011ed8 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -168,7 +168,7 @@ class AIAssistantViewController: UIViewController { // MARK: - Callbacks private func setupCallbacks() { // New chat button tapped - chatHistoryComponent.onNewChatButtonClicked = { [weak self] in + chatHistoryComponent.onNewChatButtonClicked = { [weak self] user in self?.startNewAIChat() } @@ -594,7 +594,7 @@ class MainTabBarController: UITabBarController { // AI Assistant Tab let aiVC = CometChatAIAssistanceChatHistory() aiVC.user = currentUser - aiVC.onNewChatButtonClicked = { [weak self] in + aiVC.onNewChatButtonClicked = { [weak self] user in self?.startNewAIChat() } let aiNav = UINavigationController(rootViewController: aiVC) @@ -676,9 +676,9 @@ class ProfileViewController: UIViewController { let chatHistory = CometChatAIAssistanceChatHistory() chatHistory.user = user - chatHistory.onNewChatButtonClicked = { [weak self] in + chatHistory.onNewChatButtonClicked = { [weak self] selectedUser in let messagesVC = CometChatMessages() - messagesVC.user = self?.user + messagesVC.user = selectedUser self?.navigationController?.pushViewController(messagesVC, animated: true) } @@ -713,7 +713,7 @@ class ProfileViewController: UIViewController { | Method | Parameters | Description | |--------|------------|-------------| -| `onNewChatButtonClicked` | `() -> Void` | New chat button tapped | +| `onNewChatButtonClicked` | `(User) -> Void` | New chat button tapped | | `onMessageClicked` | `(BaseMessage) -> Void` | Message tapped | | `set(onLoad:)` | `([BaseMessage]) -> Void` | Data loaded | | `set(onEmpty:)` | `() -> Void` | No data | diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index 900a1a787..8a93b1cbc 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -30,7 +30,7 @@ The `CometChatSearch` component is a powerful and customizable search interface "messagesRequestBuilder": { "type": "MessagesRequest.MessageRequestBuilder", "default": "SDK default" } }, "callbacks": { - "onConversationClicked": "(Conversation) -> Void", + "onConversationClicked": "(Conversation, IndexPath) -> Void", "onMessageClicked": "(BaseMessage) -> Void", "onBack": "() -> Void", "onError": "(CometChatException) -> Void", @@ -111,7 +111,7 @@ Triggered when you click on a Conversation from the search result. This action d import CometChatUIKitSwift let search = CometChatSearch() -search.onConversationClicked = { conversation in +search.onConversationClicked = { conversation, indexPath in print("Conversation clicked:", conversation.conversationId) } ``` @@ -759,7 +759,7 @@ Open the search screen from a conversations list: @objc func openSearch() { let searchVC = CometChatSearch() - searchVC.onConversationClicked = { [weak self] conversation in + searchVC.onConversationClicked = { [weak self] conversation, indexPath in // Navigate to messages for the selected conversation let messagesVC = CometChatMessages() if let user = conversation.conversationWith as? User { From 0d85a176fd2e2c54fee473264faa8aa056702623 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Thu, 19 Mar 2026 19:24:04 +0530 Subject: [PATCH 076/106] fixes --- sdk/ios/default-calling.mdx | 1 + ui-kit/ios/outgoing-call.mdx | 1 + 2 files changed, 2 insertions(+) diff --git a/sdk/ios/default-calling.mdx b/sdk/ios/default-calling.mdx index 7b5f18618..c7d9c8d8b 100644 --- a/sdk/ios/default-calling.mdx +++ b/sdk/ios/default-calling.mdx @@ -34,6 +34,7 @@ let callType: CometChat.CallType = .video // or .audio let newCall = Call(receiverId: receiverID, callType: callType, receiverType: receiverType) CometChat.initiateCall(call: newCall, onSuccess: { call in + guard let call = call else { return } // Call initiated, show outgoing call UI // Store call.sessionID for later use print("Call initiated successfully") diff --git a/ui-kit/ios/outgoing-call.mdx b/ui-kit/ios/outgoing-call.mdx index 33016421e..5dfdc6494 100644 --- a/ui-kit/ios/outgoing-call.mdx +++ b/ui-kit/ios/outgoing-call.mdx @@ -704,6 +704,7 @@ func initiateCall(to user: User, callType: CometChat.CallType) { let call = Call(receiverId: user.uid ?? "", callType: callType, receiverType: .user) CometChat.initiateCall(call: call) { [weak self] initiatedCall in + guard let initiatedCall = initiatedCall else { return } DispatchQueue.main.async { let outgoingCall = CometChatOutgoingCall() outgoingCall.set(call: initiatedCall) From a74da903b839159b2d6880026b5a40d65ae53536 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 10:29:04 +0530 Subject: [PATCH 077/106] issue fixes --- ui-kit/ios/guide-ai-agent.mdx | 42 +++++++++++------------ ui-kit/ios/guide-block-unblock-user.mdx | 4 +-- ui-kit/ios/guide-group-chat.mdx | 6 ++-- ui-kit/ios/guide-message-privately.mdx | 45 +++++++++++++++---------- ui-kit/ios/troubleshooting.mdx | 4 +-- ui-kit/ios/upgrading-from-v4.mdx | 2 +- 6 files changed, 56 insertions(+), 47 deletions(-) diff --git a/ui-kit/ios/guide-ai-agent.mdx b/ui-kit/ios/guide-ai-agent.mdx index 0a18bb6b2..187c6d4b2 100644 --- a/ui-kit/ios/guide-ai-agent.mdx +++ b/ui-kit/ios/guide-ai-agent.mdx @@ -163,9 +163,9 @@ class ProductionAIAgentViewController: UIViewController { }) // Chat history button handler - messageHeader.set(chatHistoryButtonClick: { [weak self] in + messageHeader.onAiChatHistoryClicked = { [weak self] user in self?.openChatHistory() - }) + } view.addSubview(messageHeader) } @@ -227,7 +227,7 @@ class ProductionAIAgentViewController: UIViewController { // MARK: - Chat History private func openChatHistory() { - let chatHistoryVC = CometChatAIAssistantChatHistory() + let chatHistoryVC = CometChatAIAssistanceChatHistory() if let user = user { chatHistoryVC.set(user: user) @@ -236,19 +236,19 @@ class ProductionAIAgentViewController: UIViewController { } // Handle new chat button - chatHistoryVC.set(onNewChatButtonClicked: { [weak self] in + chatHistoryVC.onNewChatButtonClicked = { [weak self] user in self?.startNewChat() - }) + } // Handle message selection to resume conversation - chatHistoryVC.set(onMessageClicked: { [weak self] message in + chatHistoryVC.onMessageClicked = { [weak self] message in self?.resumeConversation(from: message) - }) + } // Handle close - chatHistoryVC.set(onClose: { [weak self] in + chatHistoryVC.onClose = { [weak self] in self?.navigationController?.popViewController(animated: true) - }) + } navigationController?.pushViewController(chatHistoryVC, animated: true) } @@ -342,7 +342,7 @@ class AIAgentStylingExample { func applyGlobalStyles() { // Configure AI bubble style - let aiBubbleStyle = AiAssistantBubbleStyle() + var aiBubbleStyle = AIAssistantBubbleStyle() aiBubbleStyle.backgroundColor = .clear aiBubbleStyle.borderWidth = 1 aiBubbleStyle.borderColor = .systemBlue @@ -351,7 +351,7 @@ class AIAgentStylingExample { aiBubbleStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 12) // Apply globally - CometChatAiAssistantBubble.style = aiBubbleStyle + CometChatAIAssistantBubble.style = aiBubbleStyle } func applyInstanceStyles() -> ProductionAIAgentViewController { @@ -439,7 +439,7 @@ messageComposer.set(aiAssistantTools: { message in ## Chat History Component -The `CometChatAIAssistantChatHistory` component displays previous AI conversations: +The `CometChatAIAssistanceChatHistory` component displays previous AI conversations: ```swift import UIKit @@ -463,29 +463,29 @@ class ChatHistoryViewController: UIViewController { private func setupChatHistory() { guard let user = user else { return } - let chatHistory = CometChatAIAssistantChatHistory() + let chatHistory = CometChatAIAssistanceChatHistory() chatHistory.set(user: user) // New chat button - chatHistory.set(onNewChatButtonClicked: { [weak self] in + chatHistory.onNewChatButtonClicked = { [weak self] user in let newChat = ProductionAIAgentViewController(user: user) self?.navigationController?.pushViewController(newChat, animated: true) - }) + } // Resume conversation - chatHistory.set(onMessageClicked: { [weak self] message in + chatHistory.onMessageClicked = { [weak self] message in let resumeChat = ProductionAIAgentViewController( user: user, parentMessage: message, isHistory: true ) self?.navigationController?.pushViewController(resumeChat, animated: true) - }) + } // Close handler - chatHistory.set(onClose: { [weak self] in + chatHistory.onClose = { [weak self] in self?.dismiss(animated: true) - }) + } addChild(chatHistory) view.addSubview(chatHistory.view) @@ -513,8 +513,8 @@ class ChatHistoryViewController: UIViewController { | `CometChatMessageHeader` | Navigation and chat history access | | `CometChatMessageList` | Display messages with AI responses | | `CometChatMessageComposer` | Send messages to AI agent | -| `CometChatAIAssistantChatHistory` | Browse previous AI conversations | -| `CometChatAiAssistantBubble` | AI message bubble styling | +| `CometChatAIAssistanceChatHistory` | Browse previous AI conversations | +| `CometChatAIAssistantBubble` | AI message bubble styling | ## Related Guides diff --git a/ui-kit/ios/guide-block-unblock-user.mdx b/ui-kit/ios/guide-block-unblock-user.mdx index 0484e14d8..62f665eb7 100644 --- a/ui-kit/ios/guide-block-unblock-user.mdx +++ b/ui-kit/ios/guide-block-unblock-user.mdx @@ -435,7 +435,7 @@ class ProductionUserDetailsViewController: UIViewController { // Emit event for other components if let user = self?.user { - CometChatUserEvents.emitOnUserBlock(user: user) + CometChatUserEvents.ccUserBlocked(user: user) } } } onError: { [weak self] error in @@ -454,7 +454,7 @@ class ProductionUserDetailsViewController: UIViewController { // Emit event for other components if let user = self?.user { - CometChatUserEvents.emitOnUserUnblock(user: user) + CometChatUserEvents.ccUserUnblocked(user: user) } } } onError: { [weak self] error in diff --git a/ui-kit/ios/guide-group-chat.mdx b/ui-kit/ios/guide-group-chat.mdx index 1f5d8a79d..349edfdbe 100644 --- a/ui-kit/ios/guide-group-chat.mdx +++ b/ui-kit/ios/guide-group-chat.mdx @@ -288,10 +288,8 @@ extension GroupDetailsViewController: CometChatGroupDelegate { // MARK: - CometChatGroupEventListener extension GroupDetailsViewController: CometChatGroupEventListener { - func onOwnershipChange(group: Group?, member: GroupMember?) { - if let group = group { - updateGroupInfo(group) - } + func ccOwnershipChanged(group: Group, newOwner: GroupMember) { + updateGroupInfo(group) } } diff --git a/ui-kit/ios/guide-message-privately.mdx b/ui-kit/ios/guide-message-privately.mdx index c1b345cc1..11b6a5399 100644 --- a/ui-kit/ios/guide-message-privately.mdx +++ b/ui-kit/ios/guide-message-privately.mdx @@ -27,8 +27,8 @@ Before implementing this feature, ensure you have: | `MessageDataSource` | Supplies the `messagePrivatelyOption` in the options array | | `CometChatMessageListViewModel` | Manages UI state, including `hideMessagePrivatelyOption` | | `CometChatMessages` | Entry point for rendering or pushing the private chat interface | -| `CometChatUIKit.getUser(uid:)` | Retrieves the `User` object for the selected message sender | -| `CometChatUIKit.getConversationWith(user:)` | Creates or fetches the 1-on-1 conversation instance | +| `CometChat.getUser(UID:onSuccess:onError:)` | Retrieves the `User` object for the selected message sender | +| `CometChatUIEvents.openChat(user:group:)` | Opens the chat interface for a user or group | | `UIViewController` (Navigation) | Pushes or presents the private chat screen (`CometChatMessages`) | ## Integration Steps @@ -63,20 +63,31 @@ import CometChatSDK import CometChatUIKitSwift func startPrivateChat(with selectedMessage: BaseMessage) { - // Get the sender's UID from the selected message - if let uid = selectedMessage.sender?.uid { + // Get the sender from the selected message + if let user = selectedMessage.sender { + // Open the private chat using CometChatUIEvents + DispatchQueue.main.async { + CometChatUIEvents.openChat(user: user, group: nil) + } + } +} + +// Alternative: Manual navigation with user fetch +func startPrivateChatManual(with selectedMessage: BaseMessage) { + guard let uid = selectedMessage.sender?.uid else { return } + + // Fetch the user object + CometChat.getUser(UID: uid) { [weak self] user in + guard let user = user else { return } - // Fetch the user object - CometChatUIKit.getUser(uid: uid) { user in - - // Get or create the conversation - CometChatUIKit.getConversationWith(user: user) { conversation in - - // Navigate to the private chat screen - let messagesVC = CometChatMessages(conversation: conversation) - navigationController?.pushViewController(messagesVC, animated: true) - } + DispatchQueue.main.async { + // Navigate to the private chat screen + let messagesVC = CometChatMessages() + messagesVC.set(user: user) + self?.navigationController?.pushViewController(messagesVC, animated: true) } + } onError: { error in + print("Error fetching user: \(error?.errorDescription ?? "")") } } ``` @@ -92,8 +103,8 @@ This automates the transition from group context to private conversation. | 1 | Long-press a group message in `CometChatMessageList` | | 2 | Options menu appears with **Message Privately** | | 3 | User taps **Message Privately** | -| 4 | App fetches `User` via `CometChatUIKit.getUser(uid:)` | -| 5 | Retrieves or creates conversation via `CometChatUIKit.getConversationWith(user:)` | +| 4 | App gets `User` from `message.sender` | +| 5 | Opens chat via `CometChatUIEvents.openChat(user:group:)` | | 6 | Pushes `CometChatMessages` onto the navigation stack | ## Customization Options @@ -153,7 +164,7 @@ func getMessageOptions(for message: BaseMessage) -> [CometChatMessageOption] { | Error Type | Solution | |------------|----------| -| Block state | Catch errors from `getUser`/`getConversationWith` and alert user | +| Block state | Catch errors from `CometChat.getUser` and alert user | | Network failures | Present retry or toast on navigation errors | | Invalid data | Disable option if `sender.uid` is nil | diff --git a/ui-kit/ios/troubleshooting.mdx b/ui-kit/ios/troubleshooting.mdx index c894a5753..0926b84b5 100644 --- a/ui-kit/ios/troubleshooting.mdx +++ b/ui-kit/ios/troubleshooting.mdx @@ -91,7 +91,7 @@ If CocoaPods continues to fail, use SPM instead: | Conversations not updating | Check SDK connection and real-time listeners | | Navigation not working | Verify `navigationController` is not nil; embed in `UINavigationController` | | Custom views not appearing | Ensure custom view has proper constraints and non-zero frame | -| Typing indicator not showing | Verify `hideTypingIndicator` is not set to true | +| Typing indicator not showing | Verify `disableTyping` is not set to true | --- @@ -194,7 +194,7 @@ If CocoaPods continues to fail, use SPM instead: | Callbacks not firing | Set callbacks before pushing to navigation | | AI not responding | Verify AI features are enabled in dashboard | | Streaming not working | Check network connectivity | -| Agent not detected | Verify user role contains "agentic" | +| Agent not detected | Verify user has `isAgentic` property set to true | --- diff --git a/ui-kit/ios/upgrading-from-v4.mdx b/ui-kit/ios/upgrading-from-v4.mdx index 5bc92e1a8..19ed98fae 100644 --- a/ui-kit/ios/upgrading-from-v4.mdx +++ b/ui-kit/ios/upgrading-from-v4.mdx @@ -405,7 +405,7 @@ In v5, the approach to properties has been refined: | set(onLoad:) | ([BaseMessage]) -> Void | Load callback | | set(headerView:) | UIView | Custom header view | | set(footerView:) | UIView | Custom footer view | -| set(textFormatter:) | [CometChatTextFormatter] | Text formatters | +| set(textFormatters:) | [CometChatTextFormatter] | Text formatters | | dateTimeFormatter | CometChatDateTimeFormatter | Date/time formatting | #### Renamed Properties From 28652fd3e19c49f1811baec81e928b5b89886ee4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 12:29:56 +0530 Subject: [PATCH 078/106] fixes --- ui-kit/ios/core-features.mdx | 30 +++++++++++++++--------------- ui-kit/ios/ios-tab-based-chat.mdx | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/ui-kit/ios/core-features.mdx b/ui-kit/ios/core-features.mdx index d00343210..f5023a6e1 100644 --- a/ui-kit/ios/core-features.mdx +++ b/ui-kit/ios/core-features.mdx @@ -48,7 +48,7 @@ class ChatViewController: UIViewController { let messagesVC = CometChatMessages() // Set the user to chat with - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -88,7 +88,7 @@ class MediaChatViewController: UIViewController { // - Documents // - Audio files - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -148,7 +148,7 @@ class ReceiptsViewController: UIViewController { // To hide receipts: // messagesVC.hideReceipts = true - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -200,7 +200,7 @@ class UnreadMessagesViewController: UIViewController { // Enable starting from first unread message messagesVC.scrollToUnreadMessages = true - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -247,7 +247,7 @@ class TypingIndicatorViewController: UIViewController { let messagesVC = CometChatMessages() - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -352,7 +352,7 @@ class ReactionsViewController: UIViewController { let messagesVC = CometChatMessages() - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -464,7 +464,7 @@ class ThreadedMessagesViewController: UIViewController { let messagesVC = CometChatMessages() - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -648,7 +648,7 @@ class QuotedReplyViewController: UIViewController { let messagesVC = CometChatMessages() - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -730,7 +730,7 @@ class ModerationViewController: UIViewController { let messagesVC = CometChatMessages() - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -769,7 +769,7 @@ class ReportMessageViewController: UIViewController { let messagesVC = CometChatMessages() - CometChat.getUser(UID: "user-123") { user in + CometChat.getUser(UID: "cometchat-uid-1") { user in DispatchQueue.main.async { messagesVC.set(user: user) self.navigationController?.pushViewController(messagesVC, animated: true) @@ -785,7 +785,7 @@ class ReportMessageViewController: UIViewController { View and manage reported messages in [Flagged Messages](/moderation/flagged-messages). -## Complete Chat App Example +{/* ## Complete Chat App Example Here's a production-ready implementation combining all core features: @@ -821,7 +821,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } private func loginAndShowChat() { - CometChatUIKit.login(uid: "user-123") { result in + CometChatUIKit.login(uid: "cometchat-uid-1") { result in switch result { case .success(let user): print("Logged in as: \(user.name ?? "")") @@ -898,9 +898,9 @@ class MainTabBarController: UITabBarController { viewControllers = [conversationsNav, usersNav, groupsNav] } } -``` +``` */} -## Feature Summary +{/* ## Feature Summary | Feature | Component | Enabled by Default | |---------|-----------|-------------------| @@ -913,4 +913,4 @@ class MainTabBarController: UITabBarController { | Mentions | [MessageComposer](/ui-kit/ios/message-composer) | ✅ | | Threads | [ThreadedMessages](/ui-kit/ios/threaded-messages-header) | ✅ | | Search | [Search](/ui-kit/ios/search) | ✅ | -| Moderation | Dashboard Config | Configure in Dashboard | +| Moderation | Dashboard Config | Configure in Dashboard | */} diff --git a/ui-kit/ios/ios-tab-based-chat.mdx b/ui-kit/ios/ios-tab-based-chat.mdx index ca617c55e..e49231e10 100644 --- a/ui-kit/ios/ios-tab-based-chat.mdx +++ b/ui-kit/ios/ios-tab-based-chat.mdx @@ -42,7 +42,7 @@ Four tabs working together: Initialize CometChat and launch the tabbed view after login. -```swift title="SceneDelegate.swift" highlight={5-7} lines +```swift title="SceneDelegate.swift" highlight={9-11} lines import UIKit import CometChatUIKitSwift import CometChatSDK From f3151d50107199f23ddf8a70d4a971121cb52fa4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 12:55:46 +0530 Subject: [PATCH 079/106] Update core-features.mdx --- ui-kit/react/core-features.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/ui-kit/react/core-features.mdx b/ui-kit/react/core-features.mdx index 8af49af9c..529cfe2b2 100644 --- a/ui-kit/react/core-features.mdx +++ b/ui-kit/react/core-features.mdx @@ -210,6 +210,7 @@ Conversation and Advanced Search is a powerful feature provided by CometChat tha | [Conversations](/ui-kit/react/conversations) | [Conversations](/ui-kit/react/conversations) displays the search input. | See the [Groups](/ui-kit/react/groups) component page for details. + --- ## Next Steps From 06eca126603188ae877d53c783804ff3a98bc41d Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 13:01:00 +0530 Subject: [PATCH 080/106] Update extensions.mdx --- ui-kit/ios/extensions.mdx | 211 ++++++++++++++++---------------------- 1 file changed, 88 insertions(+), 123 deletions(-) diff --git a/ui-kit/ios/extensions.mdx b/ui-kit/ios/extensions.mdx index 74426fb4d..399619aa3 100644 --- a/ui-kit/ios/extensions.mdx +++ b/ui-kit/ios/extensions.mdx @@ -3,31 +3,12 @@ title: "Extensions" description: "Enable powerful chat features with zero code using CometChat extensions" --- - -```json -{ - "category": "extensions", - "dashboardSetup": { - "location": "CometChat Dashboard → Extensions", - "activation": "Enable extensions in dashboard, they appear automatically in UI Kit" - }, - "extensions": [ - {"name": "stickers", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/stickers"}, - {"name": "polls", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/polls"}, - {"name": "whiteboard", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/collaborative-whiteboard"}, - {"name": "document", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/collaborative-document"}, - {"name": "reactions", "component": "CometChatMessageList", "setupGuide": "/fundamentals/reactions"}, - {"name": "translation", "component": "CometChatMessageList", "setupGuide": "/fundamentals/message-translation"}, - {"name": "linkPreview", "component": "CometChatMessageList", "setupGuide": "/fundamentals/link-preview"}, - {"name": "profanityFilter", "component": "CometChatMessageList", "setupGuide": "/moderation/legacy-extensions"}, - {"name": "dataMasking", "component": "CometChatMessageList", "setupGuide": "/moderation/legacy-extensions"}, - {"name": "imageModeration", "component": "CometChatMessageList", "setupGuide": "/moderation/legacy-extensions"}, - {"name": "thumbnails", "component": "CometChatMessageList", "setupGuide": "/fundamentals/thumbnail-generation"}, - {"name": "smartReplies", "component": "CometChatMessageComposer", "setupGuide": "/fundamentals/smart-replies"} - ] -} -``` - +| Field | Value | +|-------|-------| +| Dashboard setup | CometChat Dashboard → Extensions | +| Activation | Enable in dashboard, features appear automatically in UI Kit | +| Code required | None — extensions work out of the box | +| Platforms | Works across iOS, Android, and Web with the same configuration | Extensions add powerful features to your chat app without writing any code. Simply enable them in your [CometChat Dashboard](https://app.cometchat.com), and they automatically appear in the UI Kit components. @@ -39,12 +20,12 @@ Extensions add powerful features to your chat app without writing any code. Simp 4. The features automatically appear in your app after initialization -Extensions are enabled at the dashboard level. Once activated, they work across all platforms (iOS, Android, Web) using the same CometChat app. No code changes required. +Extensions are enabled at the dashboard level. Once activated, they work across all platforms (iOS, Android, Web) using the same CometChat app. -For detailed information on all extensions, see [Extensions Overview](/fundamentals/extensions-overview). +## Composer Extensions -## Available Extensions +These extensions add new options to the [Message Composer](/ui-kit/ios/message-composer) attachment menu or action sheet. ### Stickers @@ -54,11 +35,9 @@ Let users express emotions with fun, pre-designed stickers. -| Feature | Details | -|---------|---------| -| Appears in | [Message Composer](/ui-kit/ios/message-composer) attachment menu | -| Setup guide | [Sticker Extension](/fundamentals/stickers) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message Composer](/ui-kit/ios/message-composer) | [Sticker Extension](/fundamentals/stickers) | ### Polls @@ -68,11 +47,9 @@ Create polls to gather opinions in group chats quickly. -| Feature | Details | -|---------|---------| -| Appears in | [Message Composer](/ui-kit/ios/message-composer) action sheet | -| Setup guide | [Polls Extension](/fundamentals/polls) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message Composer](/ui-kit/ios/message-composer) | [Polls Extension](/fundamentals/polls) | ### Collaborative Whiteboard @@ -82,11 +59,9 @@ Real-time whiteboard for drawing, brainstorming, and sharing ideas together. -| Feature | Details | -|---------|---------| -| Appears in | [Message Composer](/ui-kit/ios/message-composer) action sheet | -| Setup guide | [Collaborative Whiteboard](/fundamentals/collaborative-whiteboard) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message Composer](/ui-kit/ios/message-composer) | [Collaborative Whiteboard](/fundamentals/collaborative-whiteboard) | ### Collaborative Document @@ -96,11 +71,21 @@ Work together on shared documents in real-time with other users. -| Feature | Details | -|---------|---------| -| Appears in | [Message Composer](/ui-kit/ios/message-composer) action sheet | -| Setup guide | [Collaborative Document](/fundamentals/collaborative-document) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message Composer](/ui-kit/ios/message-composer) | [Collaborative Document](/fundamentals/collaborative-document) | + +### Smart Replies + +AI-powered suggested responses for faster, more efficient conversations. + +| Component | Setup Guide | +|-----------|-------------| +| [Message Composer](/ui-kit/ios/message-composer) | [Smart Replies](/fundamentals/smart-replies) | + +## Message List Extensions + +These extensions enhance messages displayed in the [Message List](/ui-kit/ios/message-list). ### Message Reactions @@ -110,11 +95,9 @@ Let users react to messages with a range of emojis for quick responses. -| Feature | Details | -|---------|---------| -| Appears in | [Message List](/ui-kit/ios/message-list) long-press menu | -| Setup guide | [Reactions Extension](/fundamentals/reactions) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message List](/ui-kit/ios/message-list) | [Reactions Extension](/fundamentals/reactions) | ### Message Translation @@ -124,11 +107,9 @@ Translate messages into any language instantly, eliminating language barriers. -| Feature | Details | -|---------|---------| -| Appears in | [Message List](/ui-kit/ios/message-list) message actions | -| Setup guide | [Message Translation](/fundamentals/message-translation) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message List](/ui-kit/ios/message-list) | [Message Translation](/fundamentals/message-translation) | ### Link Preview @@ -138,11 +119,25 @@ Show rich previews for URLs shared in chat including title, description, and thu -| Feature | Details | -|---------|---------| -| Appears in | [Message List](/ui-kit/ios/message-list) message bubbles | -| Setup guide | [Link Preview](/fundamentals/link-preview) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message List](/ui-kit/ios/message-list) | [Link Preview](/fundamentals/link-preview) | + +### Thumbnail Generation + +Automatically create smaller preview images for faster loading and reduced bandwidth. + + + + + +| Component | Setup Guide | +|-----------|-------------| +| [Message List](/ui-kit/ios/message-list) | [Thumbnail Generation](/fundamentals/thumbnail-generation) | + +## Moderation Extensions + +These extensions help maintain a safe chat environment by filtering content automatically. ### Profanity Filter @@ -152,11 +147,9 @@ Automatically censor inappropriate and obscene words in messages. -| Feature | Details | -|---------|---------| -| Appears in | [Message List](/ui-kit/ios/message-list) - filtered automatically | -| Setup guide | [Legacy Extensions](/moderation/legacy-extensions) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message List](/ui-kit/ios/message-list) | [Legacy Extensions](/moderation/legacy-extensions) | ### Data Masking @@ -166,11 +159,9 @@ Automatically mask sensitive data like credit card numbers and phone numbers. -| Feature | Details | -|---------|---------| -| Appears in | [Message List](/ui-kit/ios/message-list) - masked automatically | -| Setup guide | [Legacy Extensions](/moderation/legacy-extensions) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message List](/ui-kit/ios/message-list) | [Legacy Extensions](/moderation/legacy-extensions) | ### Image Moderation @@ -180,56 +171,30 @@ Detect and filter inappropriate or explicit images using AI/ML. -| Feature | Details | -|---------|---------| -| Appears in | [Message List](/ui-kit/ios/message-list) - filtered automatically | -| Setup guide | [Legacy Extensions](/moderation/legacy-extensions) | -| Code required | None - automatic after dashboard activation | - -### Thumbnail Generation - -Automatically create smaller preview images for faster loading and reduced bandwidth. - - - - - -| Feature | Details | -|---------|---------| -| Appears in | [Message List](/ui-kit/ios/message-list) image bubbles | -| Setup guide | [Thumbnail Generation](/fundamentals/thumbnail-generation) | -| Code required | None - automatic after dashboard activation | - -### Smart Replies - -AI-powered suggested responses for faster, more efficient conversations. - -| Feature | Details | -|---------|---------| -| Appears in | [Message Composer](/ui-kit/ios/message-composer) suggestions | -| Setup guide | [Smart Replies](/fundamentals/smart-replies) | -| Code required | None - automatic after dashboard activation | +| Component | Setup Guide | +|-----------|-------------| +| [Message List](/ui-kit/ios/message-list) | [Legacy Extensions](/moderation/legacy-extensions) | ## Extensions Summary -| Extension | Component | Use Case | -|-----------|-----------|----------| -| Stickers | Message Composer | Fun expression | -| Polls | Message Composer | Group decisions | -| Whiteboard | Message Composer | Visual collaboration | -| Document | Message Composer | Document collaboration | -| Reactions | Message List | Quick responses | -| Translation | Message List | Multi-language support | -| Link Preview | Message List | Rich URL previews | -| Profanity Filter | Message List | Content moderation | -| Data Masking | Message List | Privacy protection | -| Image Moderation | Message List | Safe content | -| Thumbnails | Message List | Faster loading | -| Smart Replies | Message Composer | Quick responses | - -## Related - -- [Extensions Overview](/fundamentals/extensions-overview) - Full extension documentation -- [Moderation](/moderation/overview) - Content moderation features -- [Message Composer](/ui-kit/ios/message-composer) - Where composer extensions appear -- [Message List](/ui-kit/ios/message-list) - Where message extensions appear +| Extension | Category | Component | Use Case | +|-----------|----------|-----------|----------| +| Stickers | Composer | Message Composer | Fun expression | +| Polls | Composer | Message Composer | Group decisions | +| Whiteboard | Composer | Message Composer | Visual collaboration | +| Document | Composer | Message Composer | Document collaboration | +| Smart Replies | Composer | Message Composer | Quick responses | +| Reactions | Message List | Message List | Quick responses | +| Translation | Message List | Message List | Multi-language support | +| Link Preview | Message List | Message List | Rich URL previews | +| Thumbnails | Message List | Message List | Faster loading | +| Profanity Filter | Moderation | Message List | Content moderation | +| Data Masking | Moderation | Message List | Privacy protection | +| Image Moderation | Moderation | Message List | Safe content | + +## Next Steps + +- [Extensions Overview](/fundamentals/extensions-overview) — Full extension documentation +- [Moderation](/moderation/overview) — Content moderation features +- [Message Composer](/ui-kit/ios/message-composer) — Where composer extensions appear +- [Message List](/ui-kit/ios/message-list) — Where message extensions appear From 289d78ad6fca3b8886730833878bff7c82b597b9 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 13:01:04 +0530 Subject: [PATCH 081/106] Update ai-features.mdx --- ui-kit/ios/ai-features.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-kit/ios/ai-features.mdx b/ui-kit/ios/ai-features.mdx index a299c6973..73eb5b61b 100644 --- a/ui-kit/ios/ai-features.mdx +++ b/ui-kit/ios/ai-features.mdx @@ -333,7 +333,7 @@ class AIAssistantViewController: UIViewController { ---- +{/* --- ## Complete App with AI Features @@ -513,4 +513,4 @@ extension AIAssistantListViewController: UITableViewDelegate, UITableViewDataSou - [Message List](/ui-kit/ios/message-list) - Where conversation starters appear - [Message Composer](/ui-kit/ios/message-composer) - Where smart replies appear - [Conversation Starter Guide](/fundamentals/ai-user-copilot/conversation-starter) - Platform configuration -- [Smart Replies Guide](/fundamentals/ai-user-copilot/smart-replies) - Platform configuration +- [Smart Replies Guide](/fundamentals/ai-user-copilot/smart-replies) - Platform configuration */} From 32c3b8ef6cfbe5e55f92edab93f3c248a8cddd5a Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 13:05:05 +0530 Subject: [PATCH 082/106] Update call-features.mdx --- ui-kit/ios/call-features.mdx | 2 -- 1 file changed, 2 deletions(-) diff --git a/ui-kit/ios/call-features.mdx b/ui-kit/ios/call-features.mdx index e46b0c29b..50321f3d5 100644 --- a/ui-kit/ios/call-features.mdx +++ b/ui-kit/ios/call-features.mdx @@ -620,8 +620,6 @@ callLogs.set(onItemClick: { callLog in }) --- ---- - ## Related - [Call Logs](/ui-kit/ios/call-logs) - Display call history From b7dce266f61d9ed55fb3716e6746540c5cd36504 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 13:13:02 +0530 Subject: [PATCH 083/106] minor fixes --- ui-kit/ios/color-resources.mdx | 4 +--- ui-kit/ios/component-styling.mdx | 4 +--- ui-kit/ios/message-bubble-styling.mdx | 4 ++-- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/ui-kit/ios/color-resources.mdx b/ui-kit/ios/color-resources.mdx index 79d12bc23..35bb66cbf 100644 --- a/ui-kit/ios/color-resources.mdx +++ b/ui-kit/ios/color-resources.mdx @@ -316,9 +316,7 @@ extension UIColor { ---- - ---- +--- ## Related diff --git a/ui-kit/ios/component-styling.mdx b/ui-kit/ios/component-styling.mdx index e866e3b8a..02aa02758 100644 --- a/ui-kit/ios/component-styling.mdx +++ b/ui-kit/ios/component-styling.mdx @@ -546,9 +546,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { ---- - ---- +--- ## Related diff --git a/ui-kit/ios/message-bubble-styling.mdx b/ui-kit/ios/message-bubble-styling.mdx index c7a60e5d9..f83a18a70 100644 --- a/ui-kit/ios/message-bubble-styling.mdx +++ b/ui-kit/ios/message-bubble-styling.mdx @@ -371,7 +371,7 @@ CometChatMessageBubble.style.outgoing.aiAssistantBubbleStyle.backgroundColor = U -**Default** +{/* **Default** @@ -381,7 +381,7 @@ CometChatMessageBubble.style.outgoing.aiAssistantBubbleStyle.backgroundColor = U - + */} --- From bec6e8e349b7bd71002ad3c5e1b19236c2082874 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 13:45:51 +0530 Subject: [PATCH 084/106] lines --- ui-kit/ios/ai-assistant-chat-history.mdx | 26 ++-- ui-kit/ios/ai-features.mdx | 14 +- ui-kit/ios/call-buttons.mdx | 28 ++-- ui-kit/ios/call-features.mdx | 26 ++-- ui-kit/ios/call-logs.mdx | 54 ++++---- ui-kit/ios/color-resources.mdx | 10 +- ui-kit/ios/component-styling.mdx | 32 ++--- ui-kit/ios/components-overview.mdx | 16 +-- ui-kit/ios/conversations.mdx | 112 ++++++++-------- ui-kit/ios/core-features.mdx | 30 ++--- ui-kit/ios/events.mdx | 26 ++-- ui-kit/ios/group-members.mdx | 84 ++++++------ ui-kit/ios/groups.mdx | 84 ++++++------ ui-kit/ios/guide-ai-agent.mdx | 18 +-- ui-kit/ios/guide-block-unblock-user.mdx | 14 +- ui-kit/ios/guide-call-log-details.mdx | 14 +- ui-kit/ios/guide-group-chat.mdx | 18 +-- ui-kit/ios/guide-group-ownership.mdx | 18 +-- ui-kit/ios/guide-message-privately.mdx | 10 +- ui-kit/ios/guide-new-chat.mdx | 16 +-- ui-kit/ios/guide-threaded-messages.mdx | 20 +-- ui-kit/ios/incoming-call.mdx | 42 +++--- ui-kit/ios/localize.mdx | 12 +- ui-kit/ios/mentions-formatter-guide.mdx | 12 +- ui-kit/ios/message-bubble-styling.mdx | 22 +-- ui-kit/ios/message-composer.mdx | 84 ++++++------ ui-kit/ios/message-header.mdx | 72 +++++----- ui-kit/ios/message-list.mdx | 162 +++++++++++------------ ui-kit/ios/message-template.mdx | 52 ++++---- ui-kit/ios/methods.mdx | 22 +-- ui-kit/ios/ongoing-call.mdx | 20 +-- ui-kit/ios/outgoing-call.mdx | 42 +++--- ui-kit/ios/search.mdx | 46 +++---- ui-kit/ios/shortcut-formatter-guide.mdx | 20 +-- ui-kit/ios/sound-manager.mdx | 10 +- ui-kit/ios/theme-introduction.mdx | 4 +- ui-kit/ios/threaded-messages-header.mdx | 22 +-- ui-kit/ios/users.mdx | 96 +++++++------- 38 files changed, 705 insertions(+), 705 deletions(-) diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index a0c011ed8..69fdaed7a 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -62,7 +62,7 @@ Go to [CometChat Dashboard](https://app.cometchat.com) → AI → Enable AI feat -```swift +```swift lines import CometChatUIKitSwift let uikitSettings = UIKitSettings() @@ -89,7 +89,7 @@ CometChatUIKit.init(uiKitSettings: uikitSettings) { result in -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -121,7 +121,7 @@ Complete implementation with all features: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -308,7 +308,7 @@ class AIAssistantViewController: UIViewController { -```swift +```swift lines let chatHistory = CometChatAIAssistanceChatHistory() chatHistory.user = user @@ -326,7 +326,7 @@ chatHistory.set(loadingView: loadingView) -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -425,7 +425,7 @@ chatHistory.set(emptyView: emptyView) -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -528,7 +528,7 @@ Customize which messages are displayed: -```swift +```swift lines import CometChatSDK import CometChatUIKitSwift @@ -560,7 +560,7 @@ These parameters are **always overridden** by the component: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -633,7 +633,7 @@ class MainTabBarController: UITabBarController { -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -748,7 +748,7 @@ Show AI chat history when user taps a button in their profile: -```swift +```swift lines @objc func showAIChatHistory() { guard let currentUser = CometChat.getLoggedInUser() else { return } @@ -773,7 +773,7 @@ Navigate to the full conversation when a message is tapped: -```swift +```swift lines let chatHistory = CometChatAIAssistanceChatHistory() chatHistory.user = user @@ -793,7 +793,7 @@ Format dates to show relative time for recent conversations: -```swift +```swift lines let chatHistory = CometChatAIAssistanceChatHistory() chatHistory.user = user @@ -828,7 +828,7 @@ Add AI chat history as a dedicated tab: -```swift +```swift lines class MainTabBarController: UITabBarController { override func viewDidLoad() { diff --git a/ui-kit/ios/ai-features.mdx b/ui-kit/ios/ai-features.mdx index 73eb5b61b..fbb20b85e 100644 --- a/ui-kit/ios/ai-features.mdx +++ b/ui-kit/ios/ai-features.mdx @@ -84,7 +84,7 @@ Conversation starters appear automatically in `CometChatMessages`: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -134,7 +134,7 @@ Smart replies appear automatically in `CometChatMessageComposer`: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -178,7 +178,7 @@ Conversation summary is available automatically: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -209,7 +209,7 @@ View and continue conversations with AI assistants. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -233,7 +233,7 @@ class AIAssistantViewController: UIViewController { -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -293,7 +293,7 @@ class AIAssistantViewController: UIViewController { -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -341,7 +341,7 @@ Full implementation showing all AI features: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK diff --git a/ui-kit/ios/call-buttons.mdx b/ui-kit/ios/call-buttons.mdx index 09e236b6c..06820f1e0 100644 --- a/ui-kit/ios/call-buttons.mdx +++ b/ui-kit/ios/call-buttons.mdx @@ -60,7 +60,7 @@ Since `CometChatCallButton` is a **custom view**, it offers flexibility in integ -```swift +```swift lines let user = User(uid: "your-uid", name: "") let cometChatCallButton = CometChatCallButtons(width: 24, height: 24) @@ -84,7 +84,7 @@ The `setOnVoiceCallClick` action is usually invoked when a voice call is initiat -```swift +```swift lines let cometChatCallButton = CometChatCallButtons(width: 24, height: 24) .set(onVoiceCallClick: { user, group in //Perform Your Action @@ -101,7 +101,7 @@ The `setOnVideoCallClick` action is typically triggered when a video call is ini -```swift +```swift lines let cometChatCallButton = CometChatCallButtons(width: 24, height: 24) .set(onVideoCallClick: { user, group in //Perform Your Action @@ -119,7 +119,7 @@ You can customize this behavior by using the provided code snippet to override t -```swift +```swift lines let cometChatCallButton = CometChatCallButtons(width: 24, height: 24) .set(onError: { error in //Perform Your Action @@ -154,7 +154,7 @@ Events emitted by the Call buttons component is as follows. -```swift +```swift lines // View controller from your project where you want to listen events. public class ViewController: UIViewController { @@ -231,7 +231,7 @@ You can customize the appearance of the `CallButtons` Component by applying the -```swift +```swift lines CometChatCallButtons.style.audioCallButtonBackground = UIColor(hex: "#EDEAFA") CometChatCallButtons.style.audioCallIconTint = UIColor(hex: "#6852D6") CometChatCallButtons.style.videoCallButtonBackground = UIColor(hex: "#EDEAFA") @@ -246,7 +246,7 @@ CometChatCallButtons.style.videoCallIconTint = UIColor(hex: "#6852D6") -```swift +```swift lines let callButtonStyle = CallButtonStyle() callButtonStyle.audioCallButtonBackground = UIColor(hex: "#EDEAFA") callButtonStyle.audioCallIconTint = UIColor(hex: "#6852D6") @@ -326,7 +326,7 @@ You can customize the properties of the Outgoing Call component by making use of -```swift +```swift lines // Create an object of OutgoingCallConfiguration let outgoingCallConfiguration = OutgoingCallConfiguration() ``` @@ -345,7 +345,7 @@ You can modify the style using the `OutgoingCallStyle` property, disable sound f -```swift +```swift lines let outgoingCallConfiguration = OutgoingCallConfiguration() .disable(soundForCalls: true) @@ -366,7 +366,7 @@ To ensure that the `CallButtons` is properly configured, passing the controller * Swift -```swift +```swift lines let callButtons = CometChatCallButtons(width: 24, height: 24) callButtons.set(controller: UIViewController) // Passing the controller is required ``` @@ -467,7 +467,7 @@ Integrate call buttons into a custom message header: -```swift +```swift lines class CustomMessageHeader: UIView { private var callButtons: CometChatCallButtons! @@ -492,7 +492,7 @@ Show only the voice call button for audio-focused apps: -```swift +```swift lines let callButtons = CometChatCallButtons(width: 24, height: 24) callButtons.set(user: user) callButtons.hideVideoCallButton = true @@ -507,7 +507,7 @@ Show confirmation before starting a call: -```swift +```swift lines let callButtons = CometChatCallButtons(width: 24, height: 24) callButtons.set(user: user) callButtons.set(onVoiceCallClick: { [weak self] user, group in @@ -533,7 +533,7 @@ Configure call buttons for group video calls: -```swift +```swift lines let callButtons = CometChatCallButtons(width: 24, height: 24) callButtons.set(group: group) callButtons.hideVoiceCallButton = true // Groups often use video calls diff --git a/ui-kit/ios/call-features.mdx b/ui-kit/ios/call-features.mdx index 50321f3d5..1505803e6 100644 --- a/ui-kit/ios/call-features.mdx +++ b/ui-kit/ios/call-features.mdx @@ -69,7 +69,7 @@ Add to `Info.plist`: In `SceneDelegate.swift`: -```swift +```swift lines import CometChatUIKitSwift func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { @@ -114,7 +114,7 @@ Complete app with calling, chat, and call history: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -176,7 +176,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -277,7 +277,7 @@ class MainTabBarController: UITabBarController { -```swift +```swift lines import CometChatSDK func startVoiceCall(to userUID: String) { @@ -304,7 +304,7 @@ startVoiceCall(to: "cometchat-uid-2") -```swift +```swift lines import CometChatSDK func startVideoCall(to userUID: String) { @@ -331,7 +331,7 @@ startVideoCall(to: "cometchat-uid-2") -```swift +```swift lines import CometChatSDK func startGroupCall(to groupGUID: String, type: CometChat.CallType) { @@ -362,7 +362,7 @@ Add call buttons anywhere in your app: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -465,7 +465,7 @@ The built-in call buttons component: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -515,7 +515,7 @@ Incoming calls are handled automatically. For custom handling: -```swift +```swift lines import CometChatSDK class CallHandler: NSObject, CometChatCallDelegate { @@ -576,7 +576,7 @@ class CallHandler: NSObject, CometChatCallDelegate { Renders voice and video call buttons. -```swift +```swift lines let callButtons = CometChatCallButtons() callButtons.user = user // or callButtons.group = group @@ -590,7 +590,7 @@ callButtons.set(onError: { error in }) Displays incoming call screen with accept/reject options. -```swift +```swift lines let incomingCall = CometChatIncomingCall() incomingCall.set(call: call) @@ -602,7 +602,7 @@ incomingCall.set(onDeclineClick: { call in }) Displays outgoing call screen while waiting for answer. -```swift +```swift lines let outgoingCall = CometChatOutgoingCall() outgoingCall.set(call: call) @@ -613,7 +613,7 @@ outgoingCall.set(onCancelClick: { call in }) Displays call history. See [Call Logs](/ui-kit/ios/call-logs) for full documentation. -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.set(onItemClick: { callLog in }) ``` diff --git a/ui-kit/ios/call-logs.mdx b/ui-kit/ios/call-logs.mdx index 8713d3c17..098d0a86a 100644 --- a/ui-kit/ios/call-logs.mdx +++ b/ui-kit/ios/call-logs.mdx @@ -77,7 +77,7 @@ The `Call Logs` component is composed of the following BaseComponents: -```swift +```swift lines // To navigate to the CometChatCallLogs let callLogs = CometChatCallLogs() self.navigationController?.pushViewController(callLogs, animated: true) @@ -97,7 +97,7 @@ self.navigationController?.pushViewController(callLogs, animated: true) -```swift +```swift lines // syntax for set(onItemClick: ((_ callLog: Any) -> ())?) // Note: callLog is of type CometChatCallsSDK.CallLog, cast it to access properties cometChatCallLogs.set(onItemClick: { callLog in @@ -119,7 +119,7 @@ cometChatCallLogs.set(onItemClick: { callLog in -```swift +```swift lines // syntax for set(onItemLongClick: ((_ callLog: Any, _ indexPath: IndexPath) -> ())?) // Note: callLog is of type CometChatCallsSDK.CallLog, cast it to access properties cometChatCallLogs.set(onItemLongClick: { callLog, indexPath in @@ -141,7 +141,7 @@ This `set(onBack:)` method becomes valuable when a user needs to override the ac -```swift +```swift lines cometChatCallLogs.set(onBack: { // Override on back }) @@ -159,7 +159,7 @@ This method proves helpful when a user needs to customize the action taken upon -```swift +```swift lines cometChatCallLogs.set(onError: { error in // Override on error }) @@ -177,7 +177,7 @@ This `set(onEmpty:)` method is triggered when the call logs list is empty in Com -```swift +```swift lines cometChatCallLogs.set(onEmpty: { }) @@ -195,7 +195,7 @@ This set(onLoad:) method is triggered when call logs are successfully loaded in -```swift +```swift lines cometChatCallLogs.set(onLoad: { callLogs in }) ``` @@ -234,7 +234,7 @@ In the example below, we are applying a filter based on limit , calltype and cal -```swift +```swift lines let callRequestBuilder = CallLogsRequest.CallLogsBuilder() .set(limit: 2) @@ -278,7 +278,7 @@ You can customize the appearance of the `CallLog` Component by applying the `Cal -```swift +```swift lines let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) @@ -296,7 +296,7 @@ CometChatCallLogs.avatarStyle = customAvatarStyle -```swift +```swift lines let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 20) @@ -416,7 +416,7 @@ This enables developers to localize, format, or personalize the date and time st -```swift +```swift lines CometChatCallLogs.dateTimeFormatter.time = { timestamp in return "at " + DateFormatter.localizedString(from: Date(timeIntervalSince1970: TimeInterval(timestamp)), dateStyle: .none, timeStyle: .short) } @@ -440,7 +440,7 @@ CometChatCallLogs.dateTimeFormatter.otherDay = { timestamp in // This will displ -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.dateTimeFormatter.yesterday = { timestamp in return "Yesterday at " + formattedTime(from: timestamp) @@ -475,7 +475,7 @@ With this function, you can assign a custom ListItem to the CallLogs Component. -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.set(listItemView: { callLog in let view = CustomListItem() @@ -493,7 +493,7 @@ callLogs.set(listItemView: { callLog in -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatCallsSDK @@ -586,7 +586,7 @@ You can create a custom Title view for more complex or unique list items and int -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.set(titleView: { callLog in let view = CustomTitleView() @@ -607,7 +607,7 @@ callLogs.set(titleView: { callLog in -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -709,7 +709,7 @@ You can create a custom Title view for more complex or unique list items and int -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.set(leadingView: { callLog in let view = CustomLeadingView() @@ -730,7 +730,7 @@ callLogs.set(leadingView: { callLog in -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -800,7 +800,7 @@ Afterwards, seamlessly integrate this `SubtitleView` UIView file into the `.setS -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.set(subtitleView: { callLog in let view = CustomSubtitleView() @@ -820,7 +820,7 @@ callLogs.set(subtitleView: { callLog in -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -886,7 +886,7 @@ Afterwards, seamlessly integrate this `CustomTrailView` UIView file into the `.s -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.set(trailView: { callLog in let view = CustomTrailView() @@ -906,7 +906,7 @@ callLogs.set(trailView: { callLog in -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -1034,7 +1034,7 @@ Customizes the appearance of avatars in the call logs list. | Type | `AvatarStyle` | | Default | `AvatarStyle()` | -```swift +```swift lines import CometChatUIKitSwift let customAvatarStyle = AvatarStyle() @@ -1090,7 +1090,7 @@ Add call logs as a tab in your main navigation: -```swift +```swift lines class MainTabBarController: UITabBarController { override func viewDidLoad() { @@ -1117,7 +1117,7 @@ Handle call log selection to initiate a callback: -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.set(onItemClick: { [weak self] callLog, indexPath in // Get the other participant @@ -1152,7 +1152,7 @@ Show only missed calls or specific call types: -```swift +```swift lines // Show only missed calls let missedCallsBuilder = CallLogsRequest.CallLogsBuilder() .set(callStatus: .unanswered) @@ -1175,7 +1175,7 @@ Show a custom view when there are no call logs: -```swift +```swift lines let callLogs = CometChatCallLogs() callLogs.set(onEmpty: { [weak self] in diff --git a/ui-kit/ios/color-resources.mdx b/ui-kit/ios/color-resources.mdx index 35bb66cbf..9e4bd68de 100644 --- a/ui-kit/ios/color-resources.mdx +++ b/ui-kit/ios/color-resources.mdx @@ -57,7 +57,7 @@ CometChat UI Kit uses `CometChatTheme` to manage colors across all components. C -```swift +```swift lines import CometChatUIKitSwift // Primary brand color @@ -91,7 +91,7 @@ let iconSecondary = CometChatTheme.iconColorSecondary -```swift +```swift lines import CometChatUIKitSwift // Set your brand color globally @@ -110,7 +110,7 @@ CometChatTheme.primaryColor = UIColor(hex: "#FF5722") // Orange brand -```swift +```swift lines import CometChatUIKitSwift class ThemeManager { @@ -159,7 +159,7 @@ CometChat automatically adapts to system appearance. You can also customize dark -```swift +```swift lines import CometChatUIKitSwift import UIKit @@ -240,7 +240,7 @@ Complete app with custom branding: -```swift +```swift lines import UIKit import CometChatUIKitSwift diff --git a/ui-kit/ios/component-styling.mdx b/ui-kit/ios/component-styling.mdx index 02aa02758..8e6fc6d0a 100644 --- a/ui-kit/ios/component-styling.mdx +++ b/ui-kit/ios/component-styling.mdx @@ -32,7 +32,7 @@ Apply once, affects all instances of a component: -```swift +```swift lines import CometChatUIKitSwift // Set before using any components (e.g., in AppDelegate) @@ -49,7 +49,7 @@ Apply to a specific component instance: -```swift +```swift lines import CometChatUIKitSwift let style = ConversationsStyle() @@ -75,7 +75,7 @@ conversations.style = style -```swift +```swift lines import CometChatUIKitSwift // Create custom styles @@ -121,7 +121,7 @@ conversations.style.listItemBackground = .systemBackground -```swift +```swift lines import CometChatUIKitSwift // Avatar style @@ -162,7 +162,7 @@ users.style.backgroundColor = .systemBackground -```swift +```swift lines import CometChatUIKitSwift // Avatar style for group icons @@ -196,7 +196,7 @@ groups.style.backgroundColor = .systemBackground -```swift +```swift lines import CometChatUIKitSwift // Avatar style @@ -226,7 +226,7 @@ CometChatMessageHeader.avatarStyle = avatarStyle -```swift +```swift lines import CometChatUIKitSwift // Background color @@ -261,7 +261,7 @@ CometChatMessageList.style.timestampTextFont = UIFont.systemFont(ofSize: 11) -```swift +```swift lines import CometChatUIKitSwift // Send button @@ -299,7 +299,7 @@ CometChatMessageComposer.style.borderColor = UIColor(hex: "#E8E8E8") -```swift +```swift lines import CometChatUIKitSwift // Avatar style @@ -336,7 +336,7 @@ CometChatCallLogs.avatarStyle = avatarStyle -```swift +```swift lines import CometChatUIKitSwift // Instance styling @@ -365,7 +365,7 @@ CometChatSearch.style.listItemBackground = UIColor(hex: "#EDEAFA") -```swift +```swift lines import CometChatUIKitSwift // Date separator style @@ -394,7 +394,7 @@ CometChatAIAssistantChatHistory.style.dateSeparatorStyle = dateStyle -```swift +```swift lines let avatarStyle = AvatarStyle() avatarStyle.backgroundColor = UIColor(hex: "#6200EE") avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 24) // Circle @@ -412,7 +412,7 @@ avatarStyle.textColor = .white -```swift +```swift lines let badgeStyle = BadgeStyle() badgeStyle.backgroundColor = UIColor(hex: "#F44336") badgeStyle.textColor = .white @@ -429,7 +429,7 @@ badgeStyle.borderWidth = 0 -```swift +```swift lines let statusStyle = StatusIndicatorStyle() statusStyle.backgroundColor = .systemGreen // Online color statusStyle.borderColor = .white @@ -445,7 +445,7 @@ statusStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 6) // Circle -```swift +```swift lines let receiptStyle = ReceiptStyle() receiptStyle.sentIconTint = UIColor(hex: "#9E9E9E") receiptStyle.deliveredIconTint = UIColor(hex: "#9E9E9E") @@ -465,7 +465,7 @@ Apply consistent branding across all components: -```swift +```swift lines import CometChatUIKitSwift import UIKit diff --git a/ui-kit/ios/components-overview.mdx b/ui-kit/ios/components-overview.mdx index 420828875..7c7e5d6c7 100644 --- a/ui-kit/ios/components-overview.mdx +++ b/ui-kit/ios/components-overview.mdx @@ -63,7 +63,7 @@ Simple UI elements with no business logic. They display data you pass to them. -```swift +```swift lines import CometChatUIKitSwift // Avatar - displays user image @@ -99,7 +99,7 @@ UI elements with built-in business logic. They fetch data, handle actions, and e -```swift +```swift lines import CometChatUIKitSwift // Users list - fetches and displays users automatically @@ -136,7 +136,7 @@ Combine multiple components into complete features. -```swift +```swift lines import CometChatUIKitSwift // Complete chat experience in one component @@ -163,7 +163,7 @@ Built-in behaviors that work automatically: -```swift +```swift lines // CometChatConversations has predefined actions: // - Tap conversation → Opens messages // - Long press → Shows options @@ -181,7 +181,7 @@ Override default behavior with your own logic: -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -242,7 +242,7 @@ Events allow components to communicate without direct references. Subscribe to e -```swift +```swift lines import CometChatUIKitSwift import Combine @@ -297,7 +297,7 @@ Customize nested components within composite components: -```swift +```swift lines import CometChatUIKitSwift // CometChatMessages contains: MessageHeader, MessageList, MessageComposer @@ -376,7 +376,7 @@ CometChatConversationsWithMessages -```swift +```swift lines // Pattern 1: Quick integration with composite let chat = CometChatConversationsWithMessages() navigationController?.pushViewController(chat, animated: true) diff --git a/ui-kit/ios/conversations.mdx b/ui-kit/ios/conversations.mdx index ca37fb595..b233cf8a5 100644 --- a/ui-kit/ios/conversations.mdx +++ b/ui-kit/ios/conversations.mdx @@ -116,7 +116,7 @@ The `CometChatConversations` component displays a list of all conversations (one `CometChatConversations` serves as the main entry point for chat functionality. It displays all conversations and navigates to `CometChatMessages` when a conversation is selected. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -163,7 +163,7 @@ class ChatListViewController: UIViewController { ## Minimal Render -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -180,7 +180,7 @@ navigationController?.pushViewController(conversations, animated: true) Use `ConversationRequest.ConversationRequestBuilder` to filter which conversations appear in the list. The builder pattern allows chaining multiple filter conditions. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -211,7 +211,7 @@ let conversations = CometChatConversations(conversationRequestBuilder: requestBu Fires when a user taps on a conversation. Use this to navigate to the messages screen. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -236,7 +236,7 @@ conversations.set(onItemClick: { [weak self] conversation, indexPath in Fires when a user long-presses on a conversation. Use this to show additional options like delete or mute. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -272,7 +272,7 @@ private func deleteConversation(_ conversation: Conversation) { Fires when the back button is pressed. Use this for custom navigation handling. -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -286,7 +286,7 @@ conversations.set(onBack: { [weak self] in Fires when conversations are selected in selection mode. Returns the list of selected conversations. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -302,7 +302,7 @@ conversations.set(onSelection: { [weak self] selectedConversations in Fires when an error occurs while loading conversations. -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -316,7 +316,7 @@ conversations.set(onError: { error in Fires when the conversation list is empty. -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -330,7 +330,7 @@ conversations.set(onEmpty: { Fires when conversations are successfully loaded. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -359,7 +359,7 @@ conversations.set(onLoad: { conversations in |-------|------------|---------| | `ccConversationDelete` | A conversation is deleted | `Conversation` | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -414,7 +414,7 @@ class MyViewController: UIViewController, CometChatConversationEventListener { Replace the entire conversation row with a custom design. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -428,7 +428,7 @@ conversations.set(listItemView: { conversation in }) ``` -```swift +```swift lines // CustomConversationCell.swift class CustomConversationCell: UIView { @@ -476,7 +476,7 @@ class CustomConversationCell: UIView { Customize just the subtitle area below the conversation name. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -509,7 +509,7 @@ Customize the avatar / left section of the conversation row. | Signature | `(Conversation) -> UIView` | | Replaces | Avatar / left section | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -564,7 +564,7 @@ Customize the title area that displays the conversation name. | Signature | `(Conversation) -> UIView` | | Replaces | Name / title text area | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -610,7 +610,7 @@ conversations.set(titleView: { conversation in Customize the right side of the conversation row (time, unread badge). Note: The setter method is `set(trailView:)`. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -669,7 +669,7 @@ conversations.set(trailView: { conversation in ### Global Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -695,7 +695,7 @@ CometChatConversation.style.badgeStyle = badgeStyle ### Instance Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -753,7 +753,7 @@ conversations.style = customStyle Sets custom swipe actions for conversation list items, replacing the default options. -```swift +```swift lines @discardableResult public func set(options: ((_ conversation: Conversation?) -> [CometChatConversationOption])?) -> Self ``` @@ -762,7 +762,7 @@ public func set(options: ((_ conversation: Conversation?) -> [CometChatConversat |-----------|------|-------------| | `options` | `((Conversation?) -> [CometChatConversationOption])?` | Closure that returns an array of swipe action options for a conversation | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -792,7 +792,7 @@ conversations.set(options: { conversation in Adds additional swipe actions to the existing default options. -```swift +```swift lines @discardableResult public func add(options: ((_ conversation: Conversation?) -> [CometChatConversationOption])?) -> Self ``` @@ -801,7 +801,7 @@ public func add(options: ((_ conversation: Conversation?) -> [CometChatConversat |-----------|------|-------------| | `options` | `((Conversation?) -> [CometChatConversationOption])?` | Closure that returns additional swipe action options to append | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -834,7 +834,7 @@ conversations.add(options: { conversation in Inserts a conversation at a specific index in the list. -```swift +```swift lines public func insert(conversation: Conversation, at index: Int) ``` @@ -843,7 +843,7 @@ public func insert(conversation: Conversation, at index: Int) | `conversation` | `Conversation` | The conversation to insert | | `index` | `Int` | The position at which to insert the conversation | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -859,11 +859,11 @@ if let conversation = someConversation { Returns the list of currently selected conversations when in selection mode. -```swift +```swift lines public func getSelectedConversations() -> [Conversation] ``` -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -879,11 +879,11 @@ print("Selected \(selectedConversations.count) conversations") Returns the complete list of conversations currently displayed. -```swift +```swift lines public func getConversationList() -> [Conversation] ``` -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -900,11 +900,11 @@ print("Total conversations: \(allConversations.count)") Manually establishes the WebSocket connection for real-time updates. Use this when you need to reconnect after calling `disconnect()`. -```swift +```swift lines public func connect() ``` -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -917,11 +917,11 @@ conversations.connect() Manually disconnects the WebSocket connection. Use this when you want to temporarily stop receiving real-time updates, such as when the view is not visible. -```swift +```swift lines public func disconnect() ``` -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -939,7 +939,7 @@ conversations.connect() Sets custom text formatters for processing and displaying message text in conversation subtitles. -```swift +```swift lines @discardableResult public func set(textFormatters: [CometChatTextFormatter]) -> Self ``` @@ -948,7 +948,7 @@ public func set(textFormatters: [CometChatTextFormatter]) -> Self |-----------|------|-------------| | `textFormatters` | `[CometChatTextFormatter]` | Array of text formatters to apply to message text | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -975,7 +975,7 @@ Customizes the appearance of avatars in conversation list items. | Type | `AvatarStyle` | | Default | `AvatarStyle()` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -998,7 +998,7 @@ Customizes the appearance of unread message count badges. | Type | `BadgeStyle` | | Default | `BadgeStyle()` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1030,7 +1030,7 @@ Customizes the appearance of date/time labels in conversation list items. | Type | `DateStyle` | | Default | `DateStyle()` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1051,7 +1051,7 @@ Custom formatter for date/time display in conversation list items. | Type | `CometChatDateTimeFormatter?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1091,7 +1091,7 @@ Disables typing indicators in the conversation list. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1170,7 +1170,7 @@ Callback triggered when the search button is clicked. | Type | `(() -> Void)?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1190,7 +1190,7 @@ Custom icon for private group conversations. | Type | `UIImage?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1206,7 +1206,7 @@ Custom icon for password-protected group conversations. | Type | `UIImage?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1222,7 +1222,7 @@ Customizes the appearance of message receipt indicators (sent, delivered, read). | Type | `ReceiptStyle` | | Default | `ReceiptStyle()` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1253,7 +1253,7 @@ Customizes the appearance of online/offline status indicators. | Type | `StatusIndicatorStyle` | | Default | `StatusIndicatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1284,7 +1284,7 @@ Customizes the appearance of typing indicators in conversation list items. | Type | `TypingIndicatorStyle` | | Default | `TypingIndicatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1312,7 +1312,7 @@ Customize how timestamps appear in the conversation list using the `datePattern` ### Global Level Formatting -```swift +```swift lines import CometChatUIKitSwift // Set a global date pattern for all conversations instances @@ -1336,7 +1336,7 @@ CometChatConversations.datePattern = { conversation in ### Instance Level Formatting -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1369,7 +1369,7 @@ conversations.set(datePattern: { conversation in ### Common Customizations -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1403,7 +1403,7 @@ Configure how @all mentions appear in conversation list items. When a message co Sets a custom label for @all mentions displayed in conversation list items. -```swift +```swift lines @discardableResult public func setMentionAllLabel(_ id: String, _ label: String) -> Self ``` @@ -1413,7 +1413,7 @@ public func setMentionAllLabel(_ id: String, _ label: String) -> Self | `id` | `String` | The identifier for the @all mention (typically "all") | | `label` | `String` | The display text shown to users when @all is mentioned | -```swift +```swift lines import CometChatUIKitSwift let conversations = CometChatConversations() @@ -1422,7 +1422,7 @@ let conversations = CometChatConversations() conversations.setMentionAllLabel("all", "Everyone") ``` -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -1463,7 +1463,7 @@ class MentionConfiguredViewController: UIViewController { Full implementation with tab bar showing CometChatConversations in a real app: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -1531,7 +1531,7 @@ class ConversationsContainerViewController: UINavigationController { ### Custom empty state with CTA -```swift +```swift lines let conversations = CometChatConversations() conversations.set(emptyStateView: { @@ -1553,7 +1553,7 @@ conversations.set(emptyStateView: { ### Hide all chrome — minimal list -```swift +```swift lines let conversations = CometChatConversations() conversations.hideReceipts = true conversations.hideUserStatus = true @@ -1563,7 +1563,7 @@ conversations.hideDeleteConversationOption = true ### Filter by conversation type -```swift +```swift lines // Only user conversations let userOnlyBuilder = ConversationRequest.ConversationRequestBuilder(limit: 30) .set(conversationType: .user) diff --git a/ui-kit/ios/core-features.mdx b/ui-kit/ios/core-features.mdx index f5023a6e1..38d41039e 100644 --- a/ui-kit/ios/core-features.mdx +++ b/ui-kit/ios/core-features.mdx @@ -34,7 +34,7 @@ Send and receive text messages in real-time. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -69,7 +69,7 @@ class ChatViewController: UIViewController { Share images, videos, audio files, and documents. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -132,7 +132,7 @@ Show when messages are delivered and read. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -185,7 +185,7 @@ Let users mark messages as unread to revisit later. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -231,7 +231,7 @@ Show when users are typing in real-time. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -288,7 +288,7 @@ Display online/offline status for users. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -337,7 +337,7 @@ Let users react to messages with emojis. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -396,7 +396,7 @@ Tag users in messages with @mentions. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -449,7 +449,7 @@ Reply to specific messages in threads. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -556,7 +556,7 @@ Create and manage group conversations. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -633,7 +633,7 @@ Reply to specific messages with context. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -668,7 +668,7 @@ Search across conversations and messages. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -712,7 +712,7 @@ Automatically filter inappropriate content. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -754,7 +754,7 @@ Allow users to report inappropriate messages. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -789,7 +789,7 @@ View and manage reported messages in [Flagged Messages](/moderation/flagged-mess Here's a production-ready implementation combining all core features: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK diff --git a/ui-kit/ios/events.mdx b/ui-kit/ios/events.mdx index e28e3ca03..cfeb45a75 100644 --- a/ui-kit/ios/events.mdx +++ b/ui-kit/ios/events.mdx @@ -80,7 +80,7 @@ Events allow different parts of your app to communicate without direct dependenc 2. **React** to events in your listener callback methods 3. **Unsubscribe** using `removeListener` in `viewWillDisappear` -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -117,7 +117,7 @@ class MyViewController: UIViewController { Listen for user-related actions like blocking and unblocking. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -153,7 +153,7 @@ extension UserEventsViewController: CometChatUserEventListener { Notify other components when you block/unblock a user: -```swift +```swift lines // After blocking a user CometChatUserEvents.ccUserBlocked(user: blockedUser) @@ -172,7 +172,7 @@ CometChatUserEvents.ccUserUnblocked(user: unblockedUser) Listen for group-related actions like creating groups, adding members, and role changes. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -246,7 +246,7 @@ extension GroupEventsViewController: CometChatGroupEventListener { Notify other components about group actions: -```swift +```swift lines // Group created CometChatGroupEvents.emitOnGroupCreate(group: newGroup) @@ -301,7 +301,7 @@ CometChatGroupEvents.emitOnGroupMemberChangeScope( Listen for conversation-level actions like delete and update. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -335,7 +335,7 @@ extension ConversationEventsViewController: CometChatConversationEventListener { ### Emit Conversation Events -```swift +```swift lines // Conversation deleted CometChatConversationEvents.ccConversationDelete(conversation: deletedConversation) @@ -354,7 +354,7 @@ CometChatConversationEvents.ccUpdateConversation(conversation: updatedConversati Listen for message-related actions like send, edit, delete, and reactions. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -453,7 +453,7 @@ extension MessageEventsViewController: CometChatMessageEventListener { ### Emit Message Events -```swift +```swift lines // Message sent (with status) CometChatMessageEvents.emitOnMessageSent(message: sentMessage, status: .success) @@ -497,7 +497,7 @@ CometChatMessageEvents.emitOnParentMessageUpdate(message: parentMessage) Listen for call-related actions like initiating, accepting, and ending calls. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -548,7 +548,7 @@ extension CallEventsViewController: CometChatCallEventListener { ### Emit Call Events -```swift +```swift lines // Call initiated CometChatCallEvents.emitOnCallInitiated(call: outgoingCall) @@ -583,7 +583,7 @@ CometChatCallEvents.emitOnOutgoingCallRejected(call: rejectedCall) Create a centralized event manager to handle events across your entire app: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -724,7 +724,7 @@ extension Notification.Name { ### Using the Event Manager -```swift +```swift lines // AppDelegate.swift class AppDelegate: UIResponder, UIApplicationDelegate { diff --git a/ui-kit/ios/group-members.mdx b/ui-kit/ios/group-members.mdx index 38e5f0420..d597d9d0e 100644 --- a/ui-kit/ios/group-members.mdx +++ b/ui-kit/ios/group-members.mdx @@ -141,7 +141,7 @@ The `CometChatGroupMembers` component displays all members of a group with their `CometChatGroupMembers` displays all members of a specific group. It's typically accessed from group details or settings screens. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -183,7 +183,7 @@ class GroupDetailViewController: UIViewController { ## Minimal Render -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -202,7 +202,7 @@ present(navController, animated: true) Use `GroupMembersRequest.GroupMembersRequestBuilder` to filter which members appear in the list. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -236,7 +236,7 @@ let groupMembers = CometChatGroupMembers( Fires when a user taps on a member. Use this to start a direct chat or view profile. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -255,7 +255,7 @@ groupMembers.set(onItemClick: { [weak self] member, indexPath in Fires when a user long-presses on a member. Use this to show member options. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -283,7 +283,7 @@ groupMembers.set(onItemLongClick: { [weak self] member, indexPath in Fires when the back button is pressed. -```swift +```swift lines import CometChatUIKitSwift let groupMembers = CometChatGroupMembers(group: group) @@ -297,7 +297,7 @@ groupMembers.set(onBack: { [weak self] in Fires when members are selected in selection mode. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -313,7 +313,7 @@ groupMembers.set(onSelection: { [weak self] selectedMembers in Fires when an error occurs while loading members. -```swift +```swift lines import CometChatUIKitSwift let groupMembers = CometChatGroupMembers(group: group) @@ -327,7 +327,7 @@ groupMembers.set(onError: { error in Fires when the member list is empty. -```swift +```swift lines import CometChatUIKitSwift let groupMembers = CometChatGroupMembers(group: group) @@ -341,7 +341,7 @@ groupMembers.set(onEmpty: { Fires when members are successfully loaded. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -372,7 +372,7 @@ groupMembers.set(onLoad: { members in | `ccGroupMemberBanned` | A member is banned | `User, Group` | | `ccGroupMemberScopeChanged` | A member's role is changed | `User, Group, MemberScope` | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -436,7 +436,7 @@ Replaces the default title view (member name) with a custom implementation. | Signature | `(GroupMember?) -> UIView` | | Replaces | Member name / title text | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -500,7 +500,7 @@ Replaces the default leading view (avatar) with a custom implementation. | Signature | `(GroupMember?) -> UIView` | | Replaces | Avatar / left section | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -568,7 +568,7 @@ groupMembers.set(leadingView: { member in Customize the subtitle area below the member name. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -597,7 +597,7 @@ groupMembers.set(subtitleView: { member in Customize the right side of the member row (role badge). Note: The setter method is `set(trailView:)`. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -649,7 +649,7 @@ groupMembers.set(trailView: { member in ### Global Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -667,7 +667,7 @@ CometChatGroupMembers.avatarStyle = avatarStyle ### Instance Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -723,7 +723,7 @@ Customizes the appearance of member avatars in the list. | Type | `AvatarStyle` | | Default | `AvatarStyle()` | -```swift +```swift lines import CometChatUIKitSwift let groupMembers = CometChatGroupMembers(group: group) @@ -852,7 +852,7 @@ Customizes the appearance of online/offline status indicators. | Type | `StatusIndicatorStyle` | | Default | `StatusIndicatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let groupMembers = CometChatGroupMembers(group: group) @@ -885,7 +885,7 @@ groupMembers.statusIndicatorStyle = statusIndicatorStyle Sets custom swipe actions for group member list items, replacing the default options. These options appear when the user swipes on a member cell. -```swift +```swift lines @discardableResult public func set(options: ((_ group: Group, _ member: GroupMember?) -> [CometChatGroupMemberOption])?) -> Self ``` @@ -894,7 +894,7 @@ public func set(options: ((_ group: Group, _ member: GroupMember?) -> [CometChat |-----------|------|-------------| | `options` | `((Group, GroupMember?) -> [CometChatGroupMemberOption])?` | Closure that returns an array of swipe action options for a member | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -938,7 +938,7 @@ groupMembers.set(options: { group, member in Adds additional swipe actions to the existing default options. -```swift +```swift lines @discardableResult public func add(options: ((_ group: Group, _ member: GroupMember?) -> [CometChatGroupMemberOption])?) -> Self ``` @@ -947,7 +947,7 @@ public func add(options: ((_ group: Group, _ member: GroupMember?) -> [CometChat |-----------|------|-------------| | `options` | `((Group, GroupMember?) -> [CometChatGroupMemberOption])?` | Closure that returns additional swipe action options to append | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -979,7 +979,7 @@ groupMembers.add(options: { group, member in Adds a new group member to the list. -```swift +```swift lines @discardableResult public func add(groupMember: GroupMember) -> Self ``` @@ -988,7 +988,7 @@ public func add(groupMember: GroupMember) -> Self |-----------|------|-------------| | `groupMember` | `GroupMember` | The group member to add to the list | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -1004,7 +1004,7 @@ groupMembers.add(groupMember: newMember) Updates an existing group member in the list. -```swift +```swift lines @discardableResult public func update(groupMember: GroupMember) -> Self ``` @@ -1013,7 +1013,7 @@ public func update(groupMember: GroupMember) -> Self |-----------|------|-------------| | `groupMember` | `GroupMember` | The group member with updated information | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -1030,7 +1030,7 @@ if var existingMember = memberToUpdate { Removes a group member from the list. -```swift +```swift lines @discardableResult public func remove(groupMember: GroupMember) -> Self ``` @@ -1039,7 +1039,7 @@ public func remove(groupMember: GroupMember) -> Self |-----------|------|-------------| | `groupMember` | `GroupMember` | The group member to remove from the list | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -1053,7 +1053,7 @@ groupMembers.remove(groupMember: memberToRemove) Inserts a group member at a specific index in the list. -```swift +```swift lines @discardableResult public func insert(groupMember: GroupMember, at index: Int) -> Self ``` @@ -1063,7 +1063,7 @@ public func insert(groupMember: GroupMember, at index: Int) -> Self | `groupMember` | `GroupMember` | The group member to insert | | `index` | `Int` | The position at which to insert the member | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -1079,11 +1079,11 @@ groupMembers.insert(groupMember: newMember, at: 0) Removes all group members from the list. -```swift +```swift lines public func clearList() ``` -```swift +```swift lines import CometChatUIKitSwift let groupMembers = CometChatGroupMembers(group: group) @@ -1096,11 +1096,11 @@ groupMembers.clearList() Returns the number of group members currently in the list. -```swift +```swift lines public func size() -> Int ``` -```swift +```swift lines import CometChatUIKitSwift let groupMembers = CometChatGroupMembers(group: group) @@ -1123,7 +1123,7 @@ Callback that fires when the user proceeds with selected members in selection mo | Type | `(([GroupMember]) -> Void)?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -1148,7 +1148,7 @@ groupMembers.set(onSelectedItemProceed: { [weak self] selectedMembers in Add custom actions when swiping on a member: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -1193,7 +1193,7 @@ groupMembers.setOptions(options: { group, member in Add buttons to the navigation bar: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -1241,7 +1241,7 @@ class GroupMembersViewController: UIViewController { ### Admins and moderators only -```swift +```swift lines let adminBuilder = GroupMembersRequest.GroupMembersRequestBuilder(guid: group.guid) .set(scopes: ["admin", "moderator"]) @@ -1250,7 +1250,7 @@ let groupMembers = CometChatGroupMembers(group: group, groupMembersRequestBuilde ### Hide management options for participants -```swift +```swift lines let groupMembers = CometChatGroupMembers(group: group) groupMembers.hideKickMemberOption = true groupMembers.hideBanMemberOption = true @@ -1259,7 +1259,7 @@ groupMembers.hideScopeChangeOption = true ### Custom empty state -```swift +```swift lines let groupMembers = CometChatGroupMembers(group: group) groupMembers.set(emptyStateView: { @@ -1272,7 +1272,7 @@ groupMembers.set(emptyStateView: { ### Multi-select members -```swift +```swift lines let groupMembers = CometChatGroupMembers(group: group) groupMembers.selectionMode = .multiple diff --git a/ui-kit/ios/groups.mdx b/ui-kit/ios/groups.mdx index 0c72cb3ef..7df45142a 100644 --- a/ui-kit/ios/groups.mdx +++ b/ui-kit/ios/groups.mdx @@ -134,7 +134,7 @@ The `CometChatGroups` component displays a searchable list of all available grou `CometChatGroups` displays all available groups for browsing and joining. It's typically used as a standalone screen or within a tab view controller. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -174,7 +174,7 @@ class GroupsViewController: UIViewController { ## Minimal Render -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -192,7 +192,7 @@ present(navController, animated: true) Use `GroupsRequest.GroupsRequestBuilder` to filter which groups appear in the list. The builder pattern allows chaining multiple filter conditions. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -223,7 +223,7 @@ let groups = CometChatGroups(groupsRequestBuilder: groupsRequestBuilder) Fires when a user taps on a group in the list. Use this to open the group chat. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -242,7 +242,7 @@ groups.set(onItemClick: { [weak self] group, indexPath in Fires when a user long-presses on a group. Use this to show additional options. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -270,7 +270,7 @@ groups.set(onItemLongClick: { [weak self] group, indexPath in Fires when the back button is pressed. -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -284,7 +284,7 @@ groups.set(onBack: { [weak self] in Fires when groups are selected in selection mode. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -300,7 +300,7 @@ groups.set(onSelection: { [weak self] selectedGroups in Fires when the user confirms their selection by tapping the proceed/submit button. Use this to handle the final selection action. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -325,7 +325,7 @@ groups.onSelectedItemProceed = { [weak self] selectedGroups in Fires when an error occurs while loading groups. -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -339,7 +339,7 @@ groups.set(onError: { error in Fires when the group list is empty. -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -353,7 +353,7 @@ groups.set(onEmpty: { Fires when groups are successfully loaded. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -386,7 +386,7 @@ groups.set(onLoad: { groups in | `ccGroupMemberJoined` | A user joins a group | `User, Group` | | `ccGroupMemberLeft` | A user leaves a group | `User, Group` | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -451,7 +451,7 @@ class MyViewController: UIViewController, CometChatGroupEventListener { Replace the entire group row with a custom design. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -471,7 +471,7 @@ groups.set(listItemView: { group in You can create a `CustomGroupCell` as a custom `UIView`: -```swift +```swift lines import UIKit import CometChatSDK @@ -577,7 +577,7 @@ class CustomGroupCell: UIView { Customize the leading view (avatar area) of a group cell. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -596,7 +596,7 @@ groups.set(leadingView: { group in You can create a `CustomLeadingView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomLeadingView: UIView { @@ -644,7 +644,7 @@ class CustomLeadingView: UIView { Customize the title view of a group cell. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -663,7 +663,7 @@ groups.set(titleView: { group in You can create a `CustomTitleView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomTitleView: UIView { @@ -738,7 +738,7 @@ class CustomTitleView: UIView { Customize the subtitle area below the group name. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -757,7 +757,7 @@ groups.set(subtitleView: { group in You can create a `CustomSubtitleView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomSubtitleView: UILabel { @@ -780,7 +780,7 @@ class CustomSubtitleView: UILabel { Customize the trailing view (right side) of a group cell. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -799,7 +799,7 @@ groups.set(trailView: { group in You can create a `CustomTrailView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomTrailView: UIView { @@ -842,7 +842,7 @@ class CustomTrailView: UIView { Customize the loading state view displayed while data is being fetched. -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -857,7 +857,7 @@ groups.set(loadingView: loadingIndicator) Customize the error state view displayed when an error occurs. -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -873,7 +873,7 @@ groups.set(errorView: errorLabel) Customize the empty state view displayed when no groups are available. -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -894,7 +894,7 @@ groups.set(emptyView: emptyLabel) Define custom swipe options for each group. This method allows you to return an array of `CometChatGroupOption` based on the group object. These options appear when the user swipes on a group cell. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -933,7 +933,7 @@ groups.set(options: { group in Dynamically add additional swipe options to groups while preserving the default options. This method lets you return additional `CometChatGroupOption` elements that will be appended to the existing options. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -964,7 +964,7 @@ groups.add(options: { group in Displays an alert dialog when a user attempts to join a password-protected group. This method shows a prompt for the user to enter the group password. -```swift +```swift lines public func showJoiningGroupAlert(for group: Group) ``` @@ -972,7 +972,7 @@ public func showJoiningGroupAlert(for group: Group) |-----------|------|-------------| | `group` | `Group` | The password-protected group to join | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -992,7 +992,7 @@ groups.set(onItemClick: { [weak self] group, indexPath in Dismisses the joining group alert dialog programmatically. Use this when you need to close the alert without user interaction. -```swift +```swift lines public func hideJoiningGroupAlert(completion: (() -> Void)? = nil) ``` @@ -1000,7 +1000,7 @@ public func hideJoiningGroupAlert(completion: (() -> Void)? = nil) |-----------|------|-------------| | `completion` | `(() -> Void)?` | Optional closure called after the alert is dismissed | -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -1022,7 +1022,7 @@ groups.hideJoiningGroupAlert { ### Global Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -1041,7 +1041,7 @@ CometChatGroups.avatarStyle = avatarStyle ### Instance Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -1098,7 +1098,7 @@ Customizes the appearance of avatars in group list items. | Type | `AvatarStyle` | | Default | `AvatarStyle()` | -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -1202,7 +1202,7 @@ Returns the count of currently selected groups when in selection mode. | Type | `Int` | | Default | `0` | -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -1222,7 +1222,7 @@ Sets the maximum number of groups that can be selected in selection mode. When t | Type | `Int` | | Default | `0` (unlimited) | -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -1260,7 +1260,7 @@ Customizes the appearance of group type status indicators. | Type | `StatusIndicatorStyle` | | Default | `StatusIndicatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let groups = CometChatGroups() @@ -1290,7 +1290,7 @@ groups.set(statusIndicatorStyle: statusIndicatorStyle) ### Public groups only -```swift +```swift lines let publicBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) .set(groupType: .public) @@ -1300,7 +1300,7 @@ groups.set(groupsRequestBuilder: publicBuilder) ### Joined groups only -```swift +```swift lines let joinedBuilder = GroupsRequest.GroupsRequestBuilder(limit: 30) .set(joinedOnly: true) @@ -1310,7 +1310,7 @@ groups.set(groupsRequestBuilder: joinedBuilder) ### Custom empty state with CTA -```swift +```swift lines let groups = CometChatGroups() groups.set(emptyStateView: { @@ -1330,7 +1330,7 @@ groups.set(emptyStateView: { ### Hide all chrome — minimal list -```swift +```swift lines let groups = CometChatGroups() groups.hideSearch = true groups.hideGroupType = true @@ -1339,7 +1339,7 @@ groups.hideSectionHeader = true ### Multi-select groups -```swift +```swift lines let groups = CometChatGroups() groups.selectionMode = .multiple diff --git a/ui-kit/ios/guide-ai-agent.mdx b/ui-kit/ios/guide-ai-agent.mdx index 187c6d4b2..a5c2193fb 100644 --- a/ui-kit/ios/guide-ai-agent.mdx +++ b/ui-kit/ios/guide-ai-agent.mdx @@ -33,7 +33,7 @@ The AI Agent integration provides: Create a simple AI chat screen: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -104,7 +104,7 @@ class AIAgentChatViewController: UIViewController { Complete AI agent chat with history, navigation, and error handling: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -287,7 +287,7 @@ class ProductionAIAgentViewController: UIViewController { Start an AI agent conversation from your app: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -334,7 +334,7 @@ class ChatListViewController: UIViewController { Customize the AI chat bubble appearance: -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -389,7 +389,7 @@ class AIAgentStylingExample { Customize the view shown when there are no messages: -```swift +```swift lines let emptyView = UIView() let label = UILabel() label.text = "Start a conversation with AI" @@ -404,7 +404,7 @@ messageList.set(emptyStateView: emptyView) Adjust how fast AI responses stream: -```swift +```swift lines // Configure streaming speed (characters per second) messageList.set(streamingSpeed: 50) ``` @@ -413,7 +413,7 @@ messageList.set(streamingSpeed: 50) Provide quick-start prompts for users: -```swift +```swift lines let suggestions = [ "What can you help me with?", "Tell me about your capabilities", @@ -427,7 +427,7 @@ messageComposer.set(suggestedMessages: suggestions) Configure custom tools for the AI agent: -```swift +```swift lines messageComposer.set(aiAssistantTools: { message in // Return custom tools based on context return [ @@ -441,7 +441,7 @@ messageComposer.set(aiAssistantTools: { message in The `CometChatAIAssistanceChatHistory` component displays previous AI conversations: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK diff --git a/ui-kit/ios/guide-block-unblock-user.mdx b/ui-kit/ios/guide-block-unblock-user.mdx index 62f665eb7..1f684f018 100644 --- a/ui-kit/ios/guide-block-unblock-user.mdx +++ b/ui-kit/ios/guide-block-unblock-user.mdx @@ -29,7 +29,7 @@ The user details screen provides: Create a simple user details screen: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -141,7 +141,7 @@ class UserDetailsViewController: UIViewController { Complete user details screen with all features and event handling: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -554,7 +554,7 @@ extension ProductionUserDetailsViewController: CometChatUserEventListener { Open the user details screen from your app: -```swift +```swift lines import UIKit import CometChatSDK @@ -587,7 +587,7 @@ class UsersListViewController: UIViewController { ### Block Users -```swift +```swift lines // Block single user CometChat.blockUsers(["user-uid"]) { blockedUsers in print("Blocked \(blockedUsers?.count ?? 0) users") @@ -605,7 +605,7 @@ CometChat.blockUsers(["user1", "user2", "user3"]) { blockedUsers in ### Unblock Users -```swift +```swift lines // Unblock single user CometChat.unblockUsers(["user-uid"]) { unblockedUsers in print("Unblocked \(unblockedUsers?.count ?? 0) users") @@ -623,7 +623,7 @@ CometChat.unblockUsers(["user1", "user2"]) { unblockedUsers in ### Fetch Blocked Users -```swift +```swift lines let request = BlockedUserRequest.BlockedUserRequestBuilder() .set(limit: 50) .set(direction: .blockedByMe) // or .hasBlockedMe, .both @@ -642,7 +642,7 @@ request.fetchNext { blockedUsers in Customize the avatar appearance: -```swift +```swift lines let avatarStyle = AvatarStyle() avatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 50) avatarStyle.borderWidth = 2 diff --git a/ui-kit/ios/guide-call-log-details.mdx b/ui-kit/ios/guide-call-log-details.mdx index 39c1adb0c..b0ce1dc4f 100644 --- a/ui-kit/ios/guide-call-log-details.mdx +++ b/ui-kit/ios/guide-call-log-details.mdx @@ -45,7 +45,7 @@ Before implementing call log details, ensure you have: Show the call log interface for a selected call: -```swift +```swift lines import UIKit import CometChatSDK import CometChatCallsSDK @@ -70,7 +70,7 @@ This bundles history, participants, and recordings into a single UI flow. Populate the participants tab with the call's members: -```swift +```swift lines import UIKit import CometChatSDK @@ -97,7 +97,7 @@ This provides an audit trail of who was present in the call. Render join/leave activities in chronological order: -```swift +```swift lines import UIKit class CallLogHistoryVC: UIViewController { @@ -126,7 +126,7 @@ This tracks user join/leave times for transparency. Provide playback links for any recorded calls: -```swift +```swift lines import UIKit class CallLogRecordingsVC: UIViewController { @@ -150,7 +150,7 @@ This enables administrators and users to review call content (if recording is en Customize colors, fonts, and spacing using CometChat's theming system: -```swift +```swift lines import CometChatUIKitSwift // Apply custom theme to call log components @@ -170,7 +170,7 @@ spacing.padding = 16 Use `CallLogViewModel` to filter by call type: -```swift +```swift lines // Filter by call type viewModel.filterByType(.incoming) // Show only incoming calls viewModel.filterByType(.outgoing) // Show only outgoing calls @@ -181,7 +181,7 @@ viewModel.filterByType(.missed) // Show only missed calls Implement an `EmptyStateView` in `CallLogHistoryVC` for no-history scenarios: -```swift +```swift lines func showEmptyState() { let emptyView = UILabel() emptyView.text = "No call history available" diff --git a/ui-kit/ios/guide-group-chat.mdx b/ui-kit/ios/guide-group-chat.mdx index 349edfdbe..a9bfc3287 100644 --- a/ui-kit/ios/guide-group-chat.mdx +++ b/ui-kit/ios/guide-group-chat.mdx @@ -44,7 +44,7 @@ Before implementing group details, ensure you have: Push `GroupDetailsViewController` for a selected group: -```swift +```swift lines import UIKit import CometChatSDK @@ -69,7 +69,7 @@ This initializes and presents the details UI with the correct group context. Configure scroll view, header, and action views: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -111,7 +111,7 @@ This lays out the UI components and registers for group events. Wire up view/add/banned members actions: -```swift +```swift lines // Action views for member management private let viewMembersView = GroupActionView() private let addMembersView = GroupActionView() @@ -158,7 +158,7 @@ This enables user interaction for member management. Provide ownership-aware leave/delete flows: -```swift +```swift lines @objc func showLeaveGroupAlert() { guard let group = group else { return } @@ -226,7 +226,7 @@ This manages group exit, with transfer prompt for owners. Update UI on member joins, leaves, bans, and ownership changes: -```swift +```swift lines private let listenerId = "group-details-listener" func connect() { @@ -247,7 +247,7 @@ deinit { } ``` -```swift +```swift lines // MARK: - CometChatGroupDelegate extension GroupDetailsViewController: CometChatGroupDelegate { @@ -309,7 +309,7 @@ This keeps the group details in sync with back-end events. Use `CometChatTheme` to customize fonts, colors, and borders: -```swift +```swift lines // Apply custom theme CometChatTheme.palette.primary = UIColor.systemBlue CometChatTheme.typography.heading = UIFont.systemFont(ofSize: 20, weight: .bold) @@ -319,7 +319,7 @@ CometChatTheme.typography.heading = UIFont.systemFont(ofSize: 20, weight: .bold) Localize or rebrand action texts: -```swift +```swift lines viewMembersView.setTitle("View Members", for: .normal) addMembersView.setTitle("Add Members", for: .normal) bannedMembersView.setTitle("Banned Members", for: .normal) @@ -329,7 +329,7 @@ bannedMembersView.setTitle("Banned Members", for: .normal) Provide fallback initials or default images: -```swift +```swift lines avatarView.set(name: group.name) avatarView.set(image: UIImage(named: "default_group_avatar")) ``` diff --git a/ui-kit/ios/guide-group-ownership.mdx b/ui-kit/ios/guide-group-ownership.mdx index 5f8655167..12e88eb40 100644 --- a/ui-kit/ios/guide-group-ownership.mdx +++ b/ui-kit/ios/guide-group-ownership.mdx @@ -43,7 +43,7 @@ Before implementing ownership transfer, ensure you have: Show the ownership transfer UI modally: -```swift +```swift lines import UIKit import CometChatSDK import CometChatUIKitSwift @@ -80,7 +80,7 @@ class GroupDetailsViewController: UIViewController { Restrict selection to one member and capture selection: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -120,7 +120,7 @@ class TransferOwnership: CometChatGroupMembers { Exclude the current owner from the selectable list: -```swift +```swift lines override func reloadData() { super.reloadData() @@ -154,7 +154,7 @@ override func reloadData() { Call the API, emit event, and exit the group: -```swift +```swift lines func transferOwnership(to member: GroupMember) { // Show loading indicator addSpinnerView() @@ -205,7 +205,7 @@ func transferOwnership(to member: GroupMember) { Provide visual feedback during network calls: -```swift +```swift lines func addSpinnerView() { // Start spinner animation spinnerView.startAnimating() @@ -229,7 +229,7 @@ func removeSpinnerView() { Here's the complete `TransferOwnership` class: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -340,7 +340,7 @@ class TransferOwnership: CometChatGroupMembers { Replace localization key with custom string: -```swift +```swift lines title = "Select New Owner" ``` @@ -348,7 +348,7 @@ title = "Select New Owner" Adjust `spinnerView.style` and color using `CometChatTheme`: -```swift +```swift lines spinnerView.style = .large spinnerView.color = CometChatTheme.palette.primary ``` @@ -357,7 +357,7 @@ spinnerView.color = CometChatTheme.palette.primary Customize error alerts in the `onError` closure: -```swift +```swift lines let alert = UIAlertController( title: "Oops!", message: "Could not transfer ownership. Please try again.", diff --git a/ui-kit/ios/guide-message-privately.mdx b/ui-kit/ios/guide-message-privately.mdx index 11b6a5399..0a06146e2 100644 --- a/ui-kit/ios/guide-message-privately.mdx +++ b/ui-kit/ios/guide-message-privately.mdx @@ -37,7 +37,7 @@ Before implementing this feature, ensure you have: Dynamically show or hide **Message Privately** based on app context: -```swift +```swift lines import CometChatUIKitSwift // Control visibility of the Message Privately option @@ -57,7 +57,7 @@ This ensures the option only appears when appropriate (e.g., based on user permi Retrieve the sender and initiate a private 1-on-1 chat: -```swift +```swift lines import UIKit import CometChatSDK import CometChatUIKitSwift @@ -113,7 +113,7 @@ This automates the transition from group context to private conversation. Override `CometChatMessageOption` UI elements: -```swift +```swift lines // Customize the message option appearance let privateOption = CometChatMessageOption( id: "message-privately", @@ -127,7 +127,7 @@ let privateOption = CometChatMessageOption( Control visibility via the view model: -```swift +```swift lines // Hide the option for specific scenarios viewModel.hideMessagePrivatelyOption = true ``` @@ -136,7 +136,7 @@ viewModel.hideMessagePrivatelyOption = true Add additional actions in `MessageDataSource.getMessageOptions(for:)`: -```swift +```swift lines func getMessageOptions(for message: BaseMessage) -> [CometChatMessageOption] { var options = [CometChatMessageOption]() diff --git a/ui-kit/ios/guide-new-chat.mdx b/ui-kit/ios/guide-new-chat.mdx index 7b37a7ed3..78f4abf90 100644 --- a/ui-kit/ios/guide-new-chat.mdx +++ b/ui-kit/ios/guide-new-chat.mdx @@ -45,7 +45,7 @@ Before implementing this feature, ensure you have: Push `CreateConversations` to allow starting a chat: -```swift +```swift lines import UIKit import CometChatSDK @@ -69,7 +69,7 @@ This provides the entry point to the create-conversation flow. Build the segmented control and page view controller: -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -116,7 +116,7 @@ This initializes the UI elements and search integration. Toggle between user and group lists when the segment changes: -```swift +```swift lines @objc public func segmentChanged(_ sender: UISegmentedControl) { let index = sender.selectedSegmentIndex @@ -145,7 +145,7 @@ This keeps the proper search bar and view in sync with the selected tab. Navigate to `MessagesVC` when a user or group is tapped: -```swift +```swift lines // Users list with tap handler public lazy var usersViewController: CometChatUsers = { let vc = CometChatUsers() @@ -189,7 +189,7 @@ This routes the user to the appropriate chat screen. Implement data source and delegate for smooth swiping: -```swift +```swift lines // MARK: - UIPageViewControllerDataSource extension CreateConversationVC: UIPageViewControllerDataSource { @@ -239,7 +239,7 @@ This synchronizes the segmented control with page swipes. Use `CometChatTheme` to customize tint and font: -```swift +```swift lines segmentedControl.selectedSegmentTintColor = CometChatTheme.palette.primary segmentedControl.setTitleTextAttributes([ .font: CometChatTypography.body, @@ -251,7 +251,7 @@ segmentedControl.setTitleTextAttributes([ Localize or rebrand "USERS" / "GROUPS" labels: -```swift +```swift lines segmentedControl.setTitle("Contacts", forSegmentAt: 0) segmentedControl.setTitle("Teams", forSegmentAt: 1) ``` @@ -260,7 +260,7 @@ segmentedControl.setTitle("Teams", forSegmentAt: 1) Adjust `searchController.placeholder` and styling: -```swift +```swift lines usersViewController.searchController.searchBar.placeholder = "Search contacts..." groupsViewController.searchController.searchBar.placeholder = "Search teams..." ``` diff --git a/ui-kit/ios/guide-threaded-messages.mdx b/ui-kit/ios/guide-threaded-messages.mdx index 866c6aa56..c8412948d 100644 --- a/ui-kit/ios/guide-threaded-messages.mdx +++ b/ui-kit/ios/guide-threaded-messages.mdx @@ -37,7 +37,7 @@ Before implementing this feature, ensure you have: Navigate to the thread when a message's thread icon is tapped: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -70,7 +70,7 @@ This captures user intent and opens a focused thread screen. Show a dedicated UI for thread replies. In `ThreadedMessagesVC.swift`: -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -101,14 +101,14 @@ class ThreadedMessagesVC: UIViewController { Header configuration: -```swift +```swift lines // Create the threaded message header let parentMessageContainerView = CometChatThreadedMessageHeader() ``` Message list configuration: -```swift +```swift lines // Configure message list with user and parent message messageListView.set(user: user, parentMessage: parentMessage) ``` @@ -119,14 +119,14 @@ This provides a focused UI for thread interactions. Ensure new replies are attached to the correct parent message: -```swift +```swift lines // Set the parent message ID for threaded replies composerView.set(parentMessageId: parentMessage?.id ?? 0) ``` Set the conversation context: -```swift +```swift lines // Configure composer for user conversation composerView.set(user: user) @@ -138,7 +138,7 @@ composerView.set(group: group) Only messages that are part of the thread are displayed. This is handled internally by: -```swift +```swift lines // Configure message list to fetch thread replies messageListView.set(user: user, parentMessage: parentMessage) ``` @@ -151,7 +151,7 @@ This ensures `CometChatMessageList` fetches replies using the `parentMessageId`. Customize `CometChatThreadedMessageHeader` appearance: -```swift +```swift lines // Customize fonts, colors, and layout let headerStyle = ThreadedMessageHeaderStyle() headerStyle.titleFont = UIFont.systemFont(ofSize: 16, weight: .semibold) @@ -163,7 +163,7 @@ parentMessageContainerView.set(style: headerStyle) Modify placeholder text, input styles, and icons: -```swift +```swift lines // Customize composer appearance composerView.set(placeholderText: "Reply in thread...") ``` @@ -172,7 +172,7 @@ composerView.set(placeholderText: "Reply in thread...") Add a custom back button for navigation: -```swift +```swift lines // Add custom back button navigationItem.leftBarButtonItem = UIBarButtonItem( image: UIImage(systemName: "chevron.left"), diff --git a/ui-kit/ios/incoming-call.mdx b/ui-kit/ios/incoming-call.mdx index 37cc0e44f..1cc0e81e4 100644 --- a/ui-kit/ios/incoming-call.mdx +++ b/ui-kit/ios/incoming-call.mdx @@ -65,7 +65,7 @@ The `CometChatIncomingCall` component serves as a visual representation when the -```swift +```swift lines // Create and configure incoming call view controller let cometChatIncomingCall = CometChatIncomingCall().set(call: call) @@ -90,7 +90,7 @@ The `setOnAcceptClick` action is typically triggered when the user clicks on the -```swift +```swift lines let cometChatIncomingCall = CometChatIncomingCall() .set(onAcceptClick: { call, controller in // Perform your custom action when call is accepted @@ -105,7 +105,7 @@ The `setOnCancelClick` action is typically triggered when the user clicks on the -```swift +```swift lines let cometChatIncomingCall = CometChatIncomingCall() .set(onCancelClick: { call, controller in // Perform your custom action when call is rejected @@ -120,7 +120,7 @@ You can customize this behavior by using the provided code snippet to override t -```swift +```swift lines let incomingCallConfiguration = IncomingCallConfiguration() .set(onError: { error in // Perform your custom error handling action @@ -153,7 +153,7 @@ Events emitted by the Incoming Call component are as follows: -```swift +```swift lines // View controller from your project where you want to listen to events public class ViewController: UIViewController { @@ -182,7 +182,7 @@ extension ViewController: CometChatCallEventListener { } ``` -```swift +```swift lines // Emitting Call Events // Emit when logged in user accepts the incoming call @@ -201,7 +201,7 @@ CometChatCallEvents.emitOnCallEnded(call: Call) -```swift +```swift lines public override func viewWillDisappear(_ animated: Bool) { // Unsubscribe from call events CometChatCallEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") @@ -228,7 +228,7 @@ You can customize the appearance of the `IncomingCall` Component by applying the -```swift +```swift lines // Create custom avatar style let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") @@ -248,7 +248,7 @@ CometChatIncomingCall.avatarStyle = customAvatarStyle -```swift +```swift lines // Create custom avatar style var customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") @@ -320,7 +320,7 @@ With this function, you can assign a custom view to the incoming call item view. -```swift +```swift lines cometChatIncomingCall.set(listItemView: { call in let customView = CustomListItemView() return customView @@ -337,7 +337,7 @@ Demonstration: You can create a CustomListItemView as a custom `UIView`: -```swift +```swift lines import UIKit class CustomListItemView: UIView { @@ -445,7 +445,7 @@ You can modify the leading view of an Incoming call component using the property -```swift +```swift lines cometChatIncomingCall.set(leadingView: { call in let view = CustomLeadingView() return view @@ -464,7 +464,7 @@ You can create a CustomLeadingView as a custom `UIView`: -```swift +```swift lines import UIKit class CustomLeadingView: UIView { @@ -530,7 +530,7 @@ You can customize the title view of an incoming call component using the propert -```swift +```swift lines cometChatIncomingCall.set(titleView: { call in let view = CustomTitleView() return view @@ -549,7 +549,7 @@ You can create a `CustomTitleView` as a custom `UIView` which we will inflate in -```swift +```swift lines import UIKit class CustomTitleView: UIView { @@ -676,7 +676,7 @@ Customizes the appearance of the caller's avatar. | Type | `AvatarStyle` | | Default | `AvatarStyle()` | -```swift +```swift lines import CometChatUIKitSwift let customAvatarStyle = AvatarStyle() @@ -717,7 +717,7 @@ You can customize the subtitle view of an incoming call component using the prop -```swift +```swift lines cometChatIncomingCall.set(subtitleView: { call in let view = CustomSubtitleView() return view @@ -732,7 +732,7 @@ You can customize the trailing view of an incoming call component using the prop -```swift +```swift lines cometChatIncomingCall.set(trailingView: { call in let view = CustomTrailingView() return view @@ -751,7 +751,7 @@ Present the incoming call screen when a call is received: -```swift +```swift lines // In your call listener func onIncomingCallReceived(incomingCall: Call) { DispatchQueue.main.async { @@ -775,7 +775,7 @@ Transition from incoming call to ongoing call when accepted: -```swift +```swift lines let incomingCall = CometChatIncomingCall() incomingCall.set(call: call) incomingCall.set(onAcceptClick: { [weak self] acceptedCall, controller in @@ -798,7 +798,7 @@ Set a custom sound for incoming calls: -```swift +```swift lines let incomingCall = CometChatIncomingCall() incomingCall.set(call: call) diff --git a/ui-kit/ios/localize.mdx b/ui-kit/ios/localize.mdx index 911145fde..9e6197848 100644 --- a/ui-kit/ios/localize.mdx +++ b/ui-kit/ios/localize.mdx @@ -50,7 +50,7 @@ Localization in the SDK is powered by: 1. The `CometChatLocalize` class — for setting and fetching the active locale 2. A `String` extension method called `.localize` — to fetch localized text dynamically -```swift +```swift lines // Example: Localizing a string key "CHATS".localize ``` @@ -76,7 +76,7 @@ The `CometChatLocalize` class provides the following methods: -```swift +```swift lines // Set Language to French CometChatLocalize.set(locale: .french) @@ -94,7 +94,7 @@ To customize any text used by the SDK, simply define the same key in your app's -```swift +```swift lines "CHATS" = "Conversations"; "USERS" = "People"; ``` @@ -186,7 +186,7 @@ A global formatter is available via `CometChatUIKit.dateTimeFormatter`. Use this -```swift +```swift lines CometChatUIKit.dateTimeFormatter.hour = { timestamp in return "Today" } @@ -204,7 +204,7 @@ Each component has a static formatter that overrides the global formatter only f -```swift +```swift lines CometChatMessageList.dateTimeFormatter.hour = { timestamp in return "Today" } @@ -222,7 +222,7 @@ Components also expose an instance-level formatter for per-instance customizatio -```swift +```swift lines let messageList = CometChatMessageList() messageList.set(user: user) diff --git a/ui-kit/ios/mentions-formatter-guide.mdx b/ui-kit/ios/mentions-formatter-guide.mdx index 6c500d5cb..e7bbe2056 100644 --- a/ui-kit/ios/mentions-formatter-guide.mdx +++ b/ui-kit/ios/mentions-formatter-guide.mdx @@ -38,7 +38,7 @@ Below is an example demonstrating how to use the `CometChatMentionsFormatter` cl -```swift +```swift lines // Create a custom mention formatter instance let customMentionFormatter = CometChatMentionsFormatter() @@ -65,7 +65,7 @@ Setting a listener for mention-click events in Message Bubbles enhances interact -```swift +```swift lines // Set up mention click handler let customMentionFormatter = CometChatMentionsFormatter() customMentionFormatter.set { message, tappedText, controller in @@ -80,7 +80,7 @@ The following code snippet represents a UIView extension used to display `showTo -```swift +```swift lines extension UIView { func showToastMessage(message: String) { // Create toast label with centered positioning @@ -142,7 +142,7 @@ Assigns the list of text formatters. If the provided list is not null, it sets t -```swift +```swift lines // Create and configure composer mention style let composerMentionStyle = MentionTextStyle() composerMentionStyle.textColor = UIColor(hex: "#30A46C") @@ -163,7 +163,7 @@ Assigns the list of text formatters. If the provided list is not null, it sets t -```swift +```swift lines // Configure left bubble (incoming) mention style var leftBubbleMentionsStyle = MentionTextStyle() leftBubbleMentionsStyle.textColor = UIColor(hex: "#D6409F") @@ -187,7 +187,7 @@ Assigns the list of text formatters. If the provided list is not null, it sets t -```swift +```swift lines // Create and configure conversation list mention style let mentionsStyle = MentionTextStyle() mentionsStyle.textColor = UIColor(hex: "#30A46C") diff --git a/ui-kit/ios/message-bubble-styling.mdx b/ui-kit/ios/message-bubble-styling.mdx index f83a18a70..3d7e0fa88 100644 --- a/ui-kit/ios/message-bubble-styling.mdx +++ b/ui-kit/ios/message-bubble-styling.mdx @@ -63,7 +63,7 @@ The following code snippet shows how to customize the incoming message bubble st -```swift +```swift lines // Customize incoming message bubble appearance CometChatMessageBubble.style.incoming.backgroundColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.incoming.borderWidth = 2 @@ -78,7 +78,7 @@ The following code snippet shows how to customize the outgoing message bubble st -```swift +```swift lines // Customize outgoing message bubble appearance CometChatMessageBubble.style.outgoing.backgroundColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.outgoing.borderWidth = 2 @@ -97,7 +97,7 @@ The following code snippet shows how to customize the text message bubble: -```swift +```swift lines // Customize text bubble for incoming messages CometChatMessageBubble.style.incoming.textBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") @@ -129,7 +129,7 @@ The following code snippet shows how to customize the image message bubble: -```swift +```swift lines // Customize image bubble for incoming messages CometChatMessageBubble.style.incoming.imageBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") @@ -161,7 +161,7 @@ The following code snippet shows how to customize the video message bubble: -```swift +```swift lines // Customize video bubble for incoming messages CometChatMessageBubble.style.incoming.videoBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") CometChatMessageBubble.style.incoming.videoBubbleStyle.playButtonTint = UIColor(hexString: "#F76808") @@ -195,7 +195,7 @@ The following code snippet shows how to customize the audio message bubble: -```swift +```swift lines // Customize audio bubble for incoming messages CometChatMessageBubble.style.incoming.audioBubbleStyle.audioWaveFormTintColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.incoming.audioBubbleStyle.playImageTintColor = UIColor(hexString: "#F76808") @@ -230,7 +230,7 @@ The following code snippet shows how to customize the poll message bubble: -```swift +```swift lines // Customize poll bubble for incoming messages CometChatMessageBubble.style.incoming.pollBubbleStyle.optionProgressTintColor = UIColor(hexString: "#F76808") CometChatMessageBubble.style.incoming.pollBubbleStyle.selectedPollImageTint = UIColor(hexString: "#F76808") @@ -264,7 +264,7 @@ The following code snippet shows how to customize the link preview message bubbl -```swift +```swift lines // Customize link preview bubble for incoming messages CometChatMessageBubble.style.incoming.linkPreviewBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") @@ -296,7 +296,7 @@ The following code snippet shows how to customize the action message bubble: -```swift +```swift lines // Customize action bubble appearance CometChatMessageBubble.actionBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") CometChatMessageBubble.actionBubbleStyle.bubbleTextColor = UIColor(hexString: "#F76808") @@ -327,7 +327,7 @@ The following code snippet shows how to customize the delete message bubble: -```swift +```swift lines // Customize delete bubble for incoming messages CometChatMessageBubble.style.incoming.deleteBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") @@ -361,7 +361,7 @@ The following code snippet shows how to customize the AI Assistant message bubbl -```swift +```swift lines // Customize AI assistant bubble for incoming messages CometChatMessageBubble.style.incoming.aiAssistantBubbleStyle.backgroundColor = UIColor(hexString: "#FEEDE1") diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index 7145b1a2f..6a23dd421 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -117,7 +117,7 @@ The `CometChatMessageComposer` component enables users to write and send message `CometChatMessageComposer` is the input component for sending messages. It's typically used within `CometChatMessages` alongside `CometChatMessageHeader` and `CometChatMessageList`. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -158,7 +158,7 @@ class ChatViewController: UIViewController { ## Minimal Render -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -180,7 +180,7 @@ messageComposer.set(user: user) Fires when the send button is clicked. Use this to handle custom send actions. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -196,7 +196,7 @@ messageComposer.set(onSendButtonClick: { [weak self] message in Fires when the user types in the composer. Use this for typing indicators or text validation. -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -211,7 +211,7 @@ messageComposer.set(onTextChangedListener: { [weak self] text in Fires when an error occurs while sending a message. -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -254,7 +254,7 @@ Replaces the default header with a custom view above the composer. | Signature | `(User?, Group?) -> UIView` | | Replaces | Default header above composer | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -272,7 +272,7 @@ messageComposer.set(headerView: { user, group in You can create a `CustomHeaderView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomHeaderView: UIView { @@ -335,7 +335,7 @@ Replaces the default footer with a custom view below the composer. | Signature | `(User?, Group?) -> UIView` | | Replaces | Default footer below composer | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -371,7 +371,7 @@ Replaces the default send button with a custom view. | Signature | `(User?, Group?) -> UIView` | | Replaces | Default send button | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -398,7 +398,7 @@ Replaces the auxiliary button area with a custom view. The auxiliary button is t | Signature | `(User?, Group?) -> UIView` | | Replaces | Default auxiliary button area | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -435,7 +435,7 @@ Customizes the attachment menu options with custom actions. | Signature | `(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]` | | Replaces | Default attachment menu options | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -503,7 +503,7 @@ messageComposer.set(attachmentOptions: { user, group, controller in ### Global Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -518,7 +518,7 @@ CometChatMessageComposer.style.aiImageTint = UIColor.systemPurple ### Instance Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -573,7 +573,7 @@ Customizes the appearance of the media recorder (voice recording) interface. | Type | `MediaRecorderStyle` | | Default | `MediaRecorderStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -595,7 +595,7 @@ Customizes the appearance of the attachment options sheet. | Type | `AttachmentSheetStyle` | | Default | `AttachmentSheetStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -617,7 +617,7 @@ Customizes the appearance of the suggestions view (for mentions and other sugges | Type | `SuggestionsStyle` | | Default | `SuggestionsStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -639,7 +639,7 @@ Customizes the appearance of the AI options menu. | Type | `AIOptionsStyle` | | Default | `AIOptionsStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -661,7 +661,7 @@ Customizes the appearance of mentions in the composer. | Type | `MentionStyle` | | Default | `MentionStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -751,7 +751,7 @@ Hides the AI button in the composer. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -776,7 +776,7 @@ Hides the collaborative document option in the attachment menu. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -792,7 +792,7 @@ Hides the collaborative whiteboard option in the attachment menu. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -808,7 +808,7 @@ Hides the file attachment option in the attachment menu. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -824,7 +824,7 @@ Hides the footer view below the composer. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -840,7 +840,7 @@ Hides the header view above the composer. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -856,7 +856,7 @@ Hides the image attachment option in the attachment menu. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -872,7 +872,7 @@ Hides the polls option in the attachment menu. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -888,7 +888,7 @@ Hides the send button. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -904,7 +904,7 @@ Hides the stickers button. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -920,7 +920,7 @@ Hides the video attachment option in the attachment menu. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -954,7 +954,7 @@ Sets the placeholder text displayed in the composer input field when empty. | Type | `String` | | Default | `"Type a message..."` | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -978,7 +978,7 @@ Array of text formatters for customizing text display (e.g., mentions). Sets a custom text formatter for the composer input. -```swift +```swift lines @discardableResult public func set(textFormatter: CometChatTextFormatter) -> Self ``` @@ -987,7 +987,7 @@ public func set(textFormatter: CometChatTextFormatter) -> Self |-----------|------|-------------| | `textFormatter` | `CometChatTextFormatter` | The text formatter to apply | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -1000,7 +1000,7 @@ messageComposer.set(textFormatter: mentionFormatter) Disables or enables the @all mention feature that notifies all group members. -```swift +```swift lines @discardableResult public func setDisableMentionAll(_ disable: Bool) -> Self ``` @@ -1009,7 +1009,7 @@ public func setDisableMentionAll(_ disable: Bool) -> Self |-----------|------|-------------| | `disable` | `Bool` | Whether to disable the @all mention feature | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -1022,7 +1022,7 @@ messageComposer.setDisableMentionAll(true) Customizes the label displayed for @all mentions in the suggestions list. -```swift +```swift lines @discardableResult public func setMentionAllLabel(_ title: String, _ subtitle: String) -> Self ``` @@ -1032,7 +1032,7 @@ public func setMentionAllLabel(_ title: String, _ subtitle: String) -> Self | `title` | `String` | The title for the @all mention | | `subtitle` | `String` | The subtitle for the @all mention | -```swift +```swift lines import CometChatUIKitSwift let messageComposer = CometChatMessageComposer() @@ -1053,7 +1053,7 @@ The MessageComposer component does not emit any global UI events. ### Hide attachment options -```swift +```swift lines let messageComposer = CometChatMessageComposer() messageComposer.set(user: user) messageComposer.hideImageAttachmentOption = true @@ -1064,7 +1064,7 @@ messageComposer.hideFileAttachmentOption = true ### Hide all auxiliary buttons -```swift +```swift lines let messageComposer = CometChatMessageComposer() messageComposer.set(user: user) messageComposer.hideAttachmentButton = true @@ -1074,7 +1074,7 @@ messageComposer.hideStickersButton = true ### Disable typing indicators -```swift +```swift lines let messageComposer = CometChatMessageComposer() messageComposer.set(user: user) messageComposer.disableTypingEvents = true @@ -1082,7 +1082,7 @@ messageComposer.disableTypingEvents = true ### Disable mentions -```swift +```swift lines let messageComposer = CometChatMessageComposer() messageComposer.set(user: user) messageComposer.disableMentions = true @@ -1090,7 +1090,7 @@ messageComposer.disableMentions = true ### Custom send button action -```swift +```swift lines let messageComposer = CometChatMessageComposer() messageComposer.set(user: user) @@ -1102,7 +1102,7 @@ messageComposer.set(onSendButtonClick: { message in ### Disable message sounds -```swift +```swift lines let messageComposer = CometChatMessageComposer() messageComposer.set(user: user) messageComposer.disableSoundForMessages = true diff --git a/ui-kit/ios/message-header.mdx b/ui-kit/ios/message-header.mdx index 507785eb4..75b1cf2f7 100644 --- a/ui-kit/ios/message-header.mdx +++ b/ui-kit/ios/message-header.mdx @@ -97,7 +97,7 @@ The `CometChatMessageHeader` component displays user or group details in the too `CometChatMessageHeader` displays the recipient's information at the top of the chat screen. It's typically used within `CometChatMessages` alongside `CometChatMessageList` and `CometChatMessageComposer`. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -133,7 +133,7 @@ class ChatViewController: UIViewController { ## Minimal Render -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -155,7 +155,7 @@ messageHeader.set(user: user) Fires when the back button is pressed. Use this for custom navigation handling. -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -169,7 +169,7 @@ messageHeader.set(onBack: { [weak self] in Fires when an error occurs. -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -215,7 +215,7 @@ messageHeader.set(onError: { error in Replace the entire header content with a custom view. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -231,7 +231,7 @@ messageHeader.set(listItemView: { user, group in You can create a `CustomHeaderView` as a custom `UIView`: -```swift +```swift lines import UIKit import CometChatSDK @@ -346,7 +346,7 @@ class CustomHeaderView: UIView { Customize the leading view (avatar area) of the header. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -365,7 +365,7 @@ messageHeader.set(leadingView: { user, group in You can create a `CustomLeadingView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomLeadingView: UIView { @@ -429,7 +429,7 @@ class CustomLeadingView: UIView { Customize the title view of the header. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -448,7 +448,7 @@ messageHeader.set(titleView: { user, group in You can create a `CustomTitleView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomTitleView: UIView { @@ -523,7 +523,7 @@ class CustomTitleView: UIView { Customize the subtitle area (status, typing indicator). -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -549,7 +549,7 @@ messageHeader.set(subtitleView: { user, group in Customize the right side of the header (call buttons, etc.). -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -568,7 +568,7 @@ messageHeader.set(trailView: { user, group in You can create a `CustomTrailView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomTrailView: UIView { @@ -636,7 +636,7 @@ class CustomTrailView: UIView { ### Global Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -656,7 +656,7 @@ CometChatMessageHeader.style.avatarStyle = avatarStyle ### Instance Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -723,12 +723,12 @@ Manually control the WebSocket connection for the message header. Establishes the WebSocket connection for real-time updates. Use this when you need to manually reconnect after disconnecting. -```swift +```swift lines @discardableResult public func connect() -> Self ``` -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -741,12 +741,12 @@ messageHeader.connect() Disconnects the WebSocket connection. Use this when you want to temporarily stop receiving real-time updates, such as when the view is not visible. -```swift +```swift lines @discardableResult public func disconnect() -> Self ``` -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -774,7 +774,7 @@ class ChatViewController: UIViewController { Sets custom menu options for the message header. These options appear in the header's menu (typically accessed via a more button or long press). -```swift +```swift lines @discardableResult public func set(options: ((_ user: User?, _ group: Group?) -> [CometChatMessageHeaderOption])?) -> Self ``` @@ -783,7 +783,7 @@ public func set(options: ((_ user: User?, _ group: Group?) -> [CometChatMessageH |-----------|------|-------------| | `options` | `((User?, Group?) -> [CometChatMessageHeaderOption])?` | Closure that returns an array of menu options based on the current user or group | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -833,7 +833,7 @@ Customizes the appearance of the avatar in the message header. | Type | `AvatarStyle` | | Default | `AvatarStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -856,7 +856,7 @@ Custom formatter for date/time display in the message header (e.g., "Last seen a | Type | `CometChatDateTimeFormatter?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -878,7 +878,7 @@ Disables typing indicators in the message header. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -903,7 +903,7 @@ Hides the AI chat history button in the header. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -919,7 +919,7 @@ Hides the AI new chat button in the header. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -962,7 +962,7 @@ Callback triggered when the AI chat history button is clicked. | Type | `(() -> Void)?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -982,7 +982,7 @@ Callback triggered when the AI new chat button is clicked. | Type | `(() -> Void)?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -1002,7 +1002,7 @@ Customizes the appearance of the online/offline status indicator. | Type | `StatusIndicatorStyle` | | Default | `StatusIndicatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -1025,7 +1025,7 @@ Customizes the appearance of the typing indicator in the message header subtitle | Type | `TypingIndicatorStyle` | | Default | `TypingIndicatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -1051,7 +1051,7 @@ Customize how timestamps appear in the message header (e.g., "Last seen at...") ### Global Level Formatting -```swift +```swift lines import CometChatUIKitSwift // Customize time format for last seen @@ -1081,7 +1081,7 @@ CometChatMessageHeader.dateTimeFormatter.yesterday = { timestamp in ### Instance Level Formatting -```swift +```swift lines import CometChatUIKitSwift let messageHeader = CometChatMessageHeader() @@ -1110,7 +1110,7 @@ messageHeader.dateTimeFormatter.otherDay = { timestamp in ### Hide call buttons -```swift +```swift lines let messageHeader = CometChatMessageHeader() messageHeader.set(user: user) messageHeader.hideVideoCallButton = true @@ -1119,7 +1119,7 @@ messageHeader.hideVoiceCallButton = true ### Custom back button action -```swift +```swift lines let messageHeader = CometChatMessageHeader() messageHeader.set(user: user) @@ -1131,7 +1131,7 @@ messageHeader.set(onBack: { [weak self] in ### Custom subtitle with typing indicator -```swift +```swift lines let messageHeader = CometChatMessageHeader() messageHeader.set(user: user) @@ -1150,7 +1150,7 @@ messageHeader.set(subtitleView: { user, group in ### Minimal header -```swift +```swift lines let messageHeader = CometChatMessageHeader() messageHeader.set(user: user) messageHeader.hideBackButton = true diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index 303ffb02b..061a6190b 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -125,7 +125,7 @@ The `CometChatMessageList` component displays a scrollable list of messages in a `CometChatMessageList` is the core component for displaying messages in a chat. It's typically used within `CometChatMessages` alongside `CometChatMessageHeader` and `CometChatMessageComposer`. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -180,7 +180,7 @@ class ChatViewController: UIViewController { ## Minimal Render -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -198,7 +198,7 @@ messageList.set(user: user) Use `MessagesRequest.MessageRequestBuilder` to filter which messages appear in the list. The builder pattern allows chaining multiple filter conditions. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -235,7 +235,7 @@ messageList.set(messagesRequestBuilder: messageRequestBuilder) Fires when a user taps on the thread indicator of a message bubble. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -257,7 +257,7 @@ messageList.set(onThreadRepliesClick: { [weak self] message, template in Fires when a user taps on a reaction on a message bubble. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -273,7 +273,7 @@ messageList.set(onReactionClick: { [weak self] reactionCount, message in Fires when a user taps on a specific reaction in the reaction list. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -289,7 +289,7 @@ messageList.set(onReactionListItemClick: { [weak self] messageReaction, message Fires when an error occurs while loading messages. -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -303,7 +303,7 @@ messageList.set(onError: { error in Fires when the message list is empty. -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -317,7 +317,7 @@ messageList.set(onEmpty: { Fires when messages are successfully loaded. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -363,7 +363,7 @@ Programmatically manage messages in the list using these methods. Adds a new message to the message list. -```swift +```swift lines @discardableResult public func add(message: BaseMessage) -> Self ``` @@ -372,7 +372,7 @@ public func add(message: BaseMessage) -> Self |-----------|------|-------------| | `message` | `BaseMessage` | The message to add to the list | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -387,7 +387,7 @@ messageList.add(message: textMessage) Updates an existing message in the list. -```swift +```swift lines @discardableResult public func update(message: BaseMessage) -> Self ``` @@ -396,7 +396,7 @@ public func update(message: BaseMessage) -> Self |-----------|------|-------------| | `message` | `BaseMessage` | The message with updated content | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -413,7 +413,7 @@ if let editedMessage = existingMessage as? TextMessage { Removes a message from the list without deleting it from the server. -```swift +```swift lines @discardableResult public func remove(message: BaseMessage) -> Self ``` @@ -422,7 +422,7 @@ public func remove(message: BaseMessage) -> Self |-----------|------|-------------| | `message` | `BaseMessage` | The message to remove from the list | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -436,7 +436,7 @@ messageList.remove(message: messageToRemove) Deletes a message from both the list and the server. -```swift +```swift lines @discardableResult public func delete(message: BaseMessage) -> Self ``` @@ -445,7 +445,7 @@ public func delete(message: BaseMessage) -> Self |-----------|------|-------------| | `message` | `BaseMessage` | The message to delete | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -459,12 +459,12 @@ messageList.delete(message: messageToDelete) Removes all messages from the list. -```swift +```swift lines @discardableResult public func clearList() -> Self ``` -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -477,11 +477,11 @@ messageList.clearList() Checks if the message list is empty. -```swift +```swift lines public func isEmpty() -> Bool ``` -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -502,12 +502,12 @@ Manually control the WebSocket connection for the message list. Establishes the WebSocket connection for real-time updates. Use this when you need to manually reconnect after disconnecting. -```swift +```swift lines @discardableResult public func connect() -> Self ``` -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -520,12 +520,12 @@ messageList.connect() Disconnects the WebSocket connection. Use this when you want to temporarily stop receiving real-time updates, such as when the view is not visible. -```swift +```swift lines @discardableResult public func disconnect() -> Self ``` -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -565,7 +565,7 @@ Replaces the default header with a custom view. | Signature | `(UIView) -> Self` | | Replaces | Default header above message list | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -594,7 +594,7 @@ Replaces the default footer with a custom view. | Signature | `(UIView) -> Self` | | Replaces | Default footer below message list | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -631,7 +631,7 @@ Replaces the default empty state view with a custom view. | Signature | `(UIView) -> Self` | | Replaces | Default empty state when no messages exist | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -661,7 +661,7 @@ Replaces the default error state view with a custom view. | Signature | `(UIView) -> Self` | | Replaces | Default error state when loading fails | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -691,7 +691,7 @@ Replaces the default loading indicator with a custom view. | Signature | `(UIView) -> Self` | | Replaces | Default loading indicator | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -713,7 +713,7 @@ Replaces the default new message indicator with a custom view. | Signature | `(UIView) -> Self` | | Replaces | Default new message indicator | -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -758,7 +758,7 @@ class NewUnreadMessageIndicator: UIView { Customize how text is displayed in messages using text formatters. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -773,7 +773,7 @@ let cometChatMessages = CometChatMessages() Sets custom text formatters for message text display. -```swift +```swift lines @discardableResult public func set(textFormatters: [CometChatTextFormatter]) -> Self ``` @@ -782,7 +782,7 @@ public func set(textFormatters: [CometChatTextFormatter]) -> Self |-----------|------|-------------| | `textFormatters` | `[CometChatTextFormatter]` | Array of text formatters to apply | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -797,7 +797,7 @@ messageList.set(textFormatters: [hashtagFormatter, mentionFormatter]) Customizes the label displayed for @all mentions. -```swift +```swift lines @discardableResult public func setMentionAllLabel(_ title: String, _ subtitle: String) -> Self ``` @@ -807,7 +807,7 @@ public func setMentionAllLabel(_ title: String, _ subtitle: String) -> Self | `title` | `String` | The title for the @all mention | | `subtitle` | `String` | The subtitle for the @all mention | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -818,7 +818,7 @@ messageList.setMentionAllLabel("Everyone", "Notify all members") You can create a custom text formatter: -```swift +```swift lines import Foundation import CometChatSDK import CometChatUIKitSwift @@ -888,7 +888,7 @@ Enables AI-powered smart reply suggestions. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -904,7 +904,7 @@ Enables AI-powered conversation starter suggestions. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -920,7 +920,7 @@ Enables AI-powered conversation summary feature. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -931,7 +931,7 @@ messageList.enableConversationSummary = true Sets keywords that trigger smart reply suggestions. -```swift +```swift lines @discardableResult public func set(smartRepliesKeywords: [String]) -> Self ``` @@ -940,7 +940,7 @@ public func set(smartRepliesKeywords: [String]) -> Self |-----------|------|-------------| | `smartRepliesKeywords` | `[String]` | Keywords that trigger smart replies | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -953,7 +953,7 @@ messageList.set(smartRepliesKeywords: ["help", "question", "support"]) Sets the delay duration before showing smart reply suggestions. -```swift +```swift lines @discardableResult public func set(smartRepliesDelayDuration: TimeInterval) -> Self ``` @@ -962,7 +962,7 @@ public func set(smartRepliesDelayDuration: TimeInterval) -> Self |-----------|------|-------------| | `smartRepliesDelayDuration` | `TimeInterval` | Delay in seconds before showing suggestions | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -986,7 +986,7 @@ Configuration object for the reactions feature. | Type | `ReactionsConfiguration` | | Default | `ReactionsConfiguration()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1007,7 +1007,7 @@ Configuration object for the reaction list display. | Type | `ReactionListConfiguration` | | Default | `ReactionListConfiguration()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1027,7 +1027,7 @@ Configuration object for quick reactions. | Type | `QuickReactionsConfiguration` | | Default | `QuickReactionsConfiguration()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1047,7 +1047,7 @@ Configuration object for message information display. | Type | `MessageInformationConfiguration` | | Default | `MessageInformationConfiguration()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1070,7 +1070,7 @@ messageList.messageInformationConfiguration = messageInfoConfig ### Global Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -1087,7 +1087,7 @@ CometChatMessageList.messageBubbleStyle.incoming.backgroundColor = UIColor.syste ### Instance Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -1135,7 +1135,7 @@ Customizes the appearance of the emoji keyboard. | Type | `EmojiKeyboardStyle` | | Default | `EmojiKeyboardStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1156,7 +1156,7 @@ Customizes the appearance of date separators between messages. | Type | `DateSeparatorStyle` | | Default | `DateSeparatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1178,7 +1178,7 @@ Customizes the appearance of the new message indicator. | Type | `NewMessageIndicatorStyle` | | Default | `NewMessageIndicatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1200,7 +1200,7 @@ Customizes the appearance of message bubbles. | Type | `MessageBubbleStyle` | | Default | `MessageBubbleStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1223,7 +1223,7 @@ Customizes the appearance of action message bubbles (e.g., group actions). | Type | `ActionBubbleStyle` | | Default | `ActionBubbleStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1245,7 +1245,7 @@ Customizes the appearance of call action message bubbles. | Type | `CallActionBubbleStyle` | | Default | `CallActionBubbleStyle()` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1323,7 +1323,7 @@ Disables the swipe-to-reply gesture on messages. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1348,7 +1348,7 @@ Custom subtitle text for the empty state view. | Type | `String` | | Default | `""` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1364,7 +1364,7 @@ Custom title text for the empty state view. | Type | `String` | | Default | `"No Messages"` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1407,7 +1407,7 @@ Custom subtitle text for the error state view. | Type | `String` | | Default | `""` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1423,7 +1423,7 @@ Custom title text for the error state view. | Type | `String` | | Default | `"Something went wrong"` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1448,7 +1448,7 @@ Hides the header section of message bubbles (sender name, timestamp). | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1518,7 +1518,7 @@ Hides the flag/report message option in message actions. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1624,7 +1624,7 @@ Hides the reply to message option in message actions. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1640,7 +1640,7 @@ Hides the share message option in message actions. | Type | `Bool` | | Default | `false` | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1783,7 +1783,7 @@ The MessageList component provides callback events for handling state changes. Fires when messages are successfully loaded. -```swift +```swift lines @discardableResult public func set(onLoad: @escaping ([BaseMessage]) -> Void) -> Self ``` @@ -1792,7 +1792,7 @@ public func set(onLoad: @escaping ([BaseMessage]) -> Void) -> Self |-----------|------|-------------| | `onLoad` | `([BaseMessage]) -> Void` | Callback with loaded messages | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -1808,7 +1808,7 @@ messageList.set(onLoad: { messages in Fires when the message list is empty. -```swift +```swift lines @discardableResult public func set(onEmpty: @escaping () -> Void) -> Self ``` @@ -1817,7 +1817,7 @@ public func set(onEmpty: @escaping () -> Void) -> Self |-----------|------|-------------| | `onEmpty` | `() -> Void` | Callback when list is empty | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1836,7 +1836,7 @@ Customize how timestamps appear in the message list using the `CometChatDateTime ### Global Level Formatting -```swift +```swift lines import CometChatUIKitSwift // Customize time format @@ -1870,7 +1870,7 @@ CometChatMessageList.dateTimeFormatter.otherDay = { timestamp in Sets a custom date pattern for message timestamps. -```swift +```swift lines @discardableResult public func set(datePattern: @escaping (Int?) -> String) -> Self ``` @@ -1879,7 +1879,7 @@ public func set(datePattern: @escaping (Int?) -> String) -> Self |-----------|------|-------------| | `datePattern` | `(Int?) -> String` | Closure that formats timestamp to date string | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1897,7 +1897,7 @@ messageList.set(datePattern: { timestamp in Sets a custom time pattern for message timestamps. -```swift +```swift lines @discardableResult public func set(timePattern: @escaping (Int) -> String) -> Self ``` @@ -1906,7 +1906,7 @@ public func set(timePattern: @escaping (Int) -> String) -> Self |-----------|------|-------------| | `timePattern` | `(Int) -> String` | Closure that formats timestamp to time string | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1923,7 +1923,7 @@ messageList.set(timePattern: { timestamp in Sets a custom pattern for date separators between messages. -```swift +```swift lines @discardableResult public func set(dateSeparatorPattern: @escaping (Int?) -> String) -> Self ``` @@ -1932,7 +1932,7 @@ public func set(dateSeparatorPattern: @escaping (Int?) -> String) -> Self |-----------|------|-------------| | `dateSeparatorPattern` | `(Int?) -> String` | Closure that formats timestamp to date separator string | -```swift +```swift lines import CometChatUIKitSwift let messageList = CometChatMessageList() @@ -1972,7 +1972,7 @@ messageList.set(dateSeparatorPattern: { timestamp in ### Hide message options -```swift +```swift lines let messageList = CometChatMessageList() messageList.set(user: user) messageList.hideReplyInThreadOption = true @@ -1984,7 +1984,7 @@ messageList.hideCopyMessageOption = true ### Disable sounds -```swift +```swift lines let messageList = CometChatMessageList() messageList.set(user: user) messageList.disableSoundForMessages = true @@ -1992,7 +1992,7 @@ messageList.disableSoundForMessages = true ### Custom empty state -```swift +```swift lines let messageList = CometChatMessageList() messageList.set(user: user) @@ -2007,7 +2007,7 @@ messageList.set(emptyStateView: { ### Scroll to bottom on new messages -```swift +```swift lines let messageList = CometChatMessageList() messageList.set(user: user) messageList.scrollToBottomOnNewMessages = true @@ -2015,7 +2015,7 @@ messageList.scrollToBottomOnNewMessages = true ### Hide UI elements -```swift +```swift lines let messageList = CometChatMessageList() messageList.set(user: user) messageList.hideAvatar = true diff --git a/ui-kit/ios/message-template.mdx b/ui-kit/ios/message-template.mdx index 79a18cfdf..9e1e7efdc 100644 --- a/ui-kit/ios/message-template.mdx +++ b/ui-kit/ios/message-template.mdx @@ -44,7 +44,7 @@ MessageTemplate provides you with methods that allow you to alter various proper Using `setType()` you can set the type of CometChatMessage. This will map your MessageTemplate to the corresponding CometChatMessage. You can set the MessageTemplate's Type using the following code snippet: -```swift +```swift lines let type = "custom_template" // Replace with your own custom type // Creating a custom message template @@ -70,7 +70,7 @@ Using `.setCategory()` you can set the category of a MessageTemplate. This will Please refer to our guide on [Message Categories](/sdk/ios/message-structure-and-hierarchy) for a deeper understanding of message categories. -```swift +```swift lines let category = "custom_category" // Replace with your own category // Creating a custom message template @@ -95,7 +95,7 @@ let customMessageTemplate = CometChatMessageTemplate( The `template.headerView` method allows you to assign a custom header view to the MessageBubble. By default, it is configured to display the sender's name. -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -110,7 +110,7 @@ for (index, template) in allTemplates.enumerated() { The `template.contentView` method allows you to assign a custom content view to the MessageBubble. By default, it displays the [Text Bubble](/ui-kit/ios/message-bubble-styling#text-bubble), [Image Bubble](/ui-kit/ios/message-bubble-styling#image-bubble), [File Bubble](/ui-kit/ios/message-bubble-styling), [Audio Bubble](/ui-kit/ios/message-bubble-styling#audio-bubble), or [Video Bubble](/ui-kit/ios/message-bubble-styling#video-bubble), depending on the message type. -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -125,7 +125,7 @@ for (index, template) in allTemplates.enumerated() { The `template.footerView` method allows you to assign a custom Footer view to the MessageBubble. By default, it displays the receipt and timestamp. -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -140,7 +140,7 @@ for (index, template) in allTemplates.enumerated() { The `template.bottomView` method allows you to assign a custom Bottom view to the MessageBubble. By default, it has buttons such as link previews or a 'load more' button for long messages. -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -155,7 +155,7 @@ for (index, template) in allTemplates.enumerated() { The `template.bubbleView` method allows you to assign a custom Bubble view to the MessageBubble. By default, headerView, contentView, and footerView together form a message bubble. -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -170,7 +170,7 @@ for (index, template) in allTemplates.enumerated() { The `template.options` lets you set the list of actions that a user can perform on a message. This includes actions like reacting to, editing, or deleting a message. -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -197,7 +197,7 @@ Let's dive into how you can use the [properties](#properties) of MessageTemplate The first step is to fetch the list of existing templates when you want to modify or add to them. This can be done using the `getAllMessageTemplates()` method from the DataSource of the CometChatUIKit class: -```swift +```swift lines var messageTemplates: [CometChatMessageTemplate] = CometChatUIKit.getDataSource().getAllMessageTemplates() ``` @@ -209,7 +209,7 @@ You will need to first get the MessageTemplates object for the type of message y -```swift +```swift lines var messageTemplates: [CometChatMessageTemplate] = CometChatUIKit.getDataSource().getAllMessageTemplates() for i in 0.. -```swift +```swift lines // Get text message template let messageTemplates: CometChatMessageTemplate = CometChatUIKit.getDataSource().getTextMessageTemplate() @@ -277,7 +277,7 @@ The `template.headerView` method of MessageTemplate allows you to add custom vie -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -347,7 +347,7 @@ class HeaderViewStyled: UIView { -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -381,7 +381,7 @@ The `template.contentView` method of MessageTemplate allows you to add a custom -```swift +```swift lines import UIKit import CometChatSDK import CometChatUIKitSwift @@ -472,7 +472,7 @@ class ContentViewStyled: UIView { -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -506,7 +506,7 @@ The `template.bottomView` method of MessageTemplate allows you to add a custom b -```swift +```swift lines import UIKit class BottomViewStyled: UIView { @@ -568,7 +568,7 @@ class BottomViewStyled: UIView { -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -602,7 +602,7 @@ The `template.footerView` method of MessageTemplate allows you to add a footer v -```swift +```swift lines import UIKit class FooterViewStyled: UIView { @@ -652,7 +652,7 @@ class FooterViewStyled: UIView { -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -687,7 +687,7 @@ The `template.bubbleView` method of MessageTemplate allows you to add a bubble v -```swift +```swift lines import UIKit class CustomMessageView: UIView { @@ -804,7 +804,7 @@ class CustomMessageView: UIView { -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -840,7 +840,7 @@ However, if you wish to override or modify these options, you can use the `templ -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -893,7 +893,7 @@ In the example below, we will integrate a custom UIView file named `custom_statu -```swift +```swift lines import UIKit import CometChatSDK import CometChatUIKitSwift @@ -978,7 +978,7 @@ class StatusInfoView: UIView { -```swift +```swift lines var allTemplates = CometChatUIKit.getDataSource().getAllMessageTemplates() for (index, template) in allTemplates.enumerated() { @@ -1012,7 +1012,7 @@ First, let's see how to send a custom message: -```swift +```swift lines // Creating a text template let textTemplate = CometChatUIKit.getDataSource().getTextMessageTemplate() @@ -1090,7 +1090,7 @@ Find the example below: -```swift +```swift lines import UIKit class CustomBubbleView: UIView { diff --git a/ui-kit/ios/methods.mdx b/ui-kit/ios/methods.mdx index 003625c2c..d59caae27 100644 --- a/ui-kit/ios/methods.mdx +++ b/ui-kit/ios/methods.mdx @@ -83,7 +83,7 @@ Replace **APP_ID**, **REGION**, and **AUTH_KEY** with your CometChat App ID, Reg -```swift +```swift lines let uiKitSettings = UIKitSettings() .set(region: "your_region") .set(appID: "your_appId") @@ -111,7 +111,7 @@ Only the `UID` of a user is needed to log in. This simple authentication procedu -```swift +```swift lines CometChatUIKit.login(uid: "uid") { (result) in switch result { case .success(let user): @@ -136,7 +136,7 @@ This advanced authentication procedure does not use the Auth Key directly in you -```swift +```swift lines CometChatUIKit.login(authToken: "your_authToken") { (result) in switch result { case .success(let user): @@ -157,7 +157,7 @@ The CometChat UI Kit and Chat SDK handle the session of the logged-in user withi -```swift +```swift lines let user = User(uid: "uid", name: "user_name") CometChatUIKit.logout(user: user) { (result) in @@ -180,7 +180,7 @@ Dynamically create users on CometChat using the `.create(user:)` function. This -```swift +```swift lines let user = User(uid: "uid", name: "user_name") CometChatUIKit.create(user: user) { result in @@ -205,7 +205,7 @@ To send a text message to a single user or a group, use the `sendTextMessage()` -```swift +```swift lines let textMessage = TextMessage(receiverUid: "uid", text: message, receiverType: .user) textMessage.muid = "\(NSDate().timeIntervalSince1970)" textMessage.sentAt = Int(Date().timeIntervalSince1970) @@ -230,7 +230,7 @@ To send a media message to a single user or a group, use the `sendMediaMessage() -```swift +```swift lines let mediaMessage = MediaMessage(receiverUid: "uid", fileurl: url, messageType: type, receiverType: .user) mediaMessage.muid = "\(NSDate().timeIntervalSince1970)" mediaMessage.sentAt = Int(Date().timeIntervalSince1970) @@ -256,7 +256,7 @@ To send a custom message to a single user or a group, use the `sendCustomMessage -```swift +```swift lines var customData = [String: Any]() customData["key"] = "value" @@ -284,7 +284,7 @@ To send a Form message to a single user or a group, use the `sendFormMessage()` -```swift +```swift lines let apiAction = APIAction() apiAction.url = "https://example.com/api" apiAction.method = .POST @@ -317,7 +317,7 @@ To send a Card message to a single user or a group, use the `sendCardMessage()` -```swift +```swift lines let apiAction = APIAction() apiAction.url = "https://example.com/api" apiAction.method = .POST @@ -346,7 +346,7 @@ To send a Scheduler message to a single user or a group, use the `sendSchedulerM -```swift +```swift lines var interactiveData = [String: Any]() interactiveData["key"] = "value" diff --git a/ui-kit/ios/ongoing-call.mdx b/ui-kit/ios/ongoing-call.mdx index 749f4aa80..d8cb0cd4d 100644 --- a/ui-kit/ios/ongoing-call.mdx +++ b/ui-kit/ios/ongoing-call.mdx @@ -54,7 +54,7 @@ The `CometChatOngoingCall` component provides users with a dedicated interface f -```swift +```swift lines // The sessionID should be received from CometChat SDK when the call was initiated or received let sessionID = "your_session_id" @@ -80,7 +80,7 @@ The `setOnCallEnded` action is typically triggered when the call ends, carrying -```swift +```swift lines let cometChatOngoingCall = CometChatOngoingCall() .setOnCallEnded { call in // Perform your action @@ -131,7 +131,7 @@ In the example below, we are applying a filter to the calls: -```swift +```swift lines let callBuilder = CallSettingsBuilder() .setAudioModeButtonDisable(true) .setEndCallButtonDisable(false) @@ -162,7 +162,7 @@ Ensure to include an `NSMicrophoneUsageDescription` key with a descriptive strin -```swift +```swift lines // View controller from your project where you want to listen to events public class ViewController: UIViewController { @@ -192,7 +192,7 @@ CometChatCallEvents.emitOnCallEnded(call: Call) -```swift +```swift lines public override func viewWillDisappear(_ animated: Bool) { // Unsubscribe from the listener CometChatCallEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") @@ -221,7 +221,7 @@ These are small functional customizations that allow you to fine-tune the overal -```swift +```swift lines let cometChatOngoingCall = CometChatOngoingCall() .set(sessionId: "Your Session ID") .set(callWorkFlow: .defaultCalling) @@ -257,7 +257,7 @@ Show the ongoing call screen after a call is accepted: -```swift +```swift lines func presentOngoingCall(sessionId: String) { let ongoingCall = CometChatOngoingCall() ongoingCall.set(sessionId: sessionId) @@ -275,7 +275,7 @@ Customize video call settings before starting: -```swift +```swift lines let callSettingsBuilder = CallSettingsBuilder() .setIsAudioOnly(false) .setDefaultAudioMode("SPEAKER") @@ -297,7 +297,7 @@ Set up an audio-only call with speaker mode: -```swift +```swift lines let audioCallSettings = CallSettingsBuilder() .setIsAudioOnly(true) .setDefaultAudioMode("SPEAKER") @@ -319,7 +319,7 @@ Use CometChatCallEvents to handle call end: -```swift +```swift lines // Subscribe to call events CometChatCallEvents.addListener("ongoing_call_listener", self as CometChatCallEventListener) diff --git a/ui-kit/ios/outgoing-call.mdx b/ui-kit/ios/outgoing-call.mdx index 5dfdc6494..3da124d7a 100644 --- a/ui-kit/ios/outgoing-call.mdx +++ b/ui-kit/ios/outgoing-call.mdx @@ -63,7 +63,7 @@ The `CometChatOutgoingCall` component is a visual representation of a user-initi -```swift +```swift lines let cometChatOutgoingCall = CometChatOutgoingCall() cometChatOutgoingCall.set(call: call) @@ -87,7 +87,7 @@ The `setOnCancelClick` action is typically triggered when the call is canceled, -```swift +```swift lines let cometChatOutgoingCall = CometChatOutgoingCall() cometChatOutgoingCall.set(onCancelClick: { call, controller in // Perform your action @@ -104,7 +104,7 @@ You can customize error handling behavior by using the provided code snippet to -```swift +```swift lines let incomingCallConfiguration = CometChatOutgoingCall() .set(onError: { error in // Perform your action @@ -134,7 +134,7 @@ The OutgoingCall component does not have any exposed filters. -```swift +```swift lines // View controller from your project where you want to listen to events public class ViewController: UIViewController { @@ -171,7 +171,7 @@ CometChatCallEvents.emitOnOutgoingCallRejected(call: Call) -```swift +```swift lines public override func viewWillDisappear(_ animated: Bool) { // Unsubscribe from the listener CometChatCallEvents.removeListener("LISTENER_ID_USED_FOR_ADDING_THIS_LISTENER") @@ -198,7 +198,7 @@ You can customize the appearance of the `OutgoingCall` Component by applying the -```swift +```swift lines let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) @@ -215,7 +215,7 @@ CometChatOutgoingCall.avatarStyle = customAvatarStyle -```swift +```swift lines let customAvatarStyle = AvatarStyle() customAvatarStyle.backgroundColor = UIColor(hex: "#FBAA75") customAvatarStyle.cornerRadius = CometChatCornerStyle(cornerRadius: 8) @@ -276,7 +276,7 @@ With this function, you can assign a custom view to the avatar of the OutgoingCa -```swift +```swift lines cometChatOutgoingCall.set(avatarView: { call in let customView = CustomAvatarView() return customView @@ -295,7 +295,7 @@ You can create a `CustomAvatarView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomAvatarView: UIView { @@ -371,7 +371,7 @@ You can modify the cancel call view of the Outgoing call component using the pro -```swift +```swift lines cometChatOutgoingCall.set(cancelView: { call in let view = CustomCancelView() return view @@ -390,7 +390,7 @@ You can create a `CustomCancelView` as a custom `UIView`: -```swift +```swift lines import UIKit class EndCallButton: UIButton { @@ -452,7 +452,7 @@ You can customize the title view of the outgoing call component using the proper -```swift +```swift lines cometChatOutgoingCall.set(titleView: { call in let view = CustomTitleView() view.configure(call: call) @@ -472,7 +472,7 @@ You can create a `CustomTitleView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomTitleView: UILabel { @@ -509,7 +509,7 @@ You can modify the subtitle view of the outgoing call component using the proper -```swift +```swift lines cometChatOutgoingCall.set(subtitleView: { call in let view = CustomSubtitleView() return view @@ -528,7 +528,7 @@ You can create a `CustomSubtitleView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomSubtitleView: UIStackView { @@ -624,7 +624,7 @@ Customizes the appearance of the recipient's avatar. | Type | `AvatarStyle` | | Default | `AvatarStyle()` | -```swift +```swift lines import CometChatUIKitSwift let customAvatarStyle = AvatarStyle() @@ -665,7 +665,7 @@ You can customize the leading view of an outgoing call component using the prope -```swift +```swift lines cometChatOutgoingCall.set(leadingView: { call in let view = CustomLeadingView() return view @@ -680,7 +680,7 @@ You can customize the trailing view of an outgoing call component using the prop -```swift +```swift lines cometChatOutgoingCall.set(trailingView: { call in let view = CustomTrailingView() return view @@ -699,7 +699,7 @@ Start a call and show the outgoing call interface: -```swift +```swift lines func initiateCall(to user: User, callType: CometChat.CallType) { let call = Call(receiverId: user.uid ?? "", callType: callType, receiverType: .user) @@ -725,7 +725,7 @@ Navigate to ongoing call when the recipient accepts: -```swift +```swift lines // Subscribe to call events CometChatCallEvents.addListener("outgoing_call_listener", self as CometChatCallEventListener) @@ -750,7 +750,7 @@ Show confirmation before canceling an outgoing call: -```swift +```swift lines let outgoingCall = CometChatOutgoingCall() outgoingCall.set(call: call) outgoingCall.set(onCancelClick: { [weak self] call, controller in diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index 8a93b1cbc..0595dad5c 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -86,7 +86,7 @@ The `CometChatSearch` component is a powerful and customizable search interface -```swift +```swift lines import CometChatUIKitSwift let search = CometChatSearch() @@ -107,7 +107,7 @@ Triggered when you click on a Conversation from the search result. This action d -```swift +```swift lines import CometChatUIKitSwift let search = CometChatSearch() @@ -126,7 +126,7 @@ Triggered when you click on a Message from the search result. This action doesn' -```swift +```swift lines import CometChatUIKitSwift let search = CometChatSearch() @@ -145,7 +145,7 @@ Triggered when you click on the back button of the search component. -```swift +```swift lines import CometChatUIKitSwift let search = CometChatSearch() @@ -164,7 +164,7 @@ Listens for any errors that occur in the Search component. This action doesn't c -```swift +```swift lines import CometChatUIKitSwift let search = CometChatSearch() @@ -183,7 +183,7 @@ Listens for the empty state of the Search component. This action doesn't change -```swift +```swift lines import CometChatUIKitSwift let search = CometChatSearch() @@ -209,7 +209,7 @@ The `SearchScope` enum defines what types of content to search: | `.conversations` | Search in conversations | | `.messages` | Search in messages | -```swift +```swift lines import CometChatUIKitSwift let search = CometChatSearch() @@ -235,7 +235,7 @@ The `SearchFilter` enum defines available filter options: | `.documents` | Filter by document messages | | `.audio` | Filter by audio messages | -```swift +```swift lines import CometChatUIKitSwift let search = CometChatSearch() @@ -250,7 +250,7 @@ Set the `ConversationsRequestBuilder` in the Search Component to filter the sear -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -271,7 +271,7 @@ Set the `MessagesRequestBuilder` in the Search Component to filter the search re -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -309,7 +309,7 @@ Using Style, you can customize the look and feel of the component in your app. T -```swift +```swift lines import CometChatUIKitSwift // Instance-level styling @@ -377,7 +377,7 @@ For advanced-level customization, you can set custom views to the component. Thi -```swift +```swift lines import CometChatUIKitSwift let searchVC = CometChatSearch() @@ -399,7 +399,7 @@ Here's how you can override the default message item view with a custom one for -```swift +```swift lines import CometChatUIKitSwift let searchVC = CometChatSearch() @@ -418,7 +418,7 @@ Custom view implementation: -```swift +```swift lines class SearchMessageItemView: UIView { // MARK: - UI Components @@ -540,7 +540,7 @@ Available message item view functions for customization: -```swift +```swift lines import CometChatUIKitSwift let searchVC = CometChatSearch() @@ -596,7 +596,7 @@ For more granular control over message search results, you can customize individ -```swift +```swift lines import CometChatUIKitSwift let searchVC = CometChatSearch() @@ -651,7 +651,7 @@ Customize the view displayed before the user enters a search query using the `in -```swift +```swift lines import CometChatUIKitSwift let searchVC = CometChatSearch() @@ -695,7 +695,7 @@ Configure how @all mentions appear in search results using the `setMentionAllLab -```swift +```swift lines import CometChatUIKitSwift let searchVC = CometChatSearch() @@ -714,7 +714,7 @@ By providing a custom implementation of the DateTimeFormatterCallback, you can c -```swift +```swift lines import CometChatUIKitSwift let searchVC = CometChatSearch() @@ -755,7 +755,7 @@ Open the search screen from a conversations list: -```swift +```swift lines @objc func openSearch() { let searchVC = CometChatSearch() @@ -791,7 +791,7 @@ Limit search to messages within a specific user or group chat: -```swift +```swift lines // Search within a specific user's conversation let searchVC = CometChatSearch() searchVC.user = user @@ -811,7 +811,7 @@ Show only photo or video messages in search results: -```swift +```swift lines let searchVC = CometChatSearch() // Set available filters with photos as the initial selection @@ -833,7 +833,7 @@ Handle search result selection with custom actions: -```swift +```swift lines let searchVC = CometChatSearch() searchVC.onMessageClicked = { [weak self] message in diff --git a/ui-kit/ios/shortcut-formatter-guide.mdx b/ui-kit/ios/shortcut-formatter-guide.mdx index 064e3616e..c9797c250 100644 --- a/ui-kit/ios/shortcut-formatter-guide.mdx +++ b/ui-kit/ios/shortcut-formatter-guide.mdx @@ -18,7 +18,7 @@ Define the `ShortCutFormatter` class by extending the `CometChatTextFormatter` c -```swift +```swift lines class ShortcutFormatter: CometChatTextFormatter { // Store fetched shortcuts from the extension @@ -37,7 +37,7 @@ Set the `trackingCharacter` to `'!'` in the initializer: -```swift +```swift lines override init(trackingCharacter: Character) { super.init(trackingCharacter: "!") } @@ -51,7 +51,7 @@ Set the regular expression for shortcut detection in the `getRegex()` method: -```swift +```swift lines override func getRegex() -> String { return "(^|\\s)!\\w+" } @@ -65,7 +65,7 @@ Define the `getTrackingCharacter()` method to return `'!'` as the shortcut track -```swift +```swift lines override func getTrackingCharacter() -> Character { return "!" } @@ -79,7 +79,7 @@ Override the `search()` method to search for shortcuts based on the entered quer -```swift +```swift lines override func search(string: String, suggestedItems: (([CometChatUIKitSwift.SuggestionItem]) -> ())? = nil) { // Fetch shortcuts from extension if not already cached @@ -124,7 +124,7 @@ Implement the `prepareMessageString()` method to convert the base chat message i -```swift +```swift lines override func prepareMessageString( baseMessage: BaseMessage, regexString: String, @@ -144,7 +144,7 @@ Override the `onTextTapped()` method if you need to handle tap events on formatt -```swift +```swift lines override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) { // Handle tap event on shortcut text } @@ -160,7 +160,7 @@ Here's the complete `ShortcutFormatter` class: -```swift +```swift lines import Foundation import CometChatSDK import CometChatUIKitSwift @@ -248,7 +248,7 @@ Create an instance of `ShortCutFormatter`: -```swift +```swift lines let shortcutFormatter = ShortcutFormatter(trackingCharacter: "!") ``` @@ -260,7 +260,7 @@ If you're using the [CometChatMessageComposer](/ui-kit/ios/message-composer) com -```swift +```swift lines let shortcutFormatter = ShortcutFormatter(trackingCharacter: "!") let cometChatMessageComposer = CometChatMessageComposer() diff --git a/ui-kit/ios/sound-manager.mdx b/ui-kit/ios/sound-manager.mdx index 00ce47729..24ecdeaaf 100644 --- a/ui-kit/ios/sound-manager.mdx +++ b/ui-kit/ios/sound-manager.mdx @@ -30,7 +30,7 @@ description: "Manage and play audio for messages and calls in CometChat UI Kit f The `play(sound:customSound:)` method triggers audio playback based on user interactions with the chat interface. If no custom sound file is provided, the default sound for that event type is played. -```swift +```swift lines play(sound: Sound, customSound: URL?) ``` @@ -43,7 +43,7 @@ play(sound: Sound, customSound: URL?) The `pause()` method stops any sound currently being played by the SoundManager. -```swift +```swift lines pause() ``` @@ -57,7 +57,7 @@ Play the default sound for an incoming message: -```swift +```swift lines // Play the default incoming message sound CometChatSoundManager().play(sound: .incomingMessage) ``` @@ -70,7 +70,7 @@ Provide a custom audio file URL to override the default sound: -```swift +```swift lines // Play a custom sound for incoming messages if let customSoundURL = Bundle.main.url(forResource: "customSound", withExtension: "wav") { CometChatSoundManager().play(sound: .incomingMessage, customSound: customSoundURL) @@ -85,7 +85,7 @@ Stop any currently playing sound: -```swift +```swift lines // Pause the currently playing sound CometChatSoundManager().pause() ``` diff --git a/ui-kit/ios/theme-introduction.mdx b/ui-kit/ios/theme-introduction.mdx index 69f6db529..b31bec8ee 100644 --- a/ui-kit/ios/theme-introduction.mdx +++ b/ui-kit/ios/theme-introduction.mdx @@ -36,7 +36,7 @@ Set up the global theme for your application during app launch. This ensures all -```swift +```swift lines import UIKit import CometChatSDK @@ -76,7 +76,7 @@ Override specific color attributes globally in `CometChatTheme`. This is equival -```swift +```swift lines // Set a custom primary color CometChatTheme.primaryColor = UIColor(hex: "#F76808") ``` diff --git a/ui-kit/ios/threaded-messages-header.mdx b/ui-kit/ios/threaded-messages-header.mdx index 6b6619bf8..0247d9793 100644 --- a/ui-kit/ios/threaded-messages-header.mdx +++ b/ui-kit/ios/threaded-messages-header.mdx @@ -60,7 +60,7 @@ Since `CometChatThreadedMessageHeader` is a view, you can add it to your view co -```swift +```swift lines let threadedMessage = CometChatThreadedMessageHeader() view.addSubview(threadedMessage) ``` @@ -85,7 +85,7 @@ In this example, we are filtering messages and searching for messages that conta -```swift +```swift lines // MARK: - Filter messages by search keyword let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() .set(uid: "your UID") @@ -122,7 +122,7 @@ To fit your app's design requirements, you can customize the appearance of the c -```swift +```swift lines // MARK: - Apply global styling CometChatThreadedMessageHeader.style.backgroundColor = UIColor(hex: "#F76808") CometChatThreadedMessageHeader.style.dividerTintColor = UIColor(hex: "#F76808") @@ -135,7 +135,7 @@ CometChatThreadedMessageHeader.style.bubbleContainerBackgroundColor = UIColor(he -```swift +```swift lines // MARK: - Apply instance-level styling let customThreadedHeaderStyle = ThreadedMessageHeaderStyle() customThreadedHeaderStyle.backgroundColor = UIColor(hex: "#F76808") @@ -200,7 +200,7 @@ You can modify the date pattern to your requirement using `.set(datePattern:)`. -```swift +```swift lines // MARK: - Custom date pattern let threadedMessageHeader = CometChatThreadedMessageHeader() threadedMessageHeader.set(datePattern: { timestamp in @@ -228,7 +228,7 @@ This code customizes a CometChat text formatter to identify and style the word " -```swift +```swift lines // MARK: - Apply custom text formatter let myCustomTextFormatter = MyCustomTextFormatter(trackingCharacter: "#") @@ -243,7 +243,7 @@ let threadedMessageHeader = CometChatThreadedMessageHeader() -```swift +```swift lines import Foundation import CometChatSDK import CometChatUIKitSwift @@ -327,7 +327,7 @@ Present the threaded messages view when a user taps on a message's reply count: -```swift +```swift lines // In your message list delegate or action handler func openThread(for parentMessage: BaseMessage) { // Create a view controller to host the threaded messages @@ -391,7 +391,7 @@ Display additional context about the parent message in the thread header: -```swift +```swift lines let threadedHeader = CometChatThreadedMessageHeader() threadedHeader.set(parentMessage: parentMessage) @@ -413,7 +413,7 @@ Show only specific types of messages in the thread: -```swift +```swift lines // Filter to show only text messages in thread let messageRequestBuilder = MessagesRequest.MessageRequestBuilder() .set(parentMessageId: parentMessage.id) @@ -431,7 +431,7 @@ messageList.set(messagesRequestBuilder: messageRequestBuilder) To ensure that the `CometChatThreadedMessageHeader` is properly configured, passing the controller is mandatory. -```swift +```swift lines let threadedMessageHeader = CometChatThreadedMessageHeader() threadedMessageHeader.set(controller: UIViewController) // Passing the controller is required ``` diff --git a/ui-kit/ios/users.mdx b/ui-kit/ios/users.mdx index 51cfb5b66..18cd430dd 100644 --- a/ui-kit/ios/users.mdx +++ b/ui-kit/ios/users.mdx @@ -129,7 +129,7 @@ The `CometChatUsers` component displays a searchable list of all available users `CometChatUsers` displays all available users for starting new conversations. It's typically used as a standalone screen or within a tab view controller. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -169,7 +169,7 @@ class UsersViewController: UIViewController { ## Minimal Render -```swift +```swift lines import CometChatUIKitSwift let users = CometChatUsers() @@ -187,7 +187,7 @@ present(navController, animated: true) Use `UsersRequest.UsersRequestBuilder` to filter which users appear in the list. The builder pattern allows chaining multiple filter conditions. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -221,7 +221,7 @@ let users = CometChatUsers(usersRequestBuilder: usersRequestBuilder) Fires when a user taps on a user in the list. Use this to start a conversation. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -240,7 +240,7 @@ users.set(onItemClick: { [weak self] user, indexPath in Fires when a user long-presses on a user. Use this to show additional options. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -268,7 +268,7 @@ users.set(onItemLongClick: { [weak self] user, indexPath in Fires when the back button is pressed. -```swift +```swift lines import CometChatUIKitSwift let users = CometChatUsers() @@ -282,7 +282,7 @@ users.set(onBack: { [weak self] in Fires when users are selected in selection mode. -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -298,7 +298,7 @@ users.set(onSelection: { [weak self] selectedUsers in Fires when an error occurs while loading users. -```swift +```swift lines import CometChatUIKitSwift let users = CometChatUsers() @@ -312,7 +312,7 @@ users.set(onError: { error in Fires when the user list is empty. -```swift +```swift lines import CometChatUIKitSwift let users = CometChatUsers() @@ -326,7 +326,7 @@ users.set(onEmpty: { Fires when users are successfully loaded. The callback receives a nested array where each inner array represents a section of users (grouped alphabetically). -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -357,7 +357,7 @@ users.set(onLoad: { userSections in | `ccUserBlocked` | A user is blocked | `User` | | `ccUserUnblocked` | A user is unblocked | `User` | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -409,7 +409,7 @@ class MyViewController: UIViewController, CometChatUserEventListener { Replace the entire user row with a custom design. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -444,7 +444,7 @@ users.set(listItemView: { user in Customize the leading view (avatar area) of a user cell. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -463,7 +463,7 @@ users.set(leadingView: { user in You can create a `CustomLeadingView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomLeadingView: UIView { @@ -533,7 +533,7 @@ class CustomLeadingView: UIView { Customize the title view of a user cell. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -552,7 +552,7 @@ users.set(titleView: { user in You can create a `CustomTitleView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomTitleView: UIView { @@ -609,7 +609,7 @@ class CustomTitleView: UIView { Customize the subtitle area below the user name. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -628,7 +628,7 @@ users.set(subtitleView: { user in You can create a `CustomSubtitleView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomSubtitleView: UILabel { @@ -651,7 +651,7 @@ class CustomSubtitleView: UILabel { Customize the trailing view (right side) of a user cell. -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -670,7 +670,7 @@ users.set(trailView: { user in You can create a `CustomTrailView` as a custom `UIView`: -```swift +```swift lines import UIKit class CustomTrailView: UIView { @@ -735,7 +735,7 @@ class CustomTrailView: UIView { Customize the loading state view displayed while data is being fetched. -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -750,7 +750,7 @@ users.set(loadingView: loadingIndicator) Customize the error state view displayed when an error occurs. -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -766,7 +766,7 @@ users.set(errorView: errorLabel) Customize the empty state view displayed when no users are available. -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -789,7 +789,7 @@ users.set(emptyView: emptyLabel) Sets custom swipe actions for user list items, replacing the default options. These options appear when the user swipes on a user cell. -```swift +```swift lines @discardableResult public func set(options: ((_ user: User?) -> [CometChatUserOption])?) -> Self ``` @@ -798,7 +798,7 @@ public func set(options: ((_ user: User?) -> [CometChatUserOption])?) -> Self |-----------|------|-------------| | `options` | `((User?) -> [CometChatUserOption])?` | Closure that returns an array of swipe action options for a user | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -840,7 +840,7 @@ users.set(options: { user in Adds additional swipe actions to the existing default options. -```swift +```swift lines @discardableResult public func add(options: ((_ user: User?) -> [CometChatUserOption])?) -> Self ``` @@ -849,7 +849,7 @@ public func add(options: ((_ user: User?) -> [CometChatUserOption])?) -> Self |-----------|------|-------------| | `options` | `((User?) -> [CometChatUserOption])?` | Closure that returns additional swipe action options to append | -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -880,7 +880,7 @@ users.add(options: { user in Adds a new user to the user list. -```swift +```swift lines @discardableResult public func add(user: User) -> Self ``` @@ -889,7 +889,7 @@ public func add(user: User) -> Self |-----------|------|-------------| | `user` | `User` | The user to add to the list | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -904,7 +904,7 @@ users.add(user: newUser) Updates an existing user in the list. -```swift +```swift lines @discardableResult public func update(user: User) -> Self ``` @@ -913,7 +913,7 @@ public func update(user: User) -> Self |-----------|------|-------------| | `user` | `User` | The user with updated information | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -930,7 +930,7 @@ if var existingUser = userToUpdate { Removes a user from the list. -```swift +```swift lines @discardableResult public func remove(user: User) -> Self ``` @@ -939,7 +939,7 @@ public func remove(user: User) -> Self |-----------|------|-------------| | `user` | `User` | The user to remove from the list | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -953,11 +953,11 @@ users.remove(user: userToRemove) Returns an array of currently selected users when in selection mode. -```swift +```swift lines public func getSelectedUsers() -> [User] ``` -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -983,7 +983,7 @@ For more complex or unique list items, you can create a custom `UIView` file nam CometChatUsers with custom listItemView showing a simplified user row with avatar and name -```swift +```swift lines import UIKit import CometChatUIKitSwift import CometChatSDK @@ -1042,7 +1042,7 @@ class CustomListItem: UIView { Usage: -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -1066,7 +1066,7 @@ users.set(listItemView: { user in ### Global Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -1085,7 +1085,7 @@ CometChatUsers.avatarStyle = avatarStyle ### Instance Level Styling -```swift +```swift lines import UIKit import CometChatUIKitSwift @@ -1148,7 +1148,7 @@ Customizes the appearance of avatars in user list items. | Type | `AvatarStyle` | | Default | `AvatarStyle()` | -```swift +```swift lines import CometChatUIKitSwift let users = CometChatUsers() @@ -1234,7 +1234,7 @@ Callback triggered when the user confirms their selection in selection mode. Use | Type | `(([User]) -> Void)?` | | Default | `nil` | -```swift +```swift lines import CometChatUIKitSwift import CometChatSDK @@ -1279,7 +1279,7 @@ Sets the maximum number of users that can be selected in selection mode. When th | Type | `Int` | | Default | `0` (unlimited) | -```swift +```swift lines import CometChatUIKitSwift let users = CometChatUsers() @@ -1317,7 +1317,7 @@ Customizes the appearance of online/offline status indicators. | Type | `StatusIndicatorStyle` | | Default | `StatusIndicatorStyle()` | -```swift +```swift lines import CometChatUIKitSwift let users = CometChatUsers() @@ -1354,7 +1354,7 @@ Custom request builder for filtering users. ### Friends-only list -```swift +```swift lines let friendsBuilder = UsersRequest.UsersRequestBuilder(limit: 30) .friendsOnly(true) @@ -1364,7 +1364,7 @@ users.set(usersRequestBuilder: friendsBuilder) ### Online users only -```swift +```swift lines let onlineBuilder = UsersRequest.UsersRequestBuilder(limit: 30) .set(status: .online) @@ -1374,7 +1374,7 @@ users.set(usersRequestBuilder: onlineBuilder) ### Custom empty state with CTA -```swift +```swift lines let users = CometChatUsers() users.set(emptyStateView: { @@ -1395,7 +1395,7 @@ users.set(emptyStateView: { ### Hide all chrome — minimal list -```swift +```swift lines let users = CometChatUsers() users.hideSearch = true users.hideUserStatus = true @@ -1404,7 +1404,7 @@ users.hideSectionHeader = true ### Multi-select users -```swift +```swift lines let users = CometChatUsers() users.selectionMode = .multiple From cb7203956a2cd3d1dd17126f837104840ec807c3 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 19:23:28 +0530 Subject: [PATCH 085/106] updates docs --- ui-kit/ios/ai-assistant-chat-history.mdx | 6 + ui-kit/ios/call-buttons.mdx | 6 + ui-kit/ios/call-logs.mdx | 6 + ui-kit/ios/conversations.mdx | 6 + ui-kit/ios/group-members.mdx | 6 + ui-kit/ios/groups.mdx | 6 + ui-kit/ios/incoming-call.mdx | 6 + ui-kit/ios/message-composer.mdx | 1113 ++++++---------------- ui-kit/ios/message-header.mdx | 6 + ui-kit/ios/message-list.mdx | 6 + ui-kit/ios/ongoing-call.mdx | 6 + ui-kit/ios/outgoing-call.mdx | 6 + ui-kit/ios/search.mdx | 6 + ui-kit/ios/threaded-messages-header.mdx | 6 + ui-kit/ios/users.mdx | 6 + 15 files changed, 355 insertions(+), 842 deletions(-) diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index 69fdaed7a..cd10a4427 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -44,6 +44,12 @@ The `CometChatAIAssistanceChatHistory` component displays past conversations bet ``` +| Field | Value | +|-------|-------| +| Component | `CometChatAIAssistantChatHistory` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Prerequisites diff --git a/ui-kit/ios/call-buttons.mdx b/ui-kit/ios/call-buttons.mdx index 06820f1e0..0c906c607 100644 --- a/ui-kit/ios/call-buttons.mdx +++ b/ui-kit/ios/call-buttons.mdx @@ -50,6 +50,12 @@ The `CometChatCallButtons` component provides users with the ability to make cal ``` +| Field | Value | +|-------|-------| +| Component | `CometChatCallButtons` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIView` | + --- ## Usage diff --git a/ui-kit/ios/call-logs.mdx b/ui-kit/ios/call-logs.mdx index 098d0a86a..ab0808108 100644 --- a/ui-kit/ios/call-logs.mdx +++ b/ui-kit/ios/call-logs.mdx @@ -58,6 +58,12 @@ The `CometChatCallLogs` component shows the list of call logs available. By defa ``` +| Field | Value | +|-------|-------| +| Component | `CometChatCallLogs` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- The `Call Logs` component is composed of the following BaseComponents: diff --git a/ui-kit/ios/conversations.mdx b/ui-kit/ios/conversations.mdx index b233cf8a5..dc9878723 100644 --- a/ui-kit/ios/conversations.mdx +++ b/ui-kit/ios/conversations.mdx @@ -110,6 +110,12 @@ The `CometChatConversations` component displays a list of all conversations (one ``` +| Field | Value | +|-------|-------| +| Component | `CometChatConversations` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Where It Fits diff --git a/ui-kit/ios/group-members.mdx b/ui-kit/ios/group-members.mdx index d597d9d0e..fde68adc1 100644 --- a/ui-kit/ios/group-members.mdx +++ b/ui-kit/ios/group-members.mdx @@ -135,6 +135,12 @@ The `CometChatGroupMembers` component displays all members of a group with their ``` +| Field | Value | +|-------|-------| +| Component | `CometChatGroupMembers` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Where It Fits diff --git a/ui-kit/ios/groups.mdx b/ui-kit/ios/groups.mdx index 7df45142a..63f51f1f3 100644 --- a/ui-kit/ios/groups.mdx +++ b/ui-kit/ios/groups.mdx @@ -128,6 +128,12 @@ The `CometChatGroups` component displays a searchable list of all available grou ``` +| Field | Value | +|-------|-------| +| Component | `CometChatGroups` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Where It Fits diff --git a/ui-kit/ios/incoming-call.mdx b/ui-kit/ios/incoming-call.mdx index 1cc0e81e4..62e8b78ae 100644 --- a/ui-kit/ios/incoming-call.mdx +++ b/ui-kit/ios/incoming-call.mdx @@ -55,6 +55,12 @@ The `CometChatIncomingCall` component serves as a visual representation when the ``` +| Field | Value | +|-------|-------| +| Component | `CometChatIncomingCall` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Usage diff --git a/ui-kit/ios/message-composer.mdx b/ui-kit/ios/message-composer.mdx index 6a23dd421..524bd6220 100644 --- a/ui-kit/ios/message-composer.mdx +++ b/ui-kit/ios/message-composer.mdx @@ -3,41 +3,19 @@ title: "Message Composer" description: "Enable users to write and send text, media, and custom messages" --- -The `CometChatMessageComposer` component enables users to write and send messages including text, images, videos, audio, files, and custom messages. It supports attachments, voice recording, stickers, mentions, and AI-powered features. - - - CometChatMessageComposer showing the default message input field with attachment, voice recording, and send buttons - - ```json { "component": "CometChatMessageComposer", "package": "CometChatUIKitSwift", "import": "import CometChatUIKitSwift\nimport CometChatSDK", - "description": "Enables users to compose and send messages with support for text, media, attachments, voice recording, stickers, mentions, and AI features.", "inherits": "UIView", - "primaryOutput": { - "callback": "onSendButtonClick", - "type": "(BaseMessage) -> Void" - }, + "description": "Rich text input for composing and sending text, media, attachments, mentions, voice notes, and custom messages.", "props": { "data": { - "user": { - "type": "User?", - "default": "nil", - "note": "User for direct messaging" - }, - "group": { - "type": "Group?", - "default": "nil", - "note": "Group for group messaging" - }, - "parentMessageId": { - "type": "Int?", - "default": "nil", - "note": "Parent message ID for thread replies" - } + "user": "User? - recipient user for direct messaging", + "group": "Group? - recipient group for group messaging", + "parentMessageId": "Int? - parent message ID for thread replies" }, "callbacks": { "onSendButtonClick": "(BaseMessage) -> Void", @@ -45,27 +23,18 @@ The `CometChatMessageComposer` component enables users to write and send message "onError": "(CometChatException) -> Void" }, "visibility": { - "hideAttachmentButton": { "type": "Bool", "default": false }, - "hideVoiceRecordingButton": { "type": "Bool", "default": false }, - "hideStickersButton": { "type": "Bool", "default": false }, - "hideSendButton": { "type": "Bool", "default": false }, - "hideAIButton": { "type": "Bool", "default": false }, - "hideHeaderView": { "type": "Bool", "default": false }, - "hideFooterView": { "type": "Bool", "default": false }, - "hideImageAttachmentOption": { "type": "Bool", "default": false }, - "hideVideoAttachmentOption": { "type": "Bool", "default": false }, - "hideAudioAttachmentOption": { "type": "Bool", "default": false }, - "hideFileAttachmentOption": { "type": "Bool", "default": false }, - "hidePollsOption": { "type": "Bool", "default": false }, - "hideCollaborativeDocumentOption": { "type": "Bool", "default": false }, - "hideCollaborativeWhiteboardOption": { "type": "Bool", "default": false } + "hideAttachmentButton": "Bool (default: false)", + "hideVoiceRecordingButton": "Bool (default: false)", + "hideStickersButton": "Bool (default: false)", + "hideSendButton": "Bool (default: false)", + "hideAIButton": "Bool (default: false)", + "hideHeaderView": "Bool (default: false)", + "hideFooterView": "Bool (default: false)" }, "behavior": { - "disableTypingEvents": { "type": "Bool", "default": false }, - "disableMentions": { "type": "Bool", "default": false }, - "disableSoundForMessages": { "type": "Bool", "default": false }, - "maxLine": { "type": "Int", "default": 5 }, - "placeholderText": { "type": "String", "default": "Type a message..." } + "disableTypingEvents": "Bool (default: false)", + "disableMentions": "Bool (default: false)", + "placeholderText": "String (default: 'Type a message...')" }, "viewSlots": { "headerView": "(User?, Group?) -> UIView", @@ -73,49 +42,43 @@ The `CometChatMessageComposer` component enables users to write and send message "sendButtonView": "(User?, Group?) -> UIView", "auxillaryButtonView": "(User?, Group?) -> UIView", "attachmentOptions": "(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]" - }, - "formatting": { - "textFormatters": "[CometChatTextFormatter]" - }, - "styling": { - "mediaRecorderStyle": { "type": "MediaRecorderStyle", "default": "MediaRecorderStyle()" }, - "attachmentSheetStyle": { "type": "AttachmentSheetStyle", "default": "AttachmentSheetStyle()" }, - "suggestionsStyle": { "type": "SuggestionsStyle", "default": "SuggestionsStyle()" }, - "aiOptionsStyle": { "type": "AIOptionsStyle", "default": "AIOptionsStyle()" }, - "mentionStyle": { "type": "MentionStyle", "default": "MentionStyle()" } } }, "methods": { - "set(textFormatter:)": "Sets a custom text formatter for the composer", - "setDisableMentionAll(_:)": "Disables or enables the @all mention feature", - "setMentionAllLabel(_:_:)": "Customizes the label for @all mentions" + "set(user:)": "Sets recipient user", + "set(group:)": "Sets recipient group", + "set(parentMessageId:)": "Sets parent message for threads", + "setInitialComposerText(_:)": "Pre-fills composer text", + "set(textFormatter:)": "Sets custom text formatter", + "setDisableMentionAll(_:)": "Disables @all mentions", + "setMentionAllLabel(_:_:)": "Customizes @all label" }, - "events": [], - "sdkListeners": [], - "compositionExample": { - "description": "MessageComposer is typically used within CometChatMessages alongside MessageHeader and MessageList", - "components": ["CometChatMessageHeader", "CometChatMessageList", "CometChatMessageComposer"], - "flow": "User types message → onTextChangedListener fires → User taps send → onSendButtonClick fires → Message sent" - }, - "types": { - "CometChatMessageComposerAction": { - "id": "String", - "text": "String", - "startIcon": "UIImage?", - "startIconTint": "UIColor?", - "textColor": "UIColor?", - "onActionClick": "() -> Void" - } + "styling": { + "globalStyle": "CometChatMessageComposer.style", + "instanceStyle": "MessageComposerStyle", + "subStyles": ["MediaRecorderStyle", "AttachmentSheetStyle", "SuggestionsStyle", "AIOptionsStyle", "MentionStyle"] } } ``` +| Field | Value | +|-------|-------| +| Component | `CometChatMessageComposer` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIView` | + +The `CometChatMessageComposer` component enables users to write and send messages including text, images, videos, audio, files, and custom messages. It supports attachments, voice recording, stickers, mentions, and AI-powered features. + + + + + --- ## Where It Fits -`CometChatMessageComposer` is the input component for sending messages. It's typically used within `CometChatMessages` alongside `CometChatMessageHeader` and `CometChatMessageList`. +`CometChatMessageComposer` provides a rich text input with attachment, emoji, voice recording, sticker, and send controls. Wire it alongside `CometChatMessageHeader` and `CometChatMessageList` to build a standard chat view. ```swift lines import UIKit @@ -124,34 +87,31 @@ import CometChatSDK class ChatViewController: UIViewController { - private var messageComposer: CometChatMessageComposer! - override func viewDidLoad() { super.viewDidLoad() - setupMessageComposer() - } - - private func setupMessageComposer(for user: User) { - messageComposer = CometChatMessageComposer() - messageComposer.set(user: user) - // Handle send button click - messageComposer.set(onSendButtonClick: { [weak self] message in - print("Message sent: \(message.id)") - }) - - // Handle text changes for typing indicators - messageComposer.set(onTextChangedListener: { [weak self] text in - print("User is typing: \(text)") - }) - - view.addSubview(messageComposer) + CometChat.getUser(UID: "uid") { user in + DispatchQueue.main.async { + let header = CometChatMessageHeader() + header.set(user: user) + + let messageList = CometChatMessageList() + messageList.set(user: user) + + let composer = CometChatMessageComposer() + composer.set(user: user) + + // Add to view hierarchy and layout + } + } onError: { error in + print("Error: \(error?.errorDescription ?? "")") + } } } ``` - CometChatMessageComposer showing integration within a chat view controller with user configuration + --- @@ -160,14 +120,13 @@ class ChatViewController: UIViewController { ```swift lines import CometChatUIKitSwift -import CometChatSDK -let messageComposer = CometChatMessageComposer() -messageComposer.set(user: user) +let composer = CometChatMessageComposer() +composer.set(user: user) ``` - CometChatMessageComposer showing minimal configuration with user set for direct messaging + --- @@ -178,60 +137,52 @@ messageComposer.set(user: user) #### onSendButtonClick -Fires when the send button is clicked. Use this to handle custom send actions. +Fires when the send button is clicked. Overrides the default send behavior. ```swift lines import CometChatUIKitSwift -import CometChatSDK -let messageComposer = CometChatMessageComposer() +let composer = CometChatMessageComposer() +composer.set(user: user) -messageComposer.set(onSendButtonClick: { [weak self] message in - guard let self = self else { return } - print("Message sent with ID: \(message.id)") +composer.set(onSendButtonClick: { message in + print("Custom send: \(message.id)") }) ``` #### onTextChangedListener -Fires when the user types in the composer. Use this for typing indicators or text validation. +Fires as the user types in the composer input. ```swift lines import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() +let composer = CometChatMessageComposer() +composer.set(user: user) -messageComposer.set(onTextChangedListener: { [weak self] text in - guard let self = self else { return } - print("Current text: \(text)") +composer.set(onTextChangedListener: { text in + print("Text changed: \(text)") }) ``` #### onError -Fires when an error occurs while sending a message. +Fires on internal errors. ```swift lines import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() +let composer = CometChatMessageComposer() +composer.set(user: user) -messageComposer.set(onError: { error in - print("Error: \(error.errorDescription)") +composer.set(onError: { error in + print("Composer error: \(error.errorDescription)") }) ``` -### Actions Reference +### SDK Events (Real-Time, Automatic) -| Method | Description | Example | -|--------|-------------|---------| -| `set(onSendButtonClick:)` | Triggered when send button is clicked | Custom send handling | -| `set(onTextChangedListener:)` | Triggered when text changes | Typing indicators | -| `set(onError:)` | Triggered when an error occurs | Show error alert | -| `set(user:)` | Sets the user for direct messaging | Configure recipient | -| `set(group:)` | Sets the group for group messaging | Configure group | -| `set(parentMessageId:)` | Sets parent message for thread replies | Thread replies | -| `setInitialComposerText(_:)` | Sets initial text in composer | Pre-fill message | +The component internally handles typing indicators and message sending. No manual SDK listener attachment needed. --- @@ -239,183 +190,104 @@ messageComposer.set(onError: { error in | Slot | Signature | Replaces | |------|-----------|----------| -| `headerView` | `(User?, Group?) -> UIView` | Header above composer | -| `footerView` | `(User?, Group?) -> UIView` | Footer below composer | +| `headerView` | `(User?, Group?) -> UIView` | Area above the composer input | +| `footerView` | `(User?, Group?) -> UIView` | Area below the composer input | | `sendButtonView` | `(User?, Group?) -> UIView` | Send button | -| `auxillaryButtonView` | `(User?, Group?) -> UIView` | Auxiliary button area | -| `attachmentOptions` | `(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]` | Attachment menu options | +| `auxillaryButtonView` | `(User?, Group?) -> UIView` | Sticker and AI button area | +| `attachmentOptions` | `(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]` | Default attachment options list | -### set(headerView:) +### headerView -Replaces the default header with a custom view above the composer. +Custom view above the composer input. -| | | -|---|---| -| Signature | `(User?, Group?) -> UIView` | -| Replaces | Default header above composer | + + + ```swift lines import UIKit import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() +let composer = CometChatMessageComposer() +composer.set(user: user) -messageComposer.set(headerView: { user, group in - let view = CustomHeaderView() +composer.set(headerView: { user, group in + let view = UIView() + view.backgroundColor = UIColor.purple.withAlphaComponent(0.1) + + let label = UILabel() + label.text = "User has paused their notifications" + label.font = UIFont.systemFont(ofSize: 14) + view.addSubview(label) + return view }) ``` - - CometChatMessageComposer with custom header view showing a notification pause message above the input field - - -You can create a `CustomHeaderView` as a custom `UIView`: - -```swift lines -import UIKit - -class CustomHeaderView: UIView { - - private let iconImageView: UIImageView = { - let imageView = UIImageView() - imageView.image = UIImage(systemName: "bell.slash.fill") - imageView.tintColor = .purple - imageView.contentMode = .scaleAspectFit - return imageView - }() - - private let messageLabel: UILabel = { - let label = UILabel() - label.text = "User has paused their notifications" - label.textColor = .black - label.font = UIFont.systemFont(ofSize: 14, weight: .medium) - return label - }() - - override init(frame: CGRect) { - super.init(frame: frame) - setupView() - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - private func setupView() { - backgroundColor = UIColor.purple.withAlphaComponent(0.1) - layer.cornerRadius = 12 - - addSubview(iconImageView) - addSubview(messageLabel) - - iconImageView.translatesAutoresizingMaskIntoConstraints = false - messageLabel.translatesAutoresizingMaskIntoConstraints = false - - NSLayoutConstraint.activate([ - iconImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12), - iconImageView.centerYAnchor.constraint(equalTo: centerYAnchor), - iconImageView.widthAnchor.constraint(equalToConstant: 20), - iconImageView.heightAnchor.constraint(equalToConstant: 20), - - messageLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 8), - messageLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12), - messageLabel.centerYAnchor.constraint(equalTo: centerYAnchor) - ]) - } -} -``` - -### set(footerView:) +### footerView -Replaces the default footer with a custom view below the composer. - -| | | -|---|---| -| Signature | `(User?, Group?) -> UIView` | -| Replaces | Default footer below composer | +Custom view below the composer input. ```swift lines import UIKit import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() +let composer = CometChatMessageComposer() +composer.set(user: user) -messageComposer.set(footerView: { user, group in - let footerView = UIView() - footerView.backgroundColor = UIColor.systemGray6 +composer.set(footerView: { user, group in + let view = UIView() let label = UILabel() label.text = "Messages are end-to-end encrypted" label.font = UIFont.systemFont(ofSize: 12) - label.textColor = UIColor.secondaryLabel - label.textAlignment = .center - - footerView.addSubview(label) - label.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - label.centerXAnchor.constraint(equalTo: footerView.centerXAnchor), - label.centerYAnchor.constraint(equalTo: footerView.centerYAnchor) - ]) + label.textColor = .secondaryLabel + view.addSubview(label) - return footerView + return view }) ``` -### set(sendButtonView:) +### sendButtonView -Replaces the default send button with a custom view. - -| | | -|---|---| -| Signature | `(User?, Group?) -> UIView` | -| Replaces | Default send button | +Replace the send button. ```swift lines import UIKit import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() +let composer = CometChatMessageComposer() +composer.set(user: user) -messageComposer.set(sendButtonView: { user, group in +composer.set(sendButtonView: { user, group in let button = UIButton(type: .system) button.setImage(UIImage(systemName: "paperplane.fill"), for: .normal) - button.tintColor = UIColor.systemBlue - button.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.1) - button.layer.cornerRadius = 20 + button.tintColor = .systemBlue return button }) ``` -{/* TODO: Add screenshot showing sendButtonView customization */} - -### set(auxillaryButtonView:) +### auxillaryButtonView -Replaces the auxiliary button area with a custom view. The auxiliary button is typically used for additional actions like AI features. - -| | | -|---|---| -| Signature | `(User?, Group?) -> UIView` | -| Replaces | Default auxiliary button area | +Replace the sticker and AI button area. ```swift lines import UIKit import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() +let composer = CometChatMessageComposer() +composer.set(user: user) -messageComposer.set(auxillaryButtonView: { user, group in +composer.set(auxillaryButtonView: { user, group in let stackView = UIStackView() stackView.axis = .horizontal stackView.spacing = 8 let aiButton = UIButton(type: .system) aiButton.setImage(UIImage(systemName: "sparkles"), for: .normal) - aiButton.tintColor = UIColor.systemPurple let emojiButton = UIButton(type: .system) emojiButton.setImage(UIImage(systemName: "face.smiling"), for: .normal) - emojiButton.tintColor = UIColor.systemOrange stackView.addArrangedSubview(aiButton) stackView.addArrangedSubview(emojiButton) @@ -424,576 +296,228 @@ messageComposer.set(auxillaryButtonView: { user, group in }) ``` -{/* TODO: Add screenshot showing auxiliaryButtonView customization */} - -### set(attachmentOptions:) +### attachmentOptions -Customizes the attachment menu options with custom actions. - -| | | -|---|---| -| Signature | `(User?, Group?, UIViewController?) -> [CometChatMessageComposerAction]` | -| Replaces | Default attachment menu options | +Override the default attachment options. ```swift lines import UIKit import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() - -messageComposer.set(attachmentOptions: { user, group, controller in - let photoAction = CometChatMessageComposerAction( - id: "photo", - text: "Photo", - startIcon: UIImage(systemName: "photo"), - startIconTint: UIColor.systemBlue, - textColor: UIColor.label, - onActionClick: { - print("Photo selected") - } - ) - - let cameraAction = CometChatMessageComposerAction( - id: "camera", - text: "Camera", - startIcon: UIImage(systemName: "camera"), - startIconTint: UIColor.systemGreen, - textColor: UIColor.label, - onActionClick: { - print("Camera selected") - } - ) - - let locationAction = CometChatMessageComposerAction( - id: "location", - text: "Location", - startIcon: UIImage(systemName: "location"), - startIconTint: UIColor.systemRed, - textColor: UIColor.label, - onActionClick: { - print("Location selected") - } - ) - - let documentAction = CometChatMessageComposerAction( - id: "document", - text: "Document", - startIcon: UIImage(systemName: "doc"), - startIconTint: UIColor.systemIndigo, - textColor: UIColor.label, - onActionClick: { - print("Document selected") - } - ) - - return [photoAction, cameraAction, locationAction, documentAction] +let composer = CometChatMessageComposer() +composer.set(user: user) + +composer.set(attachmentOptions: { user, group, controller in + return [ + CometChatMessageComposerAction( + id: "photo", + text: "Photo", + startIcon: UIImage(systemName: "photo"), + startIconTint: .systemBlue, + onActionClick: { print("Photo selected") } + ), + CometChatMessageComposerAction( + id: "camera", + text: "Camera", + startIcon: UIImage(systemName: "camera"), + startIconTint: .systemGreen, + onActionClick: { print("Camera selected") } + ), + CometChatMessageComposerAction( + id: "location", + text: "Location", + startIcon: UIImage(systemName: "location"), + startIconTint: .systemRed, + onActionClick: { print("Location selected") } + ) + ] }) ``` -{/* TODO: Add screenshot showing attachmentOptions customization */} - --- -## Styling - -### Style Hierarchy - -1. Global styles (`CometChatMessageComposer.style`) apply to all instances -2. Instance styles override global for specific instances - -### Global Level Styling - -```swift lines -import UIKit -import CometChatUIKitSwift - -// Apply global styles that affect all CometChatMessageComposer instances -CometChatMessageComposer.style.backgroundColor = UIColor.systemBackground -CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = UIColor.systemBlue -CometChatMessageComposer.style.attachmentImageTint = UIColor.systemGray -CometChatMessageComposer.style.voiceRecordingImageTint = UIColor.systemGray -CometChatMessageComposer.style.stickerTint = UIColor.systemGray -CometChatMessageComposer.style.aiImageTint = UIColor.systemPurple -``` +## Common Patterns -### Instance Level Styling +### Thread composer ```swift lines -import UIKit -import CometChatUIKitSwift - -// Create a custom style for a specific instance -var customStyle = MessageComposerStyle() -customStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) -customStyle.activeSendButtonImageBackgroundColor = UIColor.systemOrange -customStyle.composeBoxBackgroundColor = UIColor.white -customStyle.composeBoxBorderColor = UIColor.systemGray4 -customStyle.composeBoxBorderWidth = 1 - -let messageComposer = CometChatMessageComposer() -messageComposer.style = customStyle +let composer = CometChatMessageComposer() +composer.set(user: user) +composer.set(parentMessageId: parentMessage.id) ``` - - CometChatMessageComposer with custom styling showing modified background color and orange send button - - -### Key Style Properties - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `backgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Background color | -| `borderWidth` | `CGFloat` | `0` | Border width | -| `borderColor` | `UIColor` | `.clear` | Border color | -| `cornerRadius` | `CometChatCornerStyle?` | `nil` | Corner radius | -| `placeHolderTextFont` | `UIFont` | `CometChatTypography.Body.regular` | Placeholder font | -| `placeHolderTextColor` | `UIColor` | `CometChatTheme.textColorTertiary` | Placeholder color | -| `textFiledColor` | `UIColor` | `CometChatTheme.textColorPrimary` | Input text color | -| `textFiledFont` | `UIFont` | `CometChatTypography.Body.regular` | Input text font | -| `sendButtonImage` | `UIImage?` | System send icon | Send button icon | -| `sendButtonImageTint` | `UIColor` | `CometChatTheme.white` | Send button tint | -| `activeSendButtonImageBackgroundColor` | `UIColor` | `CometChatTheme.primaryColor` | Active send button background | -| `inactiveSendButtonImageBackgroundColor` | `UIColor` | `CometChatTheme.neutralColor300` | Inactive send button background | -| `composeBoxBackgroundColor` | `UIColor` | `CometChatTheme.backgroundColor01` | Compose box background | -| `composeBoxBorderColor` | `UIColor` | `CometChatTheme.borderColorDefault` | Compose box border color | -| `composeBoxBorderWidth` | `CGFloat` | `1` | Compose box border width | -| `attachmentImage` | `UIImage?` | System plus icon | Attachment button icon | -| `attachmentImageTint` | `UIColor` | `CometChatTheme.iconColorSecondary` | Attachment icon tint | -| `voiceRecordingImage` | `UIImage?` | System mic icon | Voice recording icon | -| `voiceRecordingImageTint` | `UIColor` | `CometChatTheme.iconColorSecondary` | Voice recording tint | - -### Style Properties - -#### mediaRecorderStyle - -Customizes the appearance of the media recorder (voice recording) interface. - -| | | -|---|---| -| Type | `MediaRecorderStyle` | -| Default | `MediaRecorderStyle()` | +### Minimal composer — text only ```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() - -let mediaRecorderStyle = MediaRecorderStyle() -mediaRecorderStyle.backgroundColor = UIColor.systemBackground -mediaRecorderStyle.recordButtonTint = UIColor.systemRed -mediaRecorderStyle.timerTextColor = UIColor.label - -messageComposer.mediaRecorderStyle = mediaRecorderStyle +let composer = CometChatMessageComposer() +composer.set(user: user) +composer.hideAttachmentButton = true +composer.hideVoiceRecordingButton = true +composer.hideStickersButton = true +composer.hideAIButton = true ``` -#### attachmentSheetStyle - -Customizes the appearance of the attachment options sheet. - -| | | -|---|---| -| Type | `AttachmentSheetStyle` | -| Default | `AttachmentSheetStyle()` | +### Pre-filled text ```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() - -let attachmentSheetStyle = AttachmentSheetStyle() -attachmentSheetStyle.backgroundColor = UIColor.systemBackground -attachmentSheetStyle.iconTint = UIColor.systemBlue -attachmentSheetStyle.titleColor = UIColor.label - -messageComposer.attachmentSheetStyle = attachmentSheetStyle +let composer = CometChatMessageComposer() +composer.set(user: user) +composer.setInitialComposerText("Hello! ") +composer.placeholderText = "Type a message..." ``` -#### suggestionsStyle - -Customizes the appearance of the suggestions view (for mentions and other suggestions). - -| | | -|---|---| -| Type | `SuggestionsStyle` | -| Default | `SuggestionsStyle()` | +### Disable typing indicators ```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() - -let suggestionsStyle = SuggestionsStyle() -suggestionsStyle.backgroundColor = UIColor.systemBackground -suggestionsStyle.textColor = UIColor.label -suggestionsStyle.separatorColor = UIColor.separator - -messageComposer.suggestionsStyle = suggestionsStyle +let composer = CometChatMessageComposer() +composer.set(user: user) +composer.disableTypingEvents = true ``` -#### aiOptionsStyle - -Customizes the appearance of the AI options menu. - -| | | -|---|---| -| Type | `AIOptionsStyle` | -| Default | `AIOptionsStyle()` | +### Disable mentions ```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() - -let aiOptionsStyle = AIOptionsStyle() -aiOptionsStyle.backgroundColor = UIColor.systemBackground -aiOptionsStyle.iconTint = UIColor.systemPurple -aiOptionsStyle.titleColor = UIColor.label - -messageComposer.aiOptionsStyle = aiOptionsStyle +let composer = CometChatMessageComposer() +composer.set(user: user) +composer.disableMentions = true ``` -#### mentionStyle - -Customizes the appearance of mentions in the composer. - -| | | -|---|---| -| Type | `MentionStyle` | -| Default | `MentionStyle()` | +### Custom send button action ```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() - -let mentionStyle = MentionStyle() -mentionStyle.textColor = UIColor.systemBlue -mentionStyle.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.1) -mentionStyle.font = UIFont.systemFont(ofSize: 16, weight: .medium) +let composer = CometChatMessageComposer() +composer.set(user: user) -messageComposer.mentionStyle = mentionStyle +composer.set(onSendButtonClick: { message in + print("Sending message: \(message)") +}) ``` -### Customization Matrix - -| What to change | Where | Property/API | Example | -|----------------|-------|--------------|---------| -| Background color | Style | `backgroundColor` | `UIColor.systemBackground` | -| Send button color | Style | `activeSendButtonImageBackgroundColor` | `UIColor.systemBlue` | -| Input text style | Style | `textFiledColor`, `textFiledFont` | Custom colors and fonts | -| Compose box look | Style | `composeBoxBackgroundColor`, `composeBoxBorderColor` | Custom styling | -| Attachment icon | Style | `attachmentImage`, `attachmentImageTint` | Custom icon | -| Media recorder | Style | `mediaRecorderStyle` | Custom MediaRecorderStyle | -| Attachment sheet | Style | `attachmentSheetStyle` | Custom AttachmentSheetStyle | -| Suggestions | Style | `suggestionsStyle` | Custom SuggestionsStyle | -| AI options | Style | `aiOptionsStyle` | Custom AIOptionsStyle | -| Mentions | Style | `mentionStyle` | Custom MentionStyle | -| Hide attachment | Property | `hideAttachmentButton` | `composer.hideAttachmentButton = true` | -| Hide voice recording | Property | `hideVoiceRecordingButton` | `composer.hideVoiceRecordingButton = true` | -| Hide AI button | Property | `hideAIButton` | `composer.hideAIButton = true` | -| Hide header | Property | `hideHeaderView` | `composer.hideHeaderView = true` | -| Hide footer | Property | `hideFooterView` | `composer.hideFooterView = true` | -| Placeholder text | Property | `placeholderText` | `composer.placeholderText = "..."` | -| Custom send button | View Slot | `set(sendButtonView:)` | See Custom View Slots | -| Custom header | View Slot | `set(headerView:)` | See Custom View Slots | -| Custom footer | View Slot | `set(footerView:)` | See Custom View Slots | -| Custom auxiliary | View Slot | `set(auxillaryButtonView:)` | See Custom View Slots | -| Custom attachments | View Slot | `set(attachmentOptions:)` | See Custom View Slots | - --- -## Props - -All props are optional. Sorted alphabetically. - -### disableMentions - -Disables the @mention feature in the composer. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -### disableSoundForMessages - -Disables sound when sending messages. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -### disableTypingEvents - -Disables sending typing indicators when the user types. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -### hideAttachmentButton - -Hides the attachment button. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -### hideAIButton - -Hides the AI button in the composer. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.hideAIButton = true -``` - -### hideAudioAttachmentOption - -Hides the audio attachment option. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -### hideCollaborativeDocumentOption - -Hides the collaborative document option in the attachment menu. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.hideCollaborativeDocumentOption = true -``` - -### hideCollaborativeWhiteboardOption - -Hides the collaborative whiteboard option in the attachment menu. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.hideCollaborativeWhiteboardOption = true -``` - -### hideFileAttachmentOption - -Hides the file attachment option in the attachment menu. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.hideFileAttachmentOption = true -``` - -### hideFooterView - -Hides the footer view below the composer. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.hideFooterView = true -``` - -### hideHeaderView - -Hides the header view above the composer. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.hideHeaderView = true -``` - -### hideImageAttachmentOption - -Hides the image attachment option in the attachment menu. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.hideImageAttachmentOption = true -``` - -### hidePollsOption - -Hides the polls option in the attachment menu. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.hidePollsOption = true -``` +## Styling -### hideSendButton +### Style Hierarchy -Hides the send button. +1. Global styles (`CometChatMessageComposer.style`) apply to all instances +2. Instance styles override global for specific instances -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | +### Global Level Styling ```swift lines import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() -messageComposer.hideSendButton = true +CometChatMessageComposer.style.backgroundColor = .systemBackground +CometChatMessageComposer.style.activeSendButtonImageBackgroundColor = .systemBlue +CometChatMessageComposer.style.attachmentImageTint = .systemGray +CometChatMessageComposer.style.voiceRecordingImageTint = .systemGray ``` -### hideStickersButton - -Hides the stickers button. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | +### Instance Level Styling ```swift lines import CometChatUIKitSwift -let messageComposer = CometChatMessageComposer() -messageComposer.hideStickersButton = true -``` - -### hideVideoAttachmentOption - -Hides the video attachment option in the attachment menu. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -```swift lines -import CometChatUIKitSwift +var customStyle = MessageComposerStyle() +customStyle.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.97, alpha: 1.0) +customStyle.activeSendButtonImageBackgroundColor = .systemOrange +customStyle.composeBoxBackgroundColor = .white +customStyle.composeBoxBorderColor = .systemGray4 -let messageComposer = CometChatMessageComposer() -messageComposer.hideVideoAttachmentOption = true +let composer = CometChatMessageComposer() +composer.style = customStyle ``` -### hideVoiceRecordingButton - -Hides the voice recording button. - -| | | -|---|---| -| Type | `Bool` | -| Default | `false` | - -### maxLine - -Sets the maximum number of lines for the composer input before scrolling. + + + -| | | -|---|---| -| Type | `Int` | -| Default | `5` | +### Key Style Properties -### placeholderText +| Property | Type | Description | +|----------|------|-------------| +| `backgroundColor` | `UIColor` | Background color | +| `borderWidth` | `CGFloat` | Border width | +| `borderColor` | `UIColor` | Border color | +| `cornerRadius` | `CometChatCornerStyle?` | Corner radius | +| `placeHolderTextFont` | `UIFont` | Placeholder font | +| `placeHolderTextColor` | `UIColor` | Placeholder color | +| `textFiledColor` | `UIColor` | Input text color | +| `textFiledFont` | `UIFont` | Input text font | +| `sendButtonImage` | `UIImage?` | Send button icon | +| `sendButtonImageTint` | `UIColor` | Send button tint | +| `activeSendButtonImageBackgroundColor` | `UIColor` | Active send button background | +| `inactiveSendButtonImageBackgroundColor` | `UIColor` | Inactive send button background | +| `composeBoxBackgroundColor` | `UIColor` | Compose box background | +| `composeBoxBorderColor` | `UIColor` | Compose box border color | +| `composeBoxBorderWidth` | `CGFloat` | Compose box border width | +| `attachmentImage` | `UIImage?` | Attachment button icon | +| `attachmentImageTint` | `UIColor` | Attachment icon tint | +| `voiceRecordingImage` | `UIImage?` | Voice recording icon | +| `voiceRecordingImageTint` | `UIColor` | Voice recording tint | + +### Sub-Component Styles + +| Property | Type | Description | +|----------|------|-------------| +| `mediaRecorderStyle` | `MediaRecorderStyle` | Voice recording interface | +| `attachmentSheetStyle` | `AttachmentSheetStyle` | Attachment options sheet | +| `suggestionsStyle` | `SuggestionsStyle` | Mentions suggestions view | +| `aiOptionsStyle` | `AIOptionsStyle` | AI options menu | +| `mentionStyle` | `MentionStyle` | Mentions appearance | -Sets the placeholder text displayed in the composer input field when empty. +### Customization Matrix -| | | -|---|---| -| Type | `String` | -| Default | `"Type a message..."` | +| What to change | Where | Property/API | +|----------------|-------|--------------| +| Override send behavior | Callback | `set(onSendButtonClick:)` | +| Track text input | Callback | `set(onTextChangedListener:)` | +| Toggle visibility | Props | `hide` boolean props | +| Custom attachments | View Slot | `set(attachmentOptions:)` | +| Replace UI sections | View Slot | `set(headerView:)`, `set(sendButtonView:)` | +| Change colors, fonts | Style | `MessageComposerStyle` properties | -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() -messageComposer.placeholderText = "Write your message here..." -``` +--- -### textFormatters +## Props -Array of text formatters for customizing text display (e.g., mentions). +All props are optional. Sorted alphabetically. -| | | -|---|---| -| Type | `[CometChatTextFormatter]` | -| Default | `[]` | +| Property | Type | Default | Description | +|----------|------|---------|-------------| +| `disableMentions` | `Bool` | `false` | Disables the @mention feature | +| `disableSoundForMessages` | `Bool` | `false` | Disables sound when sending messages | +| `disableTypingEvents` | `Bool` | `false` | Disables sending typing indicators | +| `hideAIButton` | `Bool` | `false` | Hides the AI button | +| `hideAttachmentButton` | `Bool` | `false` | Hides the attachment button | +| `hideAudioAttachmentOption` | `Bool` | `false` | Hides the audio attachment option | +| `hideCollaborativeDocumentOption` | `Bool` | `false` | Hides the collaborative document option | +| `hideCollaborativeWhiteboardOption` | `Bool` | `false` | Hides the collaborative whiteboard option | +| `hideFileAttachmentOption` | `Bool` | `false` | Hides the file attachment option | +| `hideFooterView` | `Bool` | `false` | Hides the footer view | +| `hideHeaderView` | `Bool` | `false` | Hides the header view | +| `hideImageAttachmentOption` | `Bool` | `false` | Hides the image attachment option | +| `hidePollsOption` | `Bool` | `false` | Hides the polls option | +| `hideSendButton` | `Bool` | `false` | Hides the send button | +| `hideStickersButton` | `Bool` | `false` | Hides the stickers button | +| `hideVideoAttachmentOption` | `Bool` | `false` | Hides the video attachment option | +| `hideVoiceRecordingButton` | `Bool` | `false` | Hides the voice recording button | +| `maxLine` | `Int` | `5` | Maximum lines before scrolling | +| `placeholderText` | `String` | `"Type a message..."` | Placeholder text | +| `textFormatters` | `[CometChatTextFormatter]` | `[]` | Custom text formatters | --- -## Text Formatter and Mention Methods +## Methods ### set(textFormatter:) Sets a custom text formatter for the composer input. ```swift lines -@discardableResult -public func set(textFormatter: CometChatTextFormatter) -> Self -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `textFormatter` | `CometChatTextFormatter` | The text formatter to apply | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() - +let composer = CometChatMessageComposer() let mentionFormatter = MentionTextFormatter(trackingCharacter: "@") -messageComposer.set(textFormatter: mentionFormatter) +composer.set(textFormatter: mentionFormatter) ``` ### setDisableMentionAll(_:) @@ -1001,21 +525,8 @@ messageComposer.set(textFormatter: mentionFormatter) Disables or enables the @all mention feature that notifies all group members. ```swift lines -@discardableResult -public func setDisableMentionAll(_ disable: Bool) -> Self -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `disable` | `Bool` | Whether to disable the @all mention feature | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() - -// Disable @all mentions -messageComposer.setDisableMentionAll(true) +let composer = CometChatMessageComposer() +composer.setDisableMentionAll(true) ``` ### setMentionAllLabel(_:_:) @@ -1023,96 +534,14 @@ messageComposer.setDisableMentionAll(true) Customizes the label displayed for @all mentions in the suggestions list. ```swift lines -@discardableResult -public func setMentionAllLabel(_ title: String, _ subtitle: String) -> Self -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `title` | `String` | The title for the @all mention | -| `subtitle` | `String` | The subtitle for the @all mention | - -```swift lines -import CometChatUIKitSwift - -let messageComposer = CometChatMessageComposer() - -// Customize the @all mention label -messageComposer.setMentionAllLabel("Everyone", "Notify all members in this group") -``` - ---- - -## Events - -The MessageComposer component does not emit any global UI events. - ---- - -## Common Patterns - -### Hide attachment options - -```swift lines -let messageComposer = CometChatMessageComposer() -messageComposer.set(user: user) -messageComposer.hideImageAttachmentOption = true -messageComposer.hideVideoAttachmentOption = true -messageComposer.hideAudioAttachmentOption = true -messageComposer.hideFileAttachmentOption = true -``` - -### Hide all auxiliary buttons - -```swift lines -let messageComposer = CometChatMessageComposer() -messageComposer.set(user: user) -messageComposer.hideAttachmentButton = true -messageComposer.hideVoiceRecordingButton = true -messageComposer.hideStickersButton = true -``` - -### Disable typing indicators - -```swift lines -let messageComposer = CometChatMessageComposer() -messageComposer.set(user: user) -messageComposer.disableTypingEvents = true -``` - -### Disable mentions - -```swift lines -let messageComposer = CometChatMessageComposer() -messageComposer.set(user: user) -messageComposer.disableMentions = true -``` - -### Custom send button action - -```swift lines -let messageComposer = CometChatMessageComposer() -messageComposer.set(user: user) - -messageComposer.set(onSendButtonClick: { message in - // Custom send logic - print("Sending message: \(message)") -}) -``` - -### Disable message sounds - -```swift lines -let messageComposer = CometChatMessageComposer() -messageComposer.set(user: user) -messageComposer.disableSoundForMessages = true +let composer = CometChatMessageComposer() +composer.setMentionAllLabel("Everyone", "Notify all members in this group") ``` --- ## Related Components -- [Message List](/ui-kit/ios/message-list) - Display messages in a conversation -- [Message Header](/ui-kit/ios/message-header) - Display user/group details -- [Messages](/ui-kit/ios/messages) - Parent component containing MessageComposer -- [Mentions Formatter](/ui-kit/ios/mentions-formatter-guide) - Configure @mention formatting +- [Message List](/ui-kit/ios/message-list) — Display messages in a conversation +- [Message Header](/ui-kit/ios/message-header) — Display user/group details +- [Mentions Formatter](/ui-kit/ios/mentions-formatter-guide) — Configure @mention formatting diff --git a/ui-kit/ios/message-header.mdx b/ui-kit/ios/message-header.mdx index 75b1cf2f7..8ef148d9c 100644 --- a/ui-kit/ios/message-header.mdx +++ b/ui-kit/ios/message-header.mdx @@ -91,6 +91,12 @@ The `CometChatMessageHeader` component displays user or group details in the too ``` +| Field | Value | +|-------|-------| +| Component | `CometChatMessageHeader` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIView` | + --- ## Where It Fits diff --git a/ui-kit/ios/message-list.mdx b/ui-kit/ios/message-list.mdx index 061a6190b..8f1c3fc9e 100644 --- a/ui-kit/ios/message-list.mdx +++ b/ui-kit/ios/message-list.mdx @@ -119,6 +119,12 @@ The `CometChatMessageList` component displays a scrollable list of messages in a ``` +| Field | Value | +|-------|-------| +| Component | `CometChatMessageList` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Where It Fits diff --git a/ui-kit/ios/ongoing-call.mdx b/ui-kit/ios/ongoing-call.mdx index d8cb0cd4d..3d5ecef29 100644 --- a/ui-kit/ios/ongoing-call.mdx +++ b/ui-kit/ios/ongoing-call.mdx @@ -44,6 +44,12 @@ The `CometChatOngoingCall` component provides users with a dedicated interface f ``` +| Field | Value | +|-------|-------| +| Component | `CometChatOngoingCall` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Usage diff --git a/ui-kit/ios/outgoing-call.mdx b/ui-kit/ios/outgoing-call.mdx index 3da124d7a..1d1a0cdc1 100644 --- a/ui-kit/ios/outgoing-call.mdx +++ b/ui-kit/ios/outgoing-call.mdx @@ -53,6 +53,12 @@ The `CometChatOutgoingCall` component is a visual representation of a user-initi ``` +| Field | Value | +|-------|-------| +| Component | `CometChatOutgoingCall` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Usage diff --git a/ui-kit/ios/search.mdx b/ui-kit/ios/search.mdx index 0595dad5c..ad10e566b 100644 --- a/ui-kit/ios/search.mdx +++ b/ui-kit/ios/search.mdx @@ -76,6 +76,12 @@ The `CometChatSearch` component is a powerful and customizable search interface ``` +| Field | Value | +|-------|-------| +| Component | `CometChatSearch` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Usage diff --git a/ui-kit/ios/threaded-messages-header.mdx b/ui-kit/ios/threaded-messages-header.mdx index 0247d9793..fdd01da71 100644 --- a/ui-kit/ios/threaded-messages-header.mdx +++ b/ui-kit/ios/threaded-messages-header.mdx @@ -41,6 +41,12 @@ The `CometChatThreadedMessageHeader` component displays the header for threaded ``` +| Field | Value | +|-------|-------| +| Component | `CometChatThreadedMessageHeader` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIView` | + --- ThreadedMessages is composed of the following components: diff --git a/ui-kit/ios/users.mdx b/ui-kit/ios/users.mdx index 18cd430dd..28369c4ab 100644 --- a/ui-kit/ios/users.mdx +++ b/ui-kit/ios/users.mdx @@ -123,6 +123,12 @@ The `CometChatUsers` component displays a searchable list of all available users ``` +| Field | Value | +|-------|-------| +| Component | `CometChatUsers` | +| Package | `CometChatUIKitSwift` | +| Inherits | `UIViewController` | + --- ## Where It Fits From c599fc2dc1233323bf5e914bfa792c15bf9dc40f Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Fri, 20 Mar 2026 19:25:57 +0530 Subject: [PATCH 086/106] Update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4669a449e..2b6c95161 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ __pycache__/ /docs-templates /docs-test-suite /prompts +/docs-comparison-tool From b61fc2be4bc894e3ef326683f638b7d34d2bafe8 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:19:18 +0530 Subject: [PATCH 087/106] Update overview.mdx --- ui-kit/ios/overview.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/ios/overview.mdx b/ui-kit/ios/overview.mdx index dc56ca772..2e5a38b0e 100644 --- a/ui-kit/ios/overview.mdx +++ b/ui-kit/ios/overview.mdx @@ -124,7 +124,7 @@ Before integrating the CometChat UI Kit, familiarize yourself with the key conce Customize the look and feel - + Common issues and solutions From adde1c979f19c0b7d1fbae498eb64741404e3ce1 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:20:08 +0530 Subject: [PATCH 088/106] Update upgrading-from-v4.mdx --- ui-kit/ios/upgrading-from-v4.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/ios/upgrading-from-v4.mdx b/ui-kit/ios/upgrading-from-v4.mdx index 19ed98fae..21f974ad7 100644 --- a/ui-kit/ios/upgrading-from-v4.mdx +++ b/ui-kit/ios/upgrading-from-v4.mdx @@ -1,6 +1,6 @@ --- title: "Upgrading from V4 to V5" -sidebarTitle: "Upgrading from V4" +sidebarTitle: "Upgrading from V4 to V5" description: "Migration guide for upgrading from CometChat iOS UI Kit v4 to v5 with breaking changes, property updates, and new patterns." --- From 51c146f4233f2455c96f51f27729f2277e2105c9 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:23:57 +0530 Subject: [PATCH 089/106] Update getting-started.mdx --- ui-kit/ios/getting-started.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-kit/ios/getting-started.mdx b/ui-kit/ios/getting-started.mdx index 1d938dc54..007725f07 100644 --- a/ui-kit/ios/getting-started.mdx +++ b/ui-kit/ios/getting-started.mdx @@ -129,7 +129,7 @@ https://github.com/cometchat/chat-sdk-ios Add these keys to your `Info.plist` for media messaging: -```xml title="Info.plist" +```xml title="Info.plist" lines NSCameraUsageDescription Allow access to the camera to capture photos and videos. @@ -165,7 +165,7 @@ Also disable **User Script Sandboxing** in Build Settings to ensure WebView can Add this to your `SceneDelegate.swift`. Init must complete before login, and login must complete before rendering any UI. -```swift title="SceneDelegate.swift" +```swift title="SceneDelegate.swift" lines import UIKit import CometChatUIKitSwift import CometChatSDK From ec771df23f0861d7173cfd04e0275e99a4e5fcf4 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:28:52 +0530 Subject: [PATCH 090/106] Update troubleshooting.mdx --- ui-kit/ios/troubleshooting.mdx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/ui-kit/ios/troubleshooting.mdx b/ui-kit/ios/troubleshooting.mdx index 0926b84b5..c41aba14c 100644 --- a/ui-kit/ios/troubleshooting.mdx +++ b/ui-kit/ios/troubleshooting.mdx @@ -63,9 +63,9 @@ If CocoaPods continues to fail, use SPM instead: | Issue | Solution | |-------|----------| -| SDK not initialized | Call `CometChat.init()` before any UI Kit operations | -| User not logged in | Ensure `CometChat.login()` completes successfully before showing UI | -| UIKit not initialized | Call `CometChatUIKit.init()` after SDK init and before using components | +| SDK not initialized | Call `CometChatUIKit.init(uiKitSettings:)` before any UI Kit operations | +| User not logged in | Ensure `CometChatUIKit.login(uid:)` completes successfully before showing UI | +| Init/login order wrong | `init()` must complete before `login()`, and `login()` must complete before rendering components | | Credentials invalid | Verify App ID, Auth Key, and Region in CometChat Dashboard | --- @@ -235,12 +235,12 @@ Add these keys to your `Info.plist` for full functionality: When troubleshooting issues, verify the following: 1. **SDK Initialization** - - `CometChat.init()` called with correct App ID and Region - - `CometChatUIKit.init()` called after SDK init + - `CometChatUIKit.init(uiKitSettings:)` called with correct App ID, Region, and Auth Key + - Init must complete before calling `login()` 2. **User Authentication** - - User is logged in via `CometChat.login()` - - Auth token is valid and not expired + - User is logged in via `CometChatUIKit.login(uid:)` + - Auth token is valid and not expired (if using `loginWithAuthToken()`) 3. **Dashboard Settings** - Features are enabled (AI, Reactions, etc.) From d3bb35b8c32ead739e994c53a44f6d88380f9530 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:30:31 +0530 Subject: [PATCH 091/106] Update troubleshooting.mdx --- ui-kit/ios/troubleshooting.mdx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/ui-kit/ios/troubleshooting.mdx b/ui-kit/ios/troubleshooting.mdx index c41aba14c..915db1c71 100644 --- a/ui-kit/ios/troubleshooting.mdx +++ b/ui-kit/ios/troubleshooting.mdx @@ -10,8 +10,8 @@ description: "Common issues and solutions for CometChat iOS UI Kit" | --- | --- | | Platform | iOS UI Kit | | Common Issues | Initialization, theming, real-time updates, permissions | -| Key Checks | SDK initialization, user login, CometChatUIKit.init() order | -| Permissions | Camera, microphone (Info.plist) | +| Key Checks | CometChatUIKit.init(uiKitSettings:), user login, init/login order | +| Permissions | Camera, microphone, photo library (Info.plist) | | Debug | Check SDK connection status, verify dashboard settings | @@ -175,7 +175,7 @@ If CocoaPods continues to fail, use SPM instead: | Call buttons not showing | Verify `CometChatCallsSDK` is in Podfile and run `pod install` | | "Permission denied" error | Add camera/microphone permissions to Info.plist | | Calls not connecting | Check network connection and CometChat credentials | -| No incoming call UI | Ensure `CometChatCallsSDK` is initialized before login | +| No incoming call UI | Verify `CometChatCallsSDK` is installed and user is logged in | | Audio not working | Check device is not on silent mode | --- @@ -226,6 +226,10 @@ Add these keys to your `Info.plist` for full functionality: NSPhotoLibraryUsageDescription Photo library access is required to send images + + +NSPhotoLibraryAddUsageDescription +Allow saving photos and videos to your device's photo library ``` --- From 32eca522962097139d50a040751bebfede944651 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:32:59 +0530 Subject: [PATCH 092/106] Update overview.mdx --- ui-kit/ios/overview.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/ios/overview.mdx b/ui-kit/ios/overview.mdx index 2e5a38b0e..84175cb8a 100644 --- a/ui-kit/ios/overview.mdx +++ b/ui-kit/ios/overview.mdx @@ -9,7 +9,7 @@ description: "Integrate chat functionality into iOS applications with prebuilt, { "platform": "iOS UI Kit", "package": "CometChatUIKitSwift", - "version": "5.0.0", + "version": "5.1.9", "description": "Pre-built UI components for iOS chat applications using SwiftUI", "metadata": { "peerDependencies": { From 4fa39f95a3f8227c58ad71863165abcc678269e7 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:33:50 +0530 Subject: [PATCH 093/106] updates version --- ui-kit/ios/components-overview.mdx | 2 +- ui-kit/ios/overview.mdx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-kit/ios/components-overview.mdx b/ui-kit/ios/components-overview.mdx index 7c7e5d6c7..e58a7fc7f 100644 --- a/ui-kit/ios/components-overview.mdx +++ b/ui-kit/ios/components-overview.mdx @@ -9,7 +9,7 @@ description: "Understanding CometChat iOS UI Kit components - types, actions, ev { "platform": "iOS UI Kit", "package": "CometChatUIKitSwift", - "version": "5.0.0", + "version": "5.1.9", "componentTypes": { "base": "Simple UI elements with no business logic", "components": "UI elements with built-in business logic", diff --git a/ui-kit/ios/overview.mdx b/ui-kit/ios/overview.mdx index 84175cb8a..588cf3fee 100644 --- a/ui-kit/ios/overview.mdx +++ b/ui-kit/ios/overview.mdx @@ -31,7 +31,7 @@ description: "Integrate chat functionality into iOS applications with prebuilt, | Property | Value | |----------|-------| | Package | CometChatUIKitSwift | -| Version | 5.0.0 | +| Version | 5.1.9 | | Peer Dependencies | CometChatSDK >= 4.0.0 | | Platforms | iOS 13.0+, iPadOS 13.0+, Mac Catalyst 13.0+ | | Language | Swift 5.0+ | From 11351b9f0100815be454ee8f4a4c6e8873b66588 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:34:04 +0530 Subject: [PATCH 094/106] Update call-features.mdx --- ui-kit/ios/call-features.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/ios/call-features.mdx b/ui-kit/ios/call-features.mdx index 1505803e6..863aef8e3 100644 --- a/ui-kit/ios/call-features.mdx +++ b/ui-kit/ios/call-features.mdx @@ -45,7 +45,7 @@ platform :ios, '13.0' use_frameworks! target 'YourApp' do - pod 'CometChatUIKitSwift', '5.1.7' + pod 'CometChatUIKitSwift', '5.1.9' pod 'CometChatCallsSDK', '4.2.2' end ``` From a37670654abd604a5ba2647fdb7da84a85291ac8 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 11:35:51 +0530 Subject: [PATCH 095/106] version fixes --- ui-kit/ios/ai-assistant-chat-history.mdx | 2 +- ui-kit/ios/theme-introduction.mdx | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ui-kit/ios/ai-assistant-chat-history.mdx b/ui-kit/ios/ai-assistant-chat-history.mdx index cd10a4427..a811738d7 100644 --- a/ui-kit/ios/ai-assistant-chat-history.mdx +++ b/ui-kit/ios/ai-assistant-chat-history.mdx @@ -58,7 +58,7 @@ The `CometChatAIAssistanceChatHistory` component displays past conversations bet Add to your Podfile: ```ruby -pod 'CometChatUIKitSwift', '5.1.7' +pod 'CometChatUIKitSwift', '5.1.9' ``` Run `pod install` diff --git a/ui-kit/ios/theme-introduction.mdx b/ui-kit/ios/theme-introduction.mdx index b31bec8ee..fcf5b7747 100644 --- a/ui-kit/ios/theme-introduction.mdx +++ b/ui-kit/ios/theme-introduction.mdx @@ -16,6 +16,7 @@ description: "Create visually consistent and customizable user interfaces with C | Border Colors | `CometChatTheme.borderColorDefault`, `borderColorLight`, `borderColorDark` | | Typography Class | `CometChatTypography` | | Typography Properties | `Body.regular`, `Body.bold`, `Heading.regular` | +| Apply Timing | Set theme before `CometChatUIKit.init()` | | Example | `CometChatTheme.primaryColor = UIColor(hex: "#F76808")` | From 2865e13614abf9b915aceb002dd8bf936c27864b Mon Sep 17 00:00:00 2001 From: "Raj Shah(CometChat)" Date: Mon, 23 Mar 2026 16:39:53 +0530 Subject: [PATCH 096/106] Added android code and updated versions --- ui-kit/flutter/getting-started.mdx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/ui-kit/flutter/getting-started.mdx b/ui-kit/flutter/getting-started.mdx index df8966cce..15281ce0f 100644 --- a/ui-kit/flutter/getting-started.mdx +++ b/ui-kit/flutter/getting-started.mdx @@ -61,8 +61,8 @@ Add to your `pubspec.yaml`: dependencies: flutter: sdk: flutter - cometchat_chat_uikit: ^5.2.10 - cometchat_calls_uikit: ^5.0.12 # Optional: for voice/video calling + cometchat_chat_uikit: ^5.2.11 + cometchat_calls_uikit: ^5.0.13 # Optional: for voice/video calling ``` Then run: @@ -71,7 +71,13 @@ Then run: flutter pub get ``` -**Android Setup** — Update `android/app/build.gradle`: +**Android Setup** — Add the following to `android/gradle.properties`: + +```properties gradle.properties +android.enableJetifier=true +``` + +Then update `android/app/build.gradle`: ```gradle build.gradle android { From adb26a04234904c39100ad5a682b6bf75dff03cd Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 18:36:33 +0530 Subject: [PATCH 097/106] Update conversations.mdx --- ui-kit/flutter/conversations.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/flutter/conversations.mdx b/ui-kit/flutter/conversations.mdx index 9bda2cc3e..9f6b27290 100644 --- a/ui-kit/flutter/conversations.mdx +++ b/ui-kit/flutter/conversations.mdx @@ -305,7 +305,7 @@ class _ChatAppState extends State { - + --- From d77910429d40af759687dd51d8624c78c315d031 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 18:38:14 +0530 Subject: [PATCH 098/106] Update users.mdx --- ui-kit/flutter/users.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/flutter/users.mdx b/ui-kit/flutter/users.mdx index 85c83a5f0..036694c32 100644 --- a/ui-kit/flutter/users.mdx +++ b/ui-kit/flutter/users.mdx @@ -213,7 +213,7 @@ class _ChatAppState extends State { - + --- From 897cea1e5eb03311f656c70bfd712a05d9ddeb16 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 18:39:58 +0530 Subject: [PATCH 099/106] Update guide-message-privately.mdx --- ui-kit/flutter/guide-message-privately.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-kit/flutter/guide-message-privately.mdx b/ui-kit/flutter/guide-message-privately.mdx index 647f90925..f77cecee7 100644 --- a/ui-kit/flutter/guide-message-privately.mdx +++ b/ui-kit/flutter/guide-message-privately.mdx @@ -17,7 +17,7 @@ description: "Initiate private one-on-one chats with group members directly from -Message Privately lets users start a direct one-on-one chat with a group member without leaving the group context. +Message Privately lets users start a direct one-on-one chat with a group member. Before starting, complete the [Getting Started](/ui-kit/flutter/getting-started) guide. From 77ef8cfb99a56cb8c38c137c0496fa3c1356c67f Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 18:43:44 +0530 Subject: [PATCH 100/106] Update methods.mdx --- ui-kit/flutter/methods.mdx | 514 +++++++++++++++++++++---------------- 1 file changed, 288 insertions(+), 226 deletions(-) diff --git a/ui-kit/flutter/methods.mdx b/ui-kit/flutter/methods.mdx index 222a617cf..a4835c368 100644 --- a/ui-kit/flutter/methods.mdx +++ b/ui-kit/flutter/methods.mdx @@ -3,7 +3,7 @@ title: "Methods" description: "Reference for CometChat Flutter UI Kit methods including init, login, logout, and message-sending wrappers." --- - + | Field | Value | | --- | --- | @@ -20,23 +20,29 @@ description: "Reference for CometChat Flutter UI Kit methods including init, log -## Overview +`CometChatUIKit` provides wrapper methods around the CometChat SDK for initialization, authentication, user management, date formatting, and sending messages — while automatically managing internal UI Kit events so that components like Message List and Conversations stay in sync. -The UI Kit's core function is to extend the [Chat SDK](/sdk/flutter/overview), essentially translating the raw data and functionality provided by the underlying methods into visually appealing and easy-to-use UI components. +## When to use this -To effectively manage and synchronize the UI elements and data across all components in the UI Kit, we utilize internal events. These internal events enable us to keep track of changes in real-time and ensure that the UI reflects the most current state of data. +- You need to initialize the CometChat UI Kit and SDK before rendering any UI components. +- You need to log a user in or out of CometChat using an Auth Key (development) or Auth Token (production). +- You need to create or update a CometChat user dynamically from your app. +- You need to send text, media, custom, or interactive messages through the UI Kit so that the Message List and Conversations components update automatically. +- You need to customize how dates and times are displayed across all UI Kit components. -The CometChat UI Kit has thoughtfully encapsulated the critical [Chat SDK](/sdk/flutter/overview) methods within its wrapper to efficiently manage internal eventing. This layer of abstraction simplifies interaction with the underlying CometChat SDK, making it more user-friendly for developers. +## Prerequisites -## Methods +- The `cometchat_chat_uikit` package added to your project. +- Your CometChat App ID, Region, and Auth Key (or Auth Token) from the [CometChat dashboard](https://app.cometchat.com/). +- `CometChatUIKit.init()` called before invoking any other UI Kit method. -You can access the methods using the `CometChatUIKit` class. This class provides access to all the public methods exposed by the CometChat UI Kit. +## API Reference -### Init +### Initialization -As a developer, you need to invoke this method every time before you use any other methods provided by the UI Kit. +#### Init -This initialization is a critical step that ensures the UI Kit and Chat SDK function correctly and as intended in your application. Typical practice is to make this one of the first lines of code executed in your application's lifecycle when it comes to implementing CometChat. +You must invoke this method before using any other methods provided by the UI Kit. This initialization ensures the UI Kit and Chat SDK function correctly in your application. Call this as one of the first lines of code in your application's lifecycle. `CometChatUIKit.init()` must be called before rendering any UI Kit components or calling any SDK methods. Initialization must complete before login. @@ -47,12 +53,12 @@ Auth Key is for development/testing only. In production, generate Auth Tokens on -Make sure you replace the **APP\_ID**, **REGION** and **AUTH\_KEY** with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#login-using-auth-token) to log in securely. +Replace `APP_ID`, `REGION`, and `AUTH_KEY` with values from the CometChat Dashboard. `Auth Key` is optional — use [Auth Token](#login-using-auth-token) for production. -As a developer, the `UIKitSettings` is an important parameter of the `init()` function. It functions as a base settings object, housing properties such as `appId`, `region`, and `authKey`, contained within `UIKitSettings`. +The `UIKitSettings` is an important parameter of the `init()` function. It serves as the base settings object, housing properties such as `appId`, `region`, and `authKey`. -Here's the table format for the properties available in `UIKitSettings`: +#### UIKitSettings Properties | Method | Type | Description | | --------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | @@ -69,13 +75,11 @@ Here's the table format for the properties available in `UIKitSettings`: | **clientHost** | `String` | Sets a custom client host URL | | **dateTimeFormatterCallback** | `DateTimeFormatterCallback` | Sets a custom date/time formatter for consistent formatting across all UI components | -*** - -The concluding code block: +#### Usage -```dart highlight={3-5} +```dart UIKitSettings uiKitSettings = (UIKitSettingsBuilder() ..subscriptionType = CometChatSubscriptionType.allUsers ..autoEstablishSocketConnection = true @@ -94,20 +98,24 @@ CometChatUIKit.init( }, ); ``` - - -*** +> **What this does:** Creates a `UIKitSettings` object with your app ID, region, and auth key, then initializes the CometChat UI Kit. On success, the SDK and UI Kit are ready for use. On error, the callback provides failure details. + +--- + +### Authentication -### Login using Auth Key +#### Login using Auth Key -Only the `UID` of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, we suggest you use [AuthToken](#login-using-auth-token) instead of Auth Key. +Only the `UID` of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, use [Auth Token](#login-using-auth-token) instead of Auth Key. + +#### Usage -```dart highlight={1} +```dart String uid = "user1"; CometChatUIKit.login( @@ -120,26 +128,26 @@ CometChatUIKit.login( }, ); ``` - - -*** +> **What this does:** Logs in a user by their `UID` using the Auth Key configured during initialization. On success, the `User` object is returned. On error, the callback provides failure details. + +--- -### Login using Auth Token +#### Login using Auth Token Production-safe authentication that does not expose the Auth Key in client code. 1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. - 2. [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database. - 3. Load the Auth Token in your client and pass it to the `loginWithAuthToken()` method. +#### Usage + -```dart highlight={1} +```dart String authToken = "AUTH_TOKEN"; CometChatUIKit.loginWithAuthToken( @@ -152,178 +160,191 @@ CometChatUIKit.loginWithAuthToken( }, ); ``` - - -*** +> **What this does:** Logs in a user using a server-generated Auth Token instead of an Auth Key. This is the recommended approach for production apps because the Auth Key never appears in client code. On success, the `User` object is returned. -### Logout +--- + +#### Logout + +The CometChat UI Kit and Chat SDK effectively handle the session of the logged-in user within the framework. Before a new user logs in, it is crucial to clean this data to avoid potential conflicts or unexpected behavior. This can be achieved by invoking the `logout()` function. -The CometChat UI Kit and Chat SDK effectively handle the session of the logged-in user within the framework. Before a new user logs in, it is crucial to clean this data to avoid potential conflicts or unexpected behavior. This can be achieved by invoking the `.logout()` function +#### Usage ```dart -CometChatUIKit.logout(onSuccess: (s) { - // TODO("Not yet implemented") -} , onError: (e) { - // TODO("Not yet implemented") -}); +CometChatUIKit.logout( + onSuccess: (s) { + // Logout successful + }, + onError: (e) { + // Handle logout error + }, +); ``` - - -*** +> **What this does:** Logs out the current user, clears the session data, and tears down the internal event system. Call this before logging in a different user to avoid conflicts. + +--- + +### User Management -### Create User +#### Create User -As a developer, you can dynamically create users on CometChat using the `.createUser()` function. This can be extremely useful for situations where users are registered or authenticated by your system and then need to be created on CometChat. +You can dynamically create users on CometChat using the `createUser()` function. This is useful when users are registered or authenticated by your system and then need to be created on CometChat. + +#### Usage ```dart -CometChatUIKit.createUser(userObject, onSuccess: (user) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); -``` +User user = User(uid: "user_uid", name: "user_name"); +CometChatUIKit.createUser( + user, + onSuccess: (user) { + // User created successfully + }, + onError: (e) { + // Handle error + }, +); +``` - -*** +> **What this does:** Creates a new user on CometChat with the specified UID and name. On success, the created `User` object is returned. On error, the callback provides failure details. + +--- + +#### Update User -### Update User +You can update user details using the `updateUser()` function. This should ideally be achieved at your backend using the Restful APIs, but can also be done client-side when needed. -As a developer, you can update user details using the `.updateUser()` function. This should ideally be achieved at your backend using the Restful APIs, but can also be done client-side when needed. +#### Usage ```dart -CometChatUIKit.updateUser(userObject, onSuccess: (user) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); -``` +User user = User(uid: "user_uid", name: "updated_name"); +CometChatUIKit.updateUser( + user, + onSuccess: (user) { + // User updated successfully + }, + onError: (e) { + // Handle error + }, +); +``` - -*** +> **What this does:** Updates an existing user's details on CometChat. On success, the updated `User` object is returned. + +--- + +#### Get Logged In User -### Get Logged In User +You can check if there is any existing session in the SDK and retrieve the details of the logged-in user using the `getLoggedInUser()` function. -You can check if there is any existing session in the SDK and retrieve the details of the logged-in user using the `.getLoggedInUser()` function. +#### Usage ```dart -CometChatUIKit.getLoggedInUser(onSuccess: (user) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +CometChatUIKit.getLoggedInUser( + onSuccess: (user) { + if (user != null) { + // User is logged in + } else { + // No user logged in + } + }, + onError: (e) { + // Handle error + }, +); ``` - - -*** +> **What this does:** Checks for an existing session in the SDK. Returns the logged-in user details or `null` if no user is logged in. + +--- ### DateFormatter -By providing a custom implementation of the DateTimeFormatterCallback, you can globally configure how time and date values are displayed across all UI components in the CometChat UI Kit. This ensures consistent formatting for labels such as "Today", "Yesterday", "X minutes ago", and more, throughout the entire application. +By providing a custom implementation of the `DateTimeFormatterCallback`, you can globally configure how time and date values are displayed across all UI components in the CometChat UI Kit. This ensures consistent formatting for labels such as "Today", "Yesterday", "X minutes ago", and more, throughout the entire application. Each method in the interface corresponds to a specific case: -* time(int? timestamp) → Custom full timestamp format -* today(int? timestamp) → Called when a message is from today -* yesterday(int? timestamp) → Called for yesterday’s messages -* lastWeek(int? timestamp) → Messages from the past week -* otherDays(int? timestamp) → Older messages -* minute(int? timestamp) / hour(int? timestamp) → Exact time unit -* minutes(int? diffInMinutesFromNow, int? timestamp) → e.g., "5 minutes ago" -* hours(int? diffInHourFromNow, int? timestamp) → e.g., "2 hours ago" +- `time(int? timestamp)` → Custom full timestamp format +- `today(int? timestamp)` → Called when a message is from today +- `yesterday(int? timestamp)` → Called for yesterday's messages +- `lastWeek(int? timestamp)` → Messages from the past week +- `otherDays(int? timestamp)` → Older messages +- `minute(int? timestamp)` / `hour(int? timestamp)` → Exact time unit +- `minutes(int? diffInMinutesFromNow, int? timestamp)` → e.g., "5 minutes ago" +- `hours(int? diffInHourFromNow, int? timestamp)` → e.g., "2 hours ago" - +#### Usage + ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:intl/intl.dart'; -/// Custom implementation of DateTimeFormatterCallback -/// to format time and date display in the CometChat UI. class DateFormatter extends DateTimeFormatterCallback { - /// Formatter for displaying full time like "10:45 PM" final DateFormat fullTimeFormatter = DateFormat('hh:mm a'); - - /// Formatter for displaying date like "23 Jun 2025" final DateFormat dateFormatter = DateFormat('dd MMM yyyy'); - /// Returns formatted time (e.g., "10:45 PM") for a given timestamp. @override String? time(int? timestamp) { if (timestamp == null) return null; return fullTimeFormatter.format(DateTime.fromMillisecondsSinceEpoch(timestamp)); } - /// Returns a static label for messages sent today. @override - String? today(int? timestamp) { - return "Today"; - } + String? today(int? timestamp) => "Today"; - /// Returns a static label for messages sent yesterday. @override - String? yesterday(int? timestamp) { - return "Yesterday"; - } + String? yesterday(int? timestamp) => "Yesterday"; - /// Returns a static label for messages sent last week. @override - String? lastWeek(int? timestamp) { - return "Last Week"; - } + String? lastWeek(int? timestamp) => "Last Week"; - /// Returns formatted date (e.g., "23 Jun 2025") for other days. @override String? otherDays(int? timestamp) { if (timestamp == null) return null; return dateFormatter.format(DateTime.fromMillisecondsSinceEpoch(timestamp)); } - /// Returns relative time in minutes (e.g., "5 mins ago"). @override String? minutes(int? diffInMinutesFromNow, int? timestamp) { if (diffInMinutesFromNow == null) return null; return "$diffInMinutesFromNow mins ago"; } - /// Returns relative time in hours (e.g., "2 hrs ago"). @override String? hours(int? diffInHourFromNow, int? timestamp) { if (diffInHourFromNow == null) return null; return "$diffInHourFromNow hrs ago"; } - /// (Optional) Returns formatted hour (e.g., "3 PM") if used by SDK. @override String? hour(int? timestamp) { if (timestamp == null) return null; return DateFormat('h a').format(DateTime.fromMillisecondsSinceEpoch(timestamp)); } - /// (Optional) Returns formatted minute value (e.g., "09") if used by SDK. @override String? minute(int? timestamp) { if (timestamp == null) return null; @@ -331,71 +352,47 @@ class DateFormatter extends DateTimeFormatterCallback { } } -// Build CometChat UIKit settings +// Apply the custom formatter during initialization UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - // Set subscription type (e.g., receive messages from all users) - ..subscriptionType = CometChatSubscriptionType.allUsers - - // Set your CometChat region - ..region = AppCredentials.region - - // Automatically connect to socket server - ..autoEstablishSocketConnection = true - - // CometChat App ID and Auth Key - ..appId = AppCredentials.appId - ..authKey = AppCredentials.authKey - - // Enable calling feature - ..callingExtension = CometChatCallingExtension() - - // Load default chat extensions (e.g., polls, stickers, reactions) - ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() - - // Load default AI features (e.g., Smart Replies, Sentiment Analysis) - ..aiFeature = CometChatUIKitChatAIFeatures.getDefaultAiFeatures() - - // Inject the custom date and time formatter - ..dateTimeFormatterCallback = DateFormatter() - ) - .build(); + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region = "your_region" + ..appId = "your_appID" + ..authKey = "your_authKey" + ..dateTimeFormatterCallback = DateFormatter() +).build(); -// Initialize CometChat UIKit with the configured settings CometChatUIKit.init( uiKitSettings: uiKitSettings, - - // Callback when initialization is successful onSuccess: (successMessage) async { - // On success + // Initialization successful }, - - // Callback when initialization fails onError: (e) { - shouldGoToHomeScreen.value = false; - if (kDebugMode) { - debugPrint("Initialization failed with error: ${e.details}"); - } + // Handle error }, ); - - ``` - - -*** +> **What this does:** Configures a custom `DateTimeFormatterCallback` on `UIKitSettings` and passes it to `CometChatUIKit.init()`. This globally overrides how timestamps appear across all UI Kit components — today's messages show "Today", yesterday's show "Yesterday", recent messages show "X mins ago" or "X hrs ago", last week's show "Last Week", and older messages show the full date in "dd MMM yyyy" format. + +--- ### Base Message #### Text Message -Sends a text message in a 1:1 or group chat. Takes a `TextMessage` object. +To send a text message to a single user or a group, use the `sendTextMessage()` function. This function requires a `TextMessage` object as its argument, which contains the necessary information for delivering the message. + + +`CometChatUIKit.sendTextMessage()` automatically adds the message to the [MessageList](/ui-kit/flutter/message-list) and [Conversations](/ui-kit/flutter/conversations) components, handling all related cases for you. In contrast, `CometChat.sendTextMessage()` only sends the message without updating these UI Kit components. + + +#### Usage -```dart highlight={1-2} +```dart String receiverID = "UID"; String messageText = "Hello world!"; @@ -415,11 +412,9 @@ CometChatUIKit.sendTextMessage( }, ); ``` - - -```dart highlight={1-2} +```dart String receiverID = "GUID"; String messageText = "Hello world!"; @@ -439,20 +434,26 @@ CometChatUIKit.sendTextMessage( }, ); ``` - - -*** +> **What this does:** Creates a `TextMessage` targeting a user or group, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components. + +--- #### Media Message -Sends a media message in a 1:1 or group chat. Takes a `MediaMessage` object. +To send a media message to a single user or a group, use the `sendMediaMessage()` function. This function requires a `MediaMessage` object as its argument, which contains the necessary information for delivering the message. + + +`CometChatUIKit.sendMediaMessage()` automatically adds the message to the [MessageList](/ui-kit/flutter/message-list) and [Conversations](/ui-kit/flutter/conversations) components, handling all related cases for you. In contrast, `CometChat.sendMediaMessage()` only sends the message without updating these UI Kit components. + + +#### Usage -```dart highlight={1-2} +```dart String receiverID = "UID"; String filePath = "/path/to/file"; @@ -473,11 +474,9 @@ CometChatUIKit.sendMediaMessage( }, ); ``` - - -```dart highlight={1-2} +```dart String receiverID = "GUID"; String filePath = "/path/to/file"; @@ -498,20 +497,30 @@ CometChatUIKit.sendMediaMessage( }, ); ``` - - -*** +> **What this does:** Creates a `MediaMessage` with a file path and message type, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components. + +--- #### Custom Message -Sends a custom message (neither text nor media) in a 1:1 or group chat. Takes a `CustomMessage` object. +To send a custom message (neither text nor media) to a single user or a group, use the `sendCustomMessage()` function. This function requires a `CustomMessage` object as its argument, which contains the necessary information for delivering the message. + + +`CometChatUIKit.sendCustomMessage()` automatically adds the message to the [MessageList](/ui-kit/flutter/message-list) and [Conversations](/ui-kit/flutter/conversations) components, handling all related cases for you. In contrast, `CometChat.sendCustomMessage()` only sends the message without updating these UI Kit components. + + + +To display custom messages in the [MessageList](/ui-kit/flutter/message-list), you must create and register a new [MessageTemplate](/ui-kit/flutter/message-template) that defines how to render your custom message type. + + +#### Usage -```dart highlight={1,3-4} +```dart String receiverID = "UID"; Map customData = { "latitude": "50.6192171633316", @@ -536,11 +545,9 @@ CometChatUIKit.sendCustomMessage( }, ); ``` - - -```dart highlight={1,3-4} +```dart String receiverID = "GUID"; Map customData = { "latitude": "50.6192171633316", @@ -565,133 +572,188 @@ CometChatUIKit.sendCustomMessage( }, ); ``` - - -*** +> **What this does:** Creates a `CustomMessage` with a custom type string and data payload, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components. + +--- ### Interactive Message #### Form Message -As a developer, if you need to send a Form message to a single user or a group, you'll need to utilize the `sendFormMessage()` function. This function requires a `FormMessage` object as its argument, which contains the necessary information to create a form bubble for that messages +To send a Form message to a single user or a group, use the `sendFormMessage()` function. This function requires a `FormMessage` object as its argument, which contains the necessary information to create a form bubble for that message. + +#### Usage ```dart -CometChatUIKit.sendFormMessage(formMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); +CometChatUIKit.sendFormMessage( + formMessageObject, + onSuccess: (message) { + // Form message sent successfully + }, + onError: (e) { + // Handle error + }, +); ``` - - -*** +> **What this does:** Sends a `FormMessage` that renders as an interactive form bubble in the chat. Users can fill out form fields and submit responses. + +--- #### Card Message -As a developer, if you need to send a Card message to a single user or a group, you'll need to utilize the `sendCardMessage()` function. This function requires a `CardMessage` object as its argument, which contains the necessary information to create a card bubble for the messages +To send a Card message to a single user or a group, use the `sendCardMessage()` function. This function requires a `CardMessage` object as its argument, which contains the necessary information to create a card bubble for the message. + +#### Usage ```dart -CometChatUIKit.sendCardMessage(cardMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); +CometChatUIKit.sendCardMessage( + cardMessageObject, + onSuccess: (message) { + // Card message sent successfully + }, + onError: (e) { + // Handle error + }, +); ``` - - -*** +> **What this does:** Sends a `CardMessage` that renders as an interactive card bubble in the chat with customizable actions. + +--- #### Scheduler Message -As a developer, if you need to send a Scheduler message to a single user or a group, you'll need to utilize the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object as its argument, which contains the necessary information to create a SchedulerMessage bubble for the messages +To send a Scheduler message to a single user or a group, use the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object as its argument, which contains the necessary information to create a scheduler bubble for the message. + +#### Usage ```dart -CometChatUIKit.sendSchedulerMessage(schedulerMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); +CometChatUIKit.sendSchedulerMessage( + schedulerMessageObject, + onSuccess: (message) { + // Scheduler message sent successfully + }, + onError: (e) { + // Handle error + }, +); ``` - - -*** +> **What this does:** Sends a `SchedulerMessage` that renders as an interactive scheduling bubble in the chat for booking appointments or meetings. + +--- #### Custom Interactive Message -As a developer, if you need to send a Interactive message to a single user or a group, you'll need to utilize the `sendCustomInteractiveMessage()` function. This function requires a `InteractiveMessage` object as its argument, which contains the necessary information to create a custom interactive message bubble for the messages +To send a custom interactive message to a single user or a group, use the `sendCustomInteractiveMessage()` function. This function requires an `InteractiveMessage` object as its argument, which contains the necessary information to create a custom interactive message bubble. + +#### Usage ```dart -CometChatUIKit.sendCustomInteractiveMessage(interactiveMessageObject, onSuccess: (p0) { - // TODO("Not yet implemented") -}, onError: (p0) { - // TODO("Not yet implemented") -}); +CometChatUIKit.sendCustomInteractiveMessage( + interactiveMessageObject, + onSuccess: (message) { + // Custom interactive message sent successfully + }, + onError: (e) { + // Handle error + }, +); ``` - - -*** +> **What this does:** Sends a custom `InteractiveMessage` that can be rendered with your own custom interactive UI. + +--- ### Reactions #### Add Reaction -As a developer, you can add a reaction to a message using the `addReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. +You can add a reaction to a message using the `addReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. + +#### Usage ```dart -CometChatUIKit.addReaction(messageId, "👍", onSuccess: (message) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +CometChatUIKit.addReaction( + messageId, + "👍", + onSuccess: (message) { + // Reaction added successfully + }, + onError: (e) { + // Handle error + }, +); ``` - - -*** +> **What this does:** Adds a reaction emoji to the specified message. The UI Kit automatically updates the Message List and Reactions components to reflect the change. + +--- #### Remove Reaction -As a developer, you can remove a reaction from a message using the `removeReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. +You can remove a reaction from a message using the `removeReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. + +#### Usage ```dart -CometChatUIKit.removeReaction(messageId, "👍", onSuccess: (message) { - // TODO("Not yet implemented") -}, onError: (e) { - // TODO("Not yet implemented") -}); +CometChatUIKit.removeReaction( + messageId, + "👍", + onSuccess: (message) { + // Reaction removed successfully + }, + onError: (e) { + // Handle error + }, +); ``` - - -*** +> **What this does:** Removes a reaction emoji from the specified message. The UI Kit automatically updates the Message List and Reactions components to reflect the change. + +--- + +## Next Steps + + + + Listen and respond to UI Kit events. + + + Set up CometChat Flutter UI Kit. + + + Display and customize chat messages. + + + Manage conversation lists. + + From ad04641f25b5e635999860c884316d9570b759ef Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 18:51:23 +0530 Subject: [PATCH 101/106] Update events.mdx --- ui-kit/flutter/events.mdx | 560 +++++++++++++++++--------------------- 1 file changed, 247 insertions(+), 313 deletions(-) diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index 022885d91..ac8503b87 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -1,9 +1,9 @@ --- title: "Events" -description: "Listen to and handle real-time events for users, groups, conversations, messages, calls, and UI interactions in Flutter UI Kit" +description: "Listen to UI Kit events for user actions, group changes, conversations, messages, calls, and UI interactions in Flutter." --- - + | Field | Value | | --- | --- | @@ -11,93 +11,78 @@ description: "Listen to and handle real-time events for users, groups, conversat | Conversation events | `ccConversationDeleted`, `ccUpdateConversation` | | User events | `ccUserBlocked`, `ccUserUnblocked` | | Group events | `ccGroupCreated`, `ccGroupDeleted`, `ccGroupLeft`, `ccGroupMemberScopeChanged`, `ccGroupMemberKicked`, `ccGroupMemberBanned`, `ccGroupMemberUnbanned`, `ccGroupMemberJoined`, `ccGroupMemberAdded`, `ccOwnershipChanged` | -| Message events | `ccMessageSent`, `ccMessageEdited`, `ccReplyToMessage`, `ccMessageDeleted`, `ccMessageRead`, `ccLiveReaction`, `ccMessageForwarded`, plus SDK listener events | +| Message events | `ccMessageSent`, `ccMessageEdited`, `ccMessageDeleted`, `ccMessageRead`, `ccLiveReaction`, `ccMessageForwarded`, `ccReplyToMessage`, plus SDK listener events | | Call events | `ccOutgoingCall`, `ccCallAccepted`, `ccCallRejected`, `ccCallEnded` | | UI events | `ccActiveChatChanged`, `showPanel`, `hidePanel`, `openChat`, `ccComposeMessage`, `onAiFeatureTapped` | | Purpose | Decoupled communication between UI Kit components — subscribe to events to react to changes without direct component references | -{/* TL;DR for Agents and Quick Reference */} - -**Quick Reference for AI Agents & Developers** +Events enable a decoupled, flexible architecture in the CometChat UI Kit. Components and Composite Components emit events in response to user interactions or state changes, allowing other parts of your application to react without direct references between components. -```dart -// Add event listener -CometChatMessageEvents.addMessagesListener("LISTENER_ID", this); +## When to use this -// Remove event listener -CometChatMessageEvents.removeMessagesListener("LISTENER_ID"); +- 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. -// Implement listener methods -@override -void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { - // Handle message sent event -} -``` +## Prerequisites -**Available Event Types:** -- **User Events** → Block/Unblock users -- **Group Events** → Create, delete, join, leave groups -- **Conversation Events** → Delete conversations, update conversations -- **Message Events** → Send, edit, delete, receive messages, reactions, AI messages -- **Call Events** → Outgoing, accepted, rejected, ended calls -- **UI Events** → Show/hide panels, active chat changes - +- The `cometchat_chat_uikit` package added to your project. +- `CometChatUIKit.init()` called and completed successfully. +- A logged-in CometChat user (call `CometChatUIKit.login()` before registering listeners). -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. +## API Reference -Both Components and Composite Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. +### User Events -*** +`CometChatUserEvents` emits events when the logged-in user executes actions on another user. This class provides methods to add and remove listeners for user events. -## User Events +**Events:** -`CometChatUserEvents` emit events when the logged-in user executes actions on another user. This class provides methods to add and remove listeners for user events, as well as methods to handle specific user actions such as blocking and unblocking users. +| Event | Description | +| ----- | ----------- | +| `ccUserBlocked` | Triggered when the logged-in user blocks another user. | +| `ccUserUnblocked` | Triggered when the logged-in user unblocks another user. | -**Available Events:** - -1. `ccUserBlocked`: Triggered when the logged-in user blocks another user. -2. `ccUserUnblocked`: Triggered when the logged-in user unblocks another user. +**Listener registration:** ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class UserEventsExample extends StatefulWidget { - const UserEventsExample({super.key}); +class YourWidget extends StatefulWidget { + const YourWidget({super.key}); @override - State createState() => _UserEventsExampleState(); + State createState() => _YourWidgetState(); } -class _UserEventsExampleState extends State with CometChatUserEventListener { - String listenerID = "unique_listener_ID"; +class _YourWidgetState extends State with CometChatUserEventListener { + final String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - - CometChatUserEvents.addUsersListener(listenerID, this); // Add the listener + CometChatUserEvents.addUsersListener(listenerID, this); } @override void dispose() { + CometChatUserEvents.removeUsersListener(listenerID); super.dispose(); - - CometChatUserEvents.removeUsersListener(listenerID); // Remove the listener } @override void ccUserBlocked(User user) { - // TODO("Not yet implemented") + // Handle user blocked } @override void ccUserUnblocked(User user) { - // TODO("Not yet implemented") + // Handle user unblocked } @override @@ -109,104 +94,107 @@ class _UserEventsExampleState extends State with CometChatUse -*** +> **What this does:** Registers a listener on `CometChatUserEvents` using a unique `listenerID`. The `ccUserBlocked` callback fires when the logged-in user blocks another user, and `ccUserUnblocked` fires when the logged-in user unblocks another user. + +--- + +### Group Events -## Group Events +`CometChatGroupEvents` emits events when the logged-in user performs actions related to groups. This class provides methods to listen to various group-related events. -`CometChatGroupEvents` Emits events when the logged-in user performs actions related to groups. This class provides methods to listen to various group-related events and handle them accordingly. +**Events:** -**Available Events:** +| Event | Description | +| ----- | ----------- | +| `ccGroupCreated` | Triggered when the logged-in user creates a group. | +| `ccGroupDeleted` | Triggered when the logged-in user deletes a group. | +| `ccGroupLeft` | Triggered when the logged-in user leaves a group. Provides the action message, the user who left, and the group. | +| `ccGroupMemberScopeChanged` | Triggered when the logged-in user changes the scope of another group member. Provides the action message, updated user, new scope, previous scope, and group. | +| `ccGroupMemberBanned` | Triggered when the logged-in user bans a group member. Provides the action message, banned user, who banned them, and the group. | +| `ccGroupMemberKicked` | Triggered when the logged-in user kicks a group member. Provides the action message, kicked user, who kicked them, and the group. | +| `ccGroupMemberUnbanned` | Triggered when the logged-in user unbans a user. Provides the action message, unbanned user, who unbanned them, and the group. | +| `ccGroupMemberJoined` | Triggered when the logged-in user joins a group. Provides the joined user and the group. | +| `ccGroupMemberAdded` | Triggered when the logged-in user adds new members to the group. Provides action messages, added users, the group, and who added them. | +| `ccOwnershipChanged` | Triggered when the logged-in user transfers group ownership. Provides the group and the new owner. | -1. `ccGroupCreated`: Triggered when the logged-in user creates a group. -2. `ccGroupDeleted`: Triggered when the logged-in user deletes a group. -3. `ccGroupLeft`: Triggered when the logged-in user leaves a group. -4. `ccGroupMemberScopeChanged`: Triggered when the logged-in user changes the scope of another group member. -5. `ccGroupMemberBanned`: Triggered when the logged-in user bans a group member from the group. -6. `ccGroupMemberKicked`: Triggered when the logged-in user kicks another group member from the group. -7. `ccGroupMemberUnbanned`: Triggered when the logged-in user unbans a user banned from the group. -8. `ccGroupMemberJoined`: Triggered when the logged-in user joins a group. -9. `ccGroupMemberAdded`: Triggered when the logged-in user adds new members to the group. -10. `ccOwnershipChanged`: Triggered when the logged-in user transfers the ownership of their group to some other member. +**Listener registration:** ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart' as sdk; -import 'package:flutter/material.dart'; -class GroupEventsExample extends StatefulWidget { - const GroupEventsExample({super.key}); +class YourWidget extends StatefulWidget { + const YourWidget({super.key}); @override - State createState() => _GroupEventsExampleState(); + State createState() => _YourWidgetState(); } -class _GroupEventsExampleState extends State with CometChatGroupEventListener { - String listenerID = "unique_listener_ID"; +class _YourWidgetState extends State with CometChatGroupEventListener { + final String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - - CometChatGroupEvents.addGroupsListener(listenerID, this); // Add the listener + CometChatGroupEvents.addGroupsListener(listenerID, this); } @override void dispose() { + CometChatGroupEvents.removeGroupsListener(listenerID); super.dispose(); - - CometChatGroupEvents.removeGroupsListener(listenerID); // Remove the listener } @override void ccGroupCreated(Group group) { - // TODO("Not yet implemented") + // Handle group created } @override void ccGroupDeleted(Group group) { - // TODO("Not yet implemented") + // Handle group deleted } @override void ccGroupLeft(sdk.Action message, User leftUser, Group leftGroup) { - // TODO("Not yet implemented") + // Handle user left group } @override void ccGroupMemberScopeChanged(sdk.Action message, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { - // TODO("Not yet implemented") + // Handle member scope changed } @override void ccGroupMemberBanned(sdk.Action message, User bannedUser, User bannedBy, Group bannedFrom) { - // TODO("Not yet implemented") + // Handle member banned } @override void ccGroupMemberKicked(sdk.Action message, User kickedUser, User kickedBy, Group kickedFrom) { - // TODO("Not yet implemented") + // Handle member kicked } @override void ccGroupMemberUnbanned(sdk.Action message, User unbannedUser, User unbannedBy, Group unbannedFrom) { - // TODO("Not yet implemented") + // Handle member unbanned } @override void ccGroupMemberJoined(User joinedUser, Group joinedGroup) { - // TODO("Not yet implemented") + // Handle member joined } @override void ccGroupMemberAdded(List messages, List usersAdded, Group groupAddedIn, User addedBy) { - // TODO("Not yet implemented") + // Handle members added } @override void ccOwnershipChanged(Group group, GroupMember newOwner) { - // TODO("Not yet implemented") + // Handle ownership changed } @override @@ -218,55 +206,56 @@ class _GroupEventsExampleState extends State with CometChatG -*** +> **What this does:** Registers a listener on `CometChatGroupEvents` using a unique `listenerID`. Each callback fires when the logged-in user performs the corresponding group action — creating, deleting, leaving a group, or managing members (scope change, ban, kick, unban, join, add, ownership transfer). + +--- + +### Conversation Events -## Conversation Events +`CometChatConversationEvents` emits events when the logged-in user performs actions related to conversations. This allows the UI to be updated when conversations change. -The `CometChatConversationEvents` component emits events when the logged-in user performs actions related to conversations. This allows for the UI to be updated accordingly. +**Events:** -**Available Events:** +| Event | Description | +| ----- | ----------- | +| `ccConversationDeleted` | Triggered when the logged-in user deletes a conversation. | +| `ccUpdateConversation` | Triggered when a conversation is updated (e.g., unread count changes). | -1. `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. -2. `ccUpdateConversation`: Triggered when a conversation is updated (e.g., unread count changes). +**Listener registration:** ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class ConversationEventsExample extends StatefulWidget { - const ConversationEventsExample({super.key}); +class YourWidget extends StatefulWidget { + const YourWidget({super.key}); @override - State createState() => _ConversationEventsExampleState(); + State createState() => _YourWidgetState(); } -class _ConversationEventsExampleState extends State with CometChatConversationEventListener { - String listenerID = "unique_listener_ID"; +class _YourWidgetState extends State with CometChatConversationEventListener { + final String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - - CometChatConversationEvents.addConversationListListener(listenerID, this); // Add the listener + CometChatConversationEvents.addConversationListListener(listenerID, this); } @override void dispose() { + CometChatConversationEvents.removeConversationListListener(listenerID); super.dispose(); - - CometChatConversationEvents.removeConversationListListener(listenerID); // Remove the listener } @override void ccConversationDeleted(Conversation conversation) { - // TODO("Not yet implemented") + // Handle conversation deleted } @override void ccUpdateConversation(Conversation conversation) { - // TODO("Not yet implemented") + // Handle conversation updated } @override @@ -278,229 +267,171 @@ class _ConversationEventsExampleState extends State w -*** - -## Message Events - -`CometChatMessageEvents` emits events when various actions are performed on messages within the application. These events facilitate updating the UI accordingly. - -**Available Events:** - -1. `ccMessageSent`: Triggered whenever a logged-in user sends any message. It can have two states: `inProgress` and `sent`. -2. `ccMessageEdited`: Triggered whenever a logged-in user edits any message from the list of messages. It can have two states: `inProgress` and `sent`. -3. `ccMessageDeleted`: Triggered whenever a logged-in user deletes any message from the list of messages. -4. `ccMessageRead`: Triggered whenever a logged-in user reads any message. -5. `ccLiveReaction`: Triggered whenever a logged-in user clicks on a live reaction. -6. `ccMessageForwarded`: Triggered whenever a logged-in user forwards any message to a list of users or groups. It can have a state of `status`. -7. `onTextMessageReceived`: Triggered when a text message is received. -8. `onMediaMessageReceived`: Triggered when a media message is received. -9. `onCustomMessageReceived`: Triggered when a custom message is received. -10. `onTypingStarted`: Triggered when a typing indicator starts. -11. `onTypingEnded`: Triggered when a typing indicator ends. -12. `onMessagesDelivered`: Triggered when messages are delivered. -13. `onMessagesRead`: Triggered when messages are read. -14. `onMessageEdited`: Triggered when a message is edited. -15. `onMessageDeleted`: Triggered when a message is deleted. -16. `onTransientMessageReceived`: Triggered when a transient message is received. -17. `onFormMessageReceived`: Triggered when a form message is received. -18. `onCardMessageReceived`: Triggered when a card message is received. -19. `onCustomInteractiveMessageReceived`: Triggered when a custom interactive message is received. -20. `onInteractionGoalCompleted`: Triggered when an interaction goal is completed. -21. `onSchedulerMessageReceived`: Triggered when a scheduler message is received. -22. `onMessageReactionAdded`: Triggered when a reaction is added to a message. -23. `onMessageReactionRemoved`: Triggered when a reaction is removed from a message. -24. `ccReplyToMessage`: Triggered when the logged-in user replies to a message. -25. `onMessagesDeliveredToAll`: Triggered when messages are delivered to all recipients. -26. `onMessagesReadByAll`: Triggered when messages are read by all recipients. -27. `onMessageModerated`: Triggered when a message is moderated. -28. `onAIAssistantMessageReceived`: Triggered when an AI Assistant message is received. -29. `onAIToolResultReceived`: Triggered when an AI tool result is received. -30. `onAIToolArgumentsReceived`: Triggered when AI tool arguments are received. +> **What this does:** Registers a listener on `CometChatConversationEvents` using a unique listener ID. The `ccConversationDeleted` callback fires when the logged-in user deletes a conversation, and `ccUpdateConversation` fires when a conversation is updated. + +--- + +### Message Events + +`CometChatMessageEvents` emits events when various actions are performed on messages within the application. These events facilitate updating the UI when messages change. + +**UI Kit Events:** + +| Event | Description | +| ----- | ----------- | +| `ccMessageSent` | Triggered when a message is sent. States: `inProgress`, `sent`. | +| `ccMessageEdited` | Triggered when a message is edited. States: `inProgress`, `sent`. | +| `ccMessageDeleted` | Triggered when a message is deleted. | +| `ccMessageRead` | Triggered when a message is read. | +| `ccLiveReaction` | Triggered when a live reaction is clicked. | +| `ccMessageForwarded` | Triggered when a message is forwarded. | +| `ccReplyToMessage` | Triggered when replying to a message. | + +**SDK Listener Events:** + +| Event | Description | +| ----- | ----------- | +| `onTextMessageReceived` | Triggered when a text message is received. | +| `onMediaMessageReceived` | Triggered when a media message is received. | +| `onCustomMessageReceived` | Triggered when a custom message is received. | +| `onTypingStarted` | Triggered when typing indicator starts. | +| `onTypingEnded` | Triggered when typing indicator ends. | +| `onMessagesDelivered` | Triggered when messages are delivered. | +| `onMessagesRead` | Triggered when messages are read. | +| `onMessageEdited` | Triggered when a message is edited by another user. | +| `onMessageDeleted` | Triggered when a message is deleted by another user. | +| `onTransientMessageReceived` | Triggered when a transient message is received. | +| `onFormMessageReceived` | Triggered when a form message is received. | +| `onCardMessageReceived` | Triggered when a card message is received. | +| `onCustomInteractiveMessageReceived` | Triggered when a custom interactive message is received. | +| `onSchedulerMessageReceived` | Triggered when a scheduler message is received. | +| `onInteractionGoalCompleted` | Triggered when an interaction goal is completed. | +| `onMessageReactionAdded` | Triggered when a reaction is added. | +| `onMessageReactionRemoved` | Triggered when a reaction is removed. | +| `onMessagesDeliveredToAll` | Triggered when messages are delivered to all recipients. | +| `onMessagesReadByAll` | Triggered when messages are read by all recipients. | +| `onMessageModerated` | Triggered when a message is moderated. | +| `onAIAssistantMessageReceived` | Triggered when an AI Assistant message is received. | +| `onAIToolResultReceived` | Triggered when an AI tool result is received. | +| `onAIToolArgumentsReceived` | Triggered when AI tool arguments are received. | + +**Listener registration:** ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class MessageEventsExample extends StatefulWidget { - const MessageEventsExample({super.key}); +class YourWidget extends StatefulWidget { + const YourWidget({super.key}); @override - State createState() => _MessageEventsExampleState(); + State createState() => _YourWidgetState(); } -class _MessageEventsExampleState extends State with CometChatMessageEventListener { - String listenerID = "unique_listener_ID"; +class _YourWidgetState extends State with CometChatMessageEventListener { + final String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - - CometChatMessageEvents.addMessagesListener(listenerID, this); // Add the listener + CometChatMessageEvents.addMessagesListener(listenerID, this); } @override void dispose() { + CometChatMessageEvents.removeMessagesListener(listenerID); super.dispose(); - - CometChatMessageEvents.removeMessagesListener(listenerID); // Remove the listener } + // UI Kit Events @override void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { - // TODO("Not yet implemented") + // Handle message sent } @override void ccMessageEdited(BaseMessage message, MessageEditStatus status) { - // TODO("Not yet implemented") + // Handle message edited } @override void ccMessageDeleted(BaseMessage message, EventStatus messageStatus) { - // TODO("Not yet implemented") + // Handle message deleted } @override void ccMessageRead(BaseMessage message) { - // TODO("Not yet implemented") + // Handle message read } @override void ccLiveReaction(String reaction) { - // TODO("Not yet implemented") + // Handle live reaction } @override void ccMessageForwarded(BaseMessage message, List? usersSent, List? groupsSent, MessageStatus status) { - // TODO("Not yet implemented") + // Handle message forwarded } @override void ccReplyToMessage(BaseMessage message, MessageStatus status) { - // TODO("Not yet implemented") + // Handle reply to message } + // SDK Listener Events @override void onTextMessageReceived(TextMessage textMessage) { - // TODO("Not yet implemented") + // Handle text message received } @override void onMediaMessageReceived(MediaMessage mediaMessage) { - // TODO("Not yet implemented") + // Handle media message received } @override void onCustomMessageReceived(CustomMessage customMessage) { - // TODO("Not yet implemented") + // Handle custom message received } @override void onTypingStarted(TypingIndicator typingIndicator) { - // TODO("Not yet implemented") + // Handle typing started } @override void onTypingEnded(TypingIndicator typingIndicator) { - // TODO("Not yet implemented") + // Handle typing ended } @override void onMessagesDelivered(MessageReceipt messageReceipt) { - // TODO("Not yet implemented") + // Handle messages delivered } @override void onMessagesRead(MessageReceipt messageReceipt) { - // TODO("Not yet implemented") + // Handle messages read } @override void onMessageEdited(BaseMessage message) { - // TODO("Not yet implemented") + // Handle message edited by another user } @override void onMessageDeleted(BaseMessage message) { - // TODO("Not yet implemented") - } - - @override - void onTransientMessageReceived(TransientMessage message) { - // TODO("Not yet implemented") - } - - @override - void onFormMessageReceived(FormMessage formMessage) { - // TODO("Not yet implemented") - } - - @override - void onCardMessageReceived(CardMessage cardMessage) { - // TODO("Not yet implemented") - } - - @override - void onCustomInteractiveMessageReceived( - CustomInteractiveMessage customInteractiveMessage) { - // TODO("Not yet implemented") - } - - @override - void onInteractionGoalCompleted(InteractionReceipt receipt) { - // TODO("Not yet implemented") - } - - @override - void onSchedulerMessageReceived(SchedulerMessage schedulerMessage) { - // TODO("Not yet implemented") + // Handle message deleted by another user } @override void onMessageReactionAdded(ReactionEvent reactionEvent) { - // TODO("Not yet implemented") + // Handle reaction added } @override void onMessageReactionRemoved(ReactionEvent reactionEvent) { - // TODO("Not yet implemented") - } - - @override - void ccReplyToMessage(BaseMessage message, MessageStatus status) { - // TODO("Not yet implemented") - } - - @override - void onMessagesDeliveredToAll(MessageReceipt messageReceipt) { - // TODO("Not yet implemented") - } - - @override - void onMessagesReadByAll(MessageReceipt messageReceipt) { - // TODO("Not yet implemented") - } - - @override - void onMessageModerated(BaseMessage message) { - // TODO("Not yet implemented") - } - - @override - void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { - // TODO("Not yet implemented") - } - - @override - void onAIToolResultReceived(AIToolResultMessage aiToolResultMessage) { - // TODO("Not yet implemented") - } - - @override - void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { - // TODO("Not yet implemented") + // Handle reaction removed } @override @@ -512,67 +443,68 @@ class _MessageEventsExampleState extends State with CometC -*** +> **What this does:** Registers a listener on `CometChatMessageEvents` using a unique ID string. The callbacks fire for message lifecycle events — sending, editing, deleting, reading messages, reactions, and receiving various message types including interactive and AI messages. -## Call Events +--- -`CometChatCallEvents` emits events related to calls within the application. This class provides methods to listen to call-related events and handle them accordingly. +### Call Events -**Available Events:** +`CometChatCallEvents` emits events related to calls within the application. This class provides methods to listen to call-related events. -1. `ccOutgoingCall`: Triggered when the logged-in user initiates an outgoing call. -2. `ccCallAccepted`: Triggered when a call is accepted. -3. `ccCallRejected`: Triggered when a call is rejected. -4. `ccCallEnded`: Triggered when a call is ended. +**Events:** + +| Event | Description | +| ----- | ----------- | +| `ccOutgoingCall` | Triggered when the logged-in user initiates an outgoing call. | +| `ccCallAccepted` | Triggered when a call is accepted. | +| `ccCallRejected` | Triggered when a call is rejected. | +| `ccCallEnded` | Triggered when a call is ended. | + +**Listener registration:** ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class CallEventsExample extends StatefulWidget { - const CallEventsExample({super.key}); +class YourWidget extends StatefulWidget { + const YourWidget({super.key}); @override - State createState() => _CallEventsExampleState(); + State createState() => _YourWidgetState(); } -class _CallEventsExampleState extends State with CometChatCallEventListener { - String listenerID = "unique_listener_ID"; +class _YourWidgetState extends State with CometChatCallEventListener { + final String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - - CometChatCallEvents.addCallEventsListener(listenerID, this); // Add the listener + CometChatCallEvents.addCallEventsListener(listenerID, this); } @override void dispose() { + CometChatCallEvents.removeCallEventsListener(listenerID); super.dispose(); - - CometChatCallEvents.removeCallEventsListener(listenerID); // Remove the listener } @override void ccOutgoingCall(Call call) { - // TODO("Not yet implemented") + // Handle outgoing call initiated } @override void ccCallAccepted(Call call) { - // TODO("Not yet implemented") + // Handle call accepted } @override void ccCallRejected(Call call) { - // TODO("Not yet implemented") + // Handle call rejected } @override void ccCallEnded(Call call) { - // TODO("Not yet implemented") + // Handle call ended } @override @@ -584,79 +516,80 @@ class _CallEventsExampleState extends State with CometChatCal -*** +> **What this does:** Registers a listener on `CometChatCallEvents` using a unique `listenerID`. The callbacks fire for each stage of the call lifecycle — initiating an outgoing call, accepting, rejecting, and ending a call. + +--- + +### UI Events -## UI Events +`CometChatUIEvents` emits events related to UI components within the CometChat UI Kit. This class provides methods to listen to UI-related events. -`CometChatUIEvents` emits events related to UI components within the CometChat UI. This class provides methods to listen to UI-related events and handle them accordingly. +**Events:** -**Available Events:** +| Event | Description | +| ----- | ----------- | +| `showPanel` | Triggered to show an additional UI panel with custom elements. | +| `hidePanel` | Triggered to hide a previously shown UI panel. | +| `ccActiveChatChanged` | Triggered when the active chat changes, providing the current message, user, group, and unread count. | +| `openChat` | Triggered to open a chat with a specific user or group. | +| `ccComposeMessage` | Triggered when composing a message with specific text and status. | +| `onAiFeatureTapped` | Triggered when an AI feature is tapped for a specific user or group. | -1. `showPanel`: Triggered to show an additional UI panel with custom elements. -2. `hidePanel`: Triggered to hide a previously shown UI panel. -3. `ccActiveChatChanged`: Triggered when the active chat changes, providing information about the current message, user, and group. -4. `openChat`: Triggered to open a chat with a specific user or group. -5. `ccComposeMessage`: Triggered when composing a message with a specific text and status. -6. `onAiFeatureTapped`: Triggered when an AI feature is tapped for a specific user or group. +**Listener registration:** ```dart -import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; -import 'package:flutter/material.dart'; - -class UIEventsExample extends StatefulWidget { - const UIEventsExample({super.key}); +class YourWidget extends StatefulWidget { + const YourWidget({super.key}); @override - State createState() => _UIEventsExampleState(); + State createState() => _YourWidgetState(); } -class _UIEventsExampleState extends State with CometChatUIEventListener { - String listenerID = "unique_listener_ID"; +class _YourWidgetState extends State with CometChatUIEventListener { + final String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - - CometChatUIEvents.addUiListener(listenerID, this); // Add the listener + CometChatUIEvents.addUiListener(listenerID, this); } @override void dispose() { + CometChatUIEvents.removeUiListener(listenerID); super.dispose(); - - CometChatUIEvents.removeUiListener(listenerID); // Remove the listener } @override void showPanel(Map? id, CustomUIPosition uiPosition, WidgetBuilder child) { - // TODO("Not yet implemented") + // Handle show panel } @override void hidePanel(Map? id, CustomUIPosition uiPosition) { - // TODO("Not yet implemented") + // Handle hide panel } @override void ccActiveChatChanged(Map? id, BaseMessage? lastMessage, User? user, Group? group, int unreadMessageCount) { - // TODO("Not yet implemented") + // Handle active chat changed } @override void openChat(User? user, Group? group) { - // TODO("Not yet implemented") + // Handle open chat } @override void ccComposeMessage(String text, MessageEditStatus status) { - // TODO("Not yet implemented") + // Handle compose message } @override void onAiFeatureTapped(User? user, Group? group) { - // TODO("Not yet implemented") + // Handle AI feature tapped } @override @@ -668,7 +601,23 @@ class _UIEventsExampleState extends State with CometChatUIEvent -*** +> **What this does:** Registers a listener on `CometChatUIEvents` using a unique ID string. The callbacks fire for UI-level actions — showing or hiding custom panels, reacting to active chat changes, opening a chat, composing messages, and AI feature interactions. + +--- + +## Removing Event Listeners + +Each event listener class provides methods to add and remove listeners. Always remove listeners in the `dispose()` method to prevent memory leaks. Use the same listener ID you passed during registration. + +```dart +@override +void dispose() { + CometChatMessageEvents.removeMessagesListener(listenerID); + super.dispose(); +} +``` + +--- ## Best Practices @@ -676,69 +625,54 @@ class _UIEventsExampleState extends State with CometChatUIEvent Always remove event listeners in the `dispose()` method to prevent memory leaks: - - ```dart @override void dispose() { - super.dispose(); CometChatMessageEvents.removeMessagesListener(listenerID); + super.dispose(); } ``` - - Use unique listener IDs for each widget to avoid conflicts: - - ```dart - String listenerID = "message_list_${widget.key}"; + final String listenerID = "message_list_${widget.key}"; ``` - - Keep event handlers lightweight and avoid heavy operations: - - ```dart @override void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { if (messageStatus == MessageStatus.sent) { - // Update UI efficiently setState(() { // Minimal state update }); } } ``` - - -*** +--- ## Next Steps - - Learn how to display and manage messages with events + + UI Kit wrapper methods for initialization, authentication, and sending messages - Handle conversation events and updates + Display and manage the conversation list, which reacts to conversation events + + + Display messages in a chat, which reacts to message events Manage group events and member actions - - Explore available methods for UI Kit operations - - -*** From aa2a8d41b2f136b12fc9fbb5a25ec3bc826f3ad2 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 18:57:09 +0530 Subject: [PATCH 102/106] Update custom-text-formatter-guide.mdx --- ui-kit/flutter/custom-text-formatter-guide.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-kit/flutter/custom-text-formatter-guide.mdx b/ui-kit/flutter/custom-text-formatter-guide.mdx index ce0274947..00a0f9894 100644 --- a/ui-kit/flutter/custom-text-formatter-guide.mdx +++ b/ui-kit/flutter/custom-text-formatter-guide.mdx @@ -116,9 +116,9 @@ TextStyle getMessageBubbleTextStyle( A hashtag formatter used with [CometChatMessageList](/ui-kit/flutter/message-list) and [CometChatMessageComposer](/ui-kit/flutter/message-composer). - +{/* - + */} From 829a50b4be67580a26cbb80bbf78909efa1e2a82 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 18:57:57 +0530 Subject: [PATCH 103/106] Update url-formatter-guide.mdx --- ui-kit/flutter/url-formatter-guide.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-kit/flutter/url-formatter-guide.mdx b/ui-kit/flutter/url-formatter-guide.mdx index b66fe6a6e..f260ad2d7 100644 --- a/ui-kit/flutter/url-formatter-guide.mdx +++ b/ui-kit/flutter/url-formatter-guide.mdx @@ -18,9 +18,9 @@ description: "Detect and style plain URLs as clickable links with optional track `CometChatUrlFormatter` extends [CometChatTextFormatter](/ui-kit/flutter/custom-text-formatter-guide) to detect URLs in text messages and render them as clickable links. - +{/* - + */} --- From 0ab7f74a9d37571afc70270ebe6f2898929db318 Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 19:02:58 +0530 Subject: [PATCH 104/106] Update message-header.mdx --- ui-kit/flutter/message-header.mdx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ui-kit/flutter/message-header.mdx b/ui-kit/flutter/message-header.mdx index 3cc79020d..0801bb6f3 100644 --- a/ui-kit/flutter/message-header.mdx +++ b/ui-kit/flutter/message-header.mdx @@ -490,10 +490,6 @@ CometChatMessageHeader( - - - - *** #### Options Menu From bfd4889ef614eaf812437b461e0fba84ef9a2aae Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 19:12:45 +0530 Subject: [PATCH 105/106] updates files --- ui-kit/flutter/events.mdx | 560 +++++++++++++++++++++---------------- ui-kit/flutter/methods.mdx | 514 +++++++++++++++------------------- 2 files changed, 539 insertions(+), 535 deletions(-) diff --git a/ui-kit/flutter/events.mdx b/ui-kit/flutter/events.mdx index ac8503b87..022885d91 100644 --- a/ui-kit/flutter/events.mdx +++ b/ui-kit/flutter/events.mdx @@ -1,9 +1,9 @@ --- title: "Events" -description: "Listen to UI Kit events for user actions, group changes, conversations, messages, calls, and UI interactions in Flutter." +description: "Listen to and handle real-time events for users, groups, conversations, messages, calls, and UI interactions in Flutter UI Kit" --- - + | Field | Value | | --- | --- | @@ -11,78 +11,93 @@ description: "Listen to UI Kit events for user actions, group changes, conversat | Conversation events | `ccConversationDeleted`, `ccUpdateConversation` | | User events | `ccUserBlocked`, `ccUserUnblocked` | | Group events | `ccGroupCreated`, `ccGroupDeleted`, `ccGroupLeft`, `ccGroupMemberScopeChanged`, `ccGroupMemberKicked`, `ccGroupMemberBanned`, `ccGroupMemberUnbanned`, `ccGroupMemberJoined`, `ccGroupMemberAdded`, `ccOwnershipChanged` | -| Message events | `ccMessageSent`, `ccMessageEdited`, `ccMessageDeleted`, `ccMessageRead`, `ccLiveReaction`, `ccMessageForwarded`, `ccReplyToMessage`, plus SDK listener events | +| Message events | `ccMessageSent`, `ccMessageEdited`, `ccReplyToMessage`, `ccMessageDeleted`, `ccMessageRead`, `ccLiveReaction`, `ccMessageForwarded`, plus SDK listener events | | Call events | `ccOutgoingCall`, `ccCallAccepted`, `ccCallRejected`, `ccCallEnded` | | UI events | `ccActiveChatChanged`, `showPanel`, `hidePanel`, `openChat`, `ccComposeMessage`, `onAiFeatureTapped` | | Purpose | Decoupled communication between UI Kit components — subscribe to events to react to changes without direct component references | -Events enable a decoupled, flexible architecture in the CometChat UI Kit. Components and Composite Components emit events in response to user interactions or state changes, allowing other parts of your application to react without direct references between components. +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** -## When to use this +```dart +// Add event listener +CometChatMessageEvents.addMessagesListener("LISTENER_ID", 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. +// Remove event listener +CometChatMessageEvents.removeMessagesListener("LISTENER_ID"); -## Prerequisites +// Implement listener methods +@override +void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { + // Handle message sent event +} +``` -- The `cometchat_chat_uikit` package added to your project. -- `CometChatUIKit.init()` called and completed successfully. -- A logged-in CometChat user (call `CometChatUIKit.login()` before registering listeners). +**Available Event Types:** +- **User Events** → Block/Unblock users +- **Group Events** → Create, delete, join, leave groups +- **Conversation Events** → Delete conversations, update conversations +- **Message Events** → Send, edit, delete, receive messages, reactions, AI messages +- **Call Events** → Outgoing, accepted, rejected, ended calls +- **UI Events** → Show/hide panels, active chat changes + -## API Reference +Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. -### User Events +Both Components and Composite Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. -`CometChatUserEvents` emits events when the logged-in user executes actions on another user. This class provides methods to add and remove listeners for user events. +*** -**Events:** +## User Events -| Event | Description | -| ----- | ----------- | -| `ccUserBlocked` | Triggered when the logged-in user blocks another user. | -| `ccUserUnblocked` | Triggered when the logged-in user unblocks another user. | +`CometChatUserEvents` emit events when the logged-in user executes actions on another user. This class provides methods to add and remove listeners for user events, as well as methods to handle specific user actions such as blocking and unblocking users. -**Listener registration:** +**Available Events:** + +1. `ccUserBlocked`: Triggered when the logged-in user blocks another user. +2. `ccUserUnblocked`: Triggered when the logged-in user unblocks another user. ```dart -class YourWidget extends StatefulWidget { - const YourWidget({super.key}); +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class UserEventsExample extends StatefulWidget { + const UserEventsExample({super.key}); @override - State createState() => _YourWidgetState(); + State createState() => _UserEventsExampleState(); } -class _YourWidgetState extends State with CometChatUserEventListener { - final String listenerID = "unique_listener_ID"; +class _UserEventsExampleState extends State with CometChatUserEventListener { + String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - CometChatUserEvents.addUsersListener(listenerID, this); + + CometChatUserEvents.addUsersListener(listenerID, this); // Add the listener } @override void dispose() { - CometChatUserEvents.removeUsersListener(listenerID); super.dispose(); + + CometChatUserEvents.removeUsersListener(listenerID); // Remove the listener } @override void ccUserBlocked(User user) { - // Handle user blocked + // TODO("Not yet implemented") } @override void ccUserUnblocked(User user) { - // Handle user unblocked + // TODO("Not yet implemented") } @override @@ -94,107 +109,104 @@ class _YourWidgetState extends State with CometChatUserEventListener -> **What this does:** Registers a listener on `CometChatUserEvents` using a unique `listenerID`. The `ccUserBlocked` callback fires when the logged-in user blocks another user, and `ccUserUnblocked` fires when the logged-in user unblocks another user. - ---- - -### Group Events +*** -`CometChatGroupEvents` emits events when the logged-in user performs actions related to groups. This class provides methods to listen to various group-related events. +## Group Events -**Events:** +`CometChatGroupEvents` Emits events when the logged-in user performs actions related to groups. This class provides methods to listen to various group-related events and handle them accordingly. -| Event | Description | -| ----- | ----------- | -| `ccGroupCreated` | Triggered when the logged-in user creates a group. | -| `ccGroupDeleted` | Triggered when the logged-in user deletes a group. | -| `ccGroupLeft` | Triggered when the logged-in user leaves a group. Provides the action message, the user who left, and the group. | -| `ccGroupMemberScopeChanged` | Triggered when the logged-in user changes the scope of another group member. Provides the action message, updated user, new scope, previous scope, and group. | -| `ccGroupMemberBanned` | Triggered when the logged-in user bans a group member. Provides the action message, banned user, who banned them, and the group. | -| `ccGroupMemberKicked` | Triggered when the logged-in user kicks a group member. Provides the action message, kicked user, who kicked them, and the group. | -| `ccGroupMemberUnbanned` | Triggered when the logged-in user unbans a user. Provides the action message, unbanned user, who unbanned them, and the group. | -| `ccGroupMemberJoined` | Triggered when the logged-in user joins a group. Provides the joined user and the group. | -| `ccGroupMemberAdded` | Triggered when the logged-in user adds new members to the group. Provides action messages, added users, the group, and who added them. | -| `ccOwnershipChanged` | Triggered when the logged-in user transfers group ownership. Provides the group and the new owner. | +**Available Events:** -**Listener registration:** +1. `ccGroupCreated`: Triggered when the logged-in user creates a group. +2. `ccGroupDeleted`: Triggered when the logged-in user deletes a group. +3. `ccGroupLeft`: Triggered when the logged-in user leaves a group. +4. `ccGroupMemberScopeChanged`: Triggered when the logged-in user changes the scope of another group member. +5. `ccGroupMemberBanned`: Triggered when the logged-in user bans a group member from the group. +6. `ccGroupMemberKicked`: Triggered when the logged-in user kicks another group member from the group. +7. `ccGroupMemberUnbanned`: Triggered when the logged-in user unbans a user banned from the group. +8. `ccGroupMemberJoined`: Triggered when the logged-in user joins a group. +9. `ccGroupMemberAdded`: Triggered when the logged-in user adds new members to the group. +10. `ccOwnershipChanged`: Triggered when the logged-in user transfers the ownership of their group to some other member. ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart' as sdk; +import 'package:flutter/material.dart'; -class YourWidget extends StatefulWidget { - const YourWidget({super.key}); +class GroupEventsExample extends StatefulWidget { + const GroupEventsExample({super.key}); @override - State createState() => _YourWidgetState(); + State createState() => _GroupEventsExampleState(); } -class _YourWidgetState extends State with CometChatGroupEventListener { - final String listenerID = "unique_listener_ID"; +class _GroupEventsExampleState extends State with CometChatGroupEventListener { + String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - CometChatGroupEvents.addGroupsListener(listenerID, this); + + CometChatGroupEvents.addGroupsListener(listenerID, this); // Add the listener } @override void dispose() { - CometChatGroupEvents.removeGroupsListener(listenerID); super.dispose(); + + CometChatGroupEvents.removeGroupsListener(listenerID); // Remove the listener } @override void ccGroupCreated(Group group) { - // Handle group created + // TODO("Not yet implemented") } @override void ccGroupDeleted(Group group) { - // Handle group deleted + // TODO("Not yet implemented") } @override void ccGroupLeft(sdk.Action message, User leftUser, Group leftGroup) { - // Handle user left group + // TODO("Not yet implemented") } @override void ccGroupMemberScopeChanged(sdk.Action message, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { - // Handle member scope changed + // TODO("Not yet implemented") } @override void ccGroupMemberBanned(sdk.Action message, User bannedUser, User bannedBy, Group bannedFrom) { - // Handle member banned + // TODO("Not yet implemented") } @override void ccGroupMemberKicked(sdk.Action message, User kickedUser, User kickedBy, Group kickedFrom) { - // Handle member kicked + // TODO("Not yet implemented") } @override void ccGroupMemberUnbanned(sdk.Action message, User unbannedUser, User unbannedBy, Group unbannedFrom) { - // Handle member unbanned + // TODO("Not yet implemented") } @override void ccGroupMemberJoined(User joinedUser, Group joinedGroup) { - // Handle member joined + // TODO("Not yet implemented") } @override void ccGroupMemberAdded(List messages, List usersAdded, Group groupAddedIn, User addedBy) { - // Handle members added + // TODO("Not yet implemented") } @override void ccOwnershipChanged(Group group, GroupMember newOwner) { - // Handle ownership changed + // TODO("Not yet implemented") } @override @@ -206,56 +218,55 @@ class _YourWidgetState extends State with CometChatGroupEventListene -> **What this does:** Registers a listener on `CometChatGroupEvents` using a unique `listenerID`. Each callback fires when the logged-in user performs the corresponding group action — creating, deleting, leaving a group, or managing members (scope change, ban, kick, unban, join, add, ownership transfer). - ---- - -### Conversation Events +*** -`CometChatConversationEvents` emits events when the logged-in user performs actions related to conversations. This allows the UI to be updated when conversations change. +## Conversation Events -**Events:** +The `CometChatConversationEvents` component emits events when the logged-in user performs actions related to conversations. This allows for the UI to be updated accordingly. -| Event | Description | -| ----- | ----------- | -| `ccConversationDeleted` | Triggered when the logged-in user deletes a conversation. | -| `ccUpdateConversation` | Triggered when a conversation is updated (e.g., unread count changes). | +**Available Events:** -**Listener registration:** +1. `ccConversationDeleted`: Triggered when the logged-in user deletes a conversation. +2. `ccUpdateConversation`: Triggered when a conversation is updated (e.g., unread count changes). ```dart -class YourWidget extends StatefulWidget { - const YourWidget({super.key}); +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class ConversationEventsExample extends StatefulWidget { + const ConversationEventsExample({super.key}); @override - State createState() => _YourWidgetState(); + State createState() => _ConversationEventsExampleState(); } -class _YourWidgetState extends State with CometChatConversationEventListener { - final String listenerID = "unique_listener_ID"; +class _ConversationEventsExampleState extends State with CometChatConversationEventListener { + String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - CometChatConversationEvents.addConversationListListener(listenerID, this); + + CometChatConversationEvents.addConversationListListener(listenerID, this); // Add the listener } @override void dispose() { - CometChatConversationEvents.removeConversationListListener(listenerID); super.dispose(); + + CometChatConversationEvents.removeConversationListListener(listenerID); // Remove the listener } @override void ccConversationDeleted(Conversation conversation) { - // Handle conversation deleted + // TODO("Not yet implemented") } @override void ccUpdateConversation(Conversation conversation) { - // Handle conversation updated + // TODO("Not yet implemented") } @override @@ -267,171 +278,229 @@ class _YourWidgetState extends State with CometChatConversationEvent -> **What this does:** Registers a listener on `CometChatConversationEvents` using a unique listener ID. The `ccConversationDeleted` callback fires when the logged-in user deletes a conversation, and `ccUpdateConversation` fires when a conversation is updated. - ---- - -### Message Events - -`CometChatMessageEvents` emits events when various actions are performed on messages within the application. These events facilitate updating the UI when messages change. - -**UI Kit Events:** - -| Event | Description | -| ----- | ----------- | -| `ccMessageSent` | Triggered when a message is sent. States: `inProgress`, `sent`. | -| `ccMessageEdited` | Triggered when a message is edited. States: `inProgress`, `sent`. | -| `ccMessageDeleted` | Triggered when a message is deleted. | -| `ccMessageRead` | Triggered when a message is read. | -| `ccLiveReaction` | Triggered when a live reaction is clicked. | -| `ccMessageForwarded` | Triggered when a message is forwarded. | -| `ccReplyToMessage` | Triggered when replying to a message. | - -**SDK Listener Events:** - -| Event | Description | -| ----- | ----------- | -| `onTextMessageReceived` | Triggered when a text message is received. | -| `onMediaMessageReceived` | Triggered when a media message is received. | -| `onCustomMessageReceived` | Triggered when a custom message is received. | -| `onTypingStarted` | Triggered when typing indicator starts. | -| `onTypingEnded` | Triggered when typing indicator ends. | -| `onMessagesDelivered` | Triggered when messages are delivered. | -| `onMessagesRead` | Triggered when messages are read. | -| `onMessageEdited` | Triggered when a message is edited by another user. | -| `onMessageDeleted` | Triggered when a message is deleted by another user. | -| `onTransientMessageReceived` | Triggered when a transient message is received. | -| `onFormMessageReceived` | Triggered when a form message is received. | -| `onCardMessageReceived` | Triggered when a card message is received. | -| `onCustomInteractiveMessageReceived` | Triggered when a custom interactive message is received. | -| `onSchedulerMessageReceived` | Triggered when a scheduler message is received. | -| `onInteractionGoalCompleted` | Triggered when an interaction goal is completed. | -| `onMessageReactionAdded` | Triggered when a reaction is added. | -| `onMessageReactionRemoved` | Triggered when a reaction is removed. | -| `onMessagesDeliveredToAll` | Triggered when messages are delivered to all recipients. | -| `onMessagesReadByAll` | Triggered when messages are read by all recipients. | -| `onMessageModerated` | Triggered when a message is moderated. | -| `onAIAssistantMessageReceived` | Triggered when an AI Assistant message is received. | -| `onAIToolResultReceived` | Triggered when an AI tool result is received. | -| `onAIToolArgumentsReceived` | Triggered when AI tool arguments are received. | - -**Listener registration:** +*** + +## Message Events + +`CometChatMessageEvents` emits events when various actions are performed on messages within the application. These events facilitate updating the UI accordingly. + +**Available Events:** + +1. `ccMessageSent`: Triggered whenever a logged-in user sends any message. It can have two states: `inProgress` and `sent`. +2. `ccMessageEdited`: Triggered whenever a logged-in user edits any message from the list of messages. It can have two states: `inProgress` and `sent`. +3. `ccMessageDeleted`: Triggered whenever a logged-in user deletes any message from the list of messages. +4. `ccMessageRead`: Triggered whenever a logged-in user reads any message. +5. `ccLiveReaction`: Triggered whenever a logged-in user clicks on a live reaction. +6. `ccMessageForwarded`: Triggered whenever a logged-in user forwards any message to a list of users or groups. It can have a state of `status`. +7. `onTextMessageReceived`: Triggered when a text message is received. +8. `onMediaMessageReceived`: Triggered when a media message is received. +9. `onCustomMessageReceived`: Triggered when a custom message is received. +10. `onTypingStarted`: Triggered when a typing indicator starts. +11. `onTypingEnded`: Triggered when a typing indicator ends. +12. `onMessagesDelivered`: Triggered when messages are delivered. +13. `onMessagesRead`: Triggered when messages are read. +14. `onMessageEdited`: Triggered when a message is edited. +15. `onMessageDeleted`: Triggered when a message is deleted. +16. `onTransientMessageReceived`: Triggered when a transient message is received. +17. `onFormMessageReceived`: Triggered when a form message is received. +18. `onCardMessageReceived`: Triggered when a card message is received. +19. `onCustomInteractiveMessageReceived`: Triggered when a custom interactive message is received. +20. `onInteractionGoalCompleted`: Triggered when an interaction goal is completed. +21. `onSchedulerMessageReceived`: Triggered when a scheduler message is received. +22. `onMessageReactionAdded`: Triggered when a reaction is added to a message. +23. `onMessageReactionRemoved`: Triggered when a reaction is removed from a message. +24. `ccReplyToMessage`: Triggered when the logged-in user replies to a message. +25. `onMessagesDeliveredToAll`: Triggered when messages are delivered to all recipients. +26. `onMessagesReadByAll`: Triggered when messages are read by all recipients. +27. `onMessageModerated`: Triggered when a message is moderated. +28. `onAIAssistantMessageReceived`: Triggered when an AI Assistant message is received. +29. `onAIToolResultReceived`: Triggered when an AI tool result is received. +30. `onAIToolArgumentsReceived`: Triggered when AI tool arguments are received. ```dart -class YourWidget extends StatefulWidget { - const YourWidget({super.key}); +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class MessageEventsExample extends StatefulWidget { + const MessageEventsExample({super.key}); @override - State createState() => _YourWidgetState(); + State createState() => _MessageEventsExampleState(); } -class _YourWidgetState extends State with CometChatMessageEventListener { - final String listenerID = "unique_listener_ID"; +class _MessageEventsExampleState extends State with CometChatMessageEventListener { + String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - CometChatMessageEvents.addMessagesListener(listenerID, this); + + CometChatMessageEvents.addMessagesListener(listenerID, this); // Add the listener } @override void dispose() { - CometChatMessageEvents.removeMessagesListener(listenerID); super.dispose(); + + CometChatMessageEvents.removeMessagesListener(listenerID); // Remove the listener } - // UI Kit Events @override void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { - // Handle message sent + // TODO("Not yet implemented") } @override void ccMessageEdited(BaseMessage message, MessageEditStatus status) { - // Handle message edited + // TODO("Not yet implemented") } @override void ccMessageDeleted(BaseMessage message, EventStatus messageStatus) { - // Handle message deleted + // TODO("Not yet implemented") } @override void ccMessageRead(BaseMessage message) { - // Handle message read + // TODO("Not yet implemented") } @override void ccLiveReaction(String reaction) { - // Handle live reaction + // TODO("Not yet implemented") } @override void ccMessageForwarded(BaseMessage message, List? usersSent, List? groupsSent, MessageStatus status) { - // Handle message forwarded + // TODO("Not yet implemented") } @override void ccReplyToMessage(BaseMessage message, MessageStatus status) { - // Handle reply to message + // TODO("Not yet implemented") } - // SDK Listener Events @override void onTextMessageReceived(TextMessage textMessage) { - // Handle text message received + // TODO("Not yet implemented") } @override void onMediaMessageReceived(MediaMessage mediaMessage) { - // Handle media message received + // TODO("Not yet implemented") } @override void onCustomMessageReceived(CustomMessage customMessage) { - // Handle custom message received + // TODO("Not yet implemented") } @override void onTypingStarted(TypingIndicator typingIndicator) { - // Handle typing started + // TODO("Not yet implemented") } @override void onTypingEnded(TypingIndicator typingIndicator) { - // Handle typing ended + // TODO("Not yet implemented") } @override void onMessagesDelivered(MessageReceipt messageReceipt) { - // Handle messages delivered + // TODO("Not yet implemented") } @override void onMessagesRead(MessageReceipt messageReceipt) { - // Handle messages read + // TODO("Not yet implemented") } @override void onMessageEdited(BaseMessage message) { - // Handle message edited by another user + // TODO("Not yet implemented") } @override void onMessageDeleted(BaseMessage message) { - // Handle message deleted by another user + // TODO("Not yet implemented") + } + + @override + void onTransientMessageReceived(TransientMessage message) { + // TODO("Not yet implemented") + } + + @override + void onFormMessageReceived(FormMessage formMessage) { + // TODO("Not yet implemented") + } + + @override + void onCardMessageReceived(CardMessage cardMessage) { + // TODO("Not yet implemented") + } + + @override + void onCustomInteractiveMessageReceived( + CustomInteractiveMessage customInteractiveMessage) { + // TODO("Not yet implemented") + } + + @override + void onInteractionGoalCompleted(InteractionReceipt receipt) { + // TODO("Not yet implemented") + } + + @override + void onSchedulerMessageReceived(SchedulerMessage schedulerMessage) { + // TODO("Not yet implemented") } @override void onMessageReactionAdded(ReactionEvent reactionEvent) { - // Handle reaction added + // TODO("Not yet implemented") } @override void onMessageReactionRemoved(ReactionEvent reactionEvent) { - // Handle reaction removed + // TODO("Not yet implemented") + } + + @override + void ccReplyToMessage(BaseMessage message, MessageStatus status) { + // TODO("Not yet implemented") + } + + @override + void onMessagesDeliveredToAll(MessageReceipt messageReceipt) { + // TODO("Not yet implemented") + } + + @override + void onMessagesReadByAll(MessageReceipt messageReceipt) { + // TODO("Not yet implemented") + } + + @override + void onMessageModerated(BaseMessage message) { + // TODO("Not yet implemented") + } + + @override + void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { + // TODO("Not yet implemented") + } + + @override + void onAIToolResultReceived(AIToolResultMessage aiToolResultMessage) { + // TODO("Not yet implemented") + } + + @override + void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { + // TODO("Not yet implemented") } @override @@ -443,68 +512,67 @@ class _YourWidgetState extends State with CometChatMessageEventListe -> **What this does:** Registers a listener on `CometChatMessageEvents` using a unique ID string. The callbacks fire for message lifecycle events — sending, editing, deleting, reading messages, reactions, and receiving various message types including interactive and AI messages. +*** ---- +## Call Events -### Call Events +`CometChatCallEvents` emits events related to calls within the application. This class provides methods to listen to call-related events and handle them accordingly. -`CometChatCallEvents` emits events related to calls within the application. This class provides methods to listen to call-related events. +**Available Events:** -**Events:** - -| Event | Description | -| ----- | ----------- | -| `ccOutgoingCall` | Triggered when the logged-in user initiates an outgoing call. | -| `ccCallAccepted` | Triggered when a call is accepted. | -| `ccCallRejected` | Triggered when a call is rejected. | -| `ccCallEnded` | Triggered when a call is ended. | - -**Listener registration:** +1. `ccOutgoingCall`: Triggered when the logged-in user initiates an outgoing call. +2. `ccCallAccepted`: Triggered when a call is accepted. +3. `ccCallRejected`: Triggered when a call is rejected. +4. `ccCallEnded`: Triggered when a call is ended. ```dart -class YourWidget extends StatefulWidget { - const YourWidget({super.key}); +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class CallEventsExample extends StatefulWidget { + const CallEventsExample({super.key}); @override - State createState() => _YourWidgetState(); + State createState() => _CallEventsExampleState(); } -class _YourWidgetState extends State with CometChatCallEventListener { - final String listenerID = "unique_listener_ID"; +class _CallEventsExampleState extends State with CometChatCallEventListener { + String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - CometChatCallEvents.addCallEventsListener(listenerID, this); + + CometChatCallEvents.addCallEventsListener(listenerID, this); // Add the listener } @override void dispose() { - CometChatCallEvents.removeCallEventsListener(listenerID); super.dispose(); + + CometChatCallEvents.removeCallEventsListener(listenerID); // Remove the listener } @override void ccOutgoingCall(Call call) { - // Handle outgoing call initiated + // TODO("Not yet implemented") } @override void ccCallAccepted(Call call) { - // Handle call accepted + // TODO("Not yet implemented") } @override void ccCallRejected(Call call) { - // Handle call rejected + // TODO("Not yet implemented") } @override void ccCallEnded(Call call) { - // Handle call ended + // TODO("Not yet implemented") } @override @@ -516,80 +584,79 @@ class _YourWidgetState extends State with CometChatCallEventListener -> **What this does:** Registers a listener on `CometChatCallEvents` using a unique `listenerID`. The callbacks fire for each stage of the call lifecycle — initiating an outgoing call, accepting, rejecting, and ending a call. - ---- - -### UI Events +*** -`CometChatUIEvents` emits events related to UI components within the CometChat UI Kit. This class provides methods to listen to UI-related events. +## UI Events -**Events:** +`CometChatUIEvents` emits events related to UI components within the CometChat UI. This class provides methods to listen to UI-related events and handle them accordingly. -| Event | Description | -| ----- | ----------- | -| `showPanel` | Triggered to show an additional UI panel with custom elements. | -| `hidePanel` | Triggered to hide a previously shown UI panel. | -| `ccActiveChatChanged` | Triggered when the active chat changes, providing the current message, user, group, and unread count. | -| `openChat` | Triggered to open a chat with a specific user or group. | -| `ccComposeMessage` | Triggered when composing a message with specific text and status. | -| `onAiFeatureTapped` | Triggered when an AI feature is tapped for a specific user or group. | +**Available Events:** -**Listener registration:** +1. `showPanel`: Triggered to show an additional UI panel with custom elements. +2. `hidePanel`: Triggered to hide a previously shown UI panel. +3. `ccActiveChatChanged`: Triggered when the active chat changes, providing information about the current message, user, and group. +4. `openChat`: Triggered to open a chat with a specific user or group. +5. `ccComposeMessage`: Triggered when composing a message with a specific text and status. +6. `onAiFeatureTapped`: Triggered when an AI feature is tapped for a specific user or group. ```dart -class YourWidget extends StatefulWidget { - const YourWidget({super.key}); +import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; +import 'package:flutter/material.dart'; + +class UIEventsExample extends StatefulWidget { + const UIEventsExample({super.key}); @override - State createState() => _YourWidgetState(); + State createState() => _UIEventsExampleState(); } -class _YourWidgetState extends State with CometChatUIEventListener { - final String listenerID = "unique_listener_ID"; +class _UIEventsExampleState extends State with CometChatUIEventListener { + String listenerID = "unique_listener_ID"; @override void initState() { super.initState(); - CometChatUIEvents.addUiListener(listenerID, this); + + CometChatUIEvents.addUiListener(listenerID, this); // Add the listener } @override void dispose() { - CometChatUIEvents.removeUiListener(listenerID); super.dispose(); + + CometChatUIEvents.removeUiListener(listenerID); // Remove the listener } @override void showPanel(Map? id, CustomUIPosition uiPosition, WidgetBuilder child) { - // Handle show panel + // TODO("Not yet implemented") } @override void hidePanel(Map? id, CustomUIPosition uiPosition) { - // Handle hide panel + // TODO("Not yet implemented") } @override void ccActiveChatChanged(Map? id, BaseMessage? lastMessage, User? user, Group? group, int unreadMessageCount) { - // Handle active chat changed + // TODO("Not yet implemented") } @override void openChat(User? user, Group? group) { - // Handle open chat + // TODO("Not yet implemented") } @override void ccComposeMessage(String text, MessageEditStatus status) { - // Handle compose message + // TODO("Not yet implemented") } @override void onAiFeatureTapped(User? user, Group? group) { - // Handle AI feature tapped + // TODO("Not yet implemented") } @override @@ -601,23 +668,7 @@ class _YourWidgetState extends State with CometChatUIEventListener { -> **What this does:** Registers a listener on `CometChatUIEvents` using a unique ID string. The callbacks fire for UI-level actions — showing or hiding custom panels, reacting to active chat changes, opening a chat, composing messages, and AI feature interactions. - ---- - -## Removing Event Listeners - -Each event listener class provides methods to add and remove listeners. Always remove listeners in the `dispose()` method to prevent memory leaks. Use the same listener ID you passed during registration. - -```dart -@override -void dispose() { - CometChatMessageEvents.removeMessagesListener(listenerID); - super.dispose(); -} -``` - ---- +*** ## Best Practices @@ -625,54 +676,69 @@ void dispose() { Always remove event listeners in the `dispose()` method to prevent memory leaks: + + ```dart @override void dispose() { - CometChatMessageEvents.removeMessagesListener(listenerID); super.dispose(); + CometChatMessageEvents.removeMessagesListener(listenerID); } ``` + + Use unique listener IDs for each widget to avoid conflicts: + + ```dart - final String listenerID = "message_list_${widget.key}"; + String listenerID = "message_list_${widget.key}"; ``` + + Keep event handlers lightweight and avoid heavy operations: + + ```dart @override void ccMessageSent(BaseMessage message, MessageStatus messageStatus) { if (messageStatus == MessageStatus.sent) { + // Update UI efficiently setState(() { // Minimal state update }); } } ``` + + ---- +*** ## Next Steps - - UI Kit wrapper methods for initialization, authentication, and sending messages + + Learn how to display and manage messages with events - Display and manage the conversation list, which reacts to conversation events - - - Display messages in a chat, which reacts to message events + Handle conversation events and updates Manage group events and member actions + + Explore available methods for UI Kit operations + + +*** diff --git a/ui-kit/flutter/methods.mdx b/ui-kit/flutter/methods.mdx index a4835c368..222a617cf 100644 --- a/ui-kit/flutter/methods.mdx +++ b/ui-kit/flutter/methods.mdx @@ -3,7 +3,7 @@ title: "Methods" description: "Reference for CometChat Flutter UI Kit methods including init, login, logout, and message-sending wrappers." --- - + | Field | Value | | --- | --- | @@ -20,29 +20,23 @@ description: "Reference for CometChat Flutter UI Kit methods including init, log -`CometChatUIKit` provides wrapper methods around the CometChat SDK for initialization, authentication, user management, date formatting, and sending messages — while automatically managing internal UI Kit events so that components like Message List and Conversations stay in sync. +## Overview -## When to use this +The UI Kit's core function is to extend the [Chat SDK](/sdk/flutter/overview), essentially translating the raw data and functionality provided by the underlying methods into visually appealing and easy-to-use UI components. -- You need to initialize the CometChat UI Kit and SDK before rendering any UI components. -- You need to log a user in or out of CometChat using an Auth Key (development) or Auth Token (production). -- You need to create or update a CometChat user dynamically from your app. -- You need to send text, media, custom, or interactive messages through the UI Kit so that the Message List and Conversations components update automatically. -- You need to customize how dates and times are displayed across all UI Kit components. +To effectively manage and synchronize the UI elements and data across all components in the UI Kit, we utilize internal events. These internal events enable us to keep track of changes in real-time and ensure that the UI reflects the most current state of data. -## Prerequisites +The CometChat UI Kit has thoughtfully encapsulated the critical [Chat SDK](/sdk/flutter/overview) methods within its wrapper to efficiently manage internal eventing. This layer of abstraction simplifies interaction with the underlying CometChat SDK, making it more user-friendly for developers. -- The `cometchat_chat_uikit` package added to your project. -- Your CometChat App ID, Region, and Auth Key (or Auth Token) from the [CometChat dashboard](https://app.cometchat.com/). -- `CometChatUIKit.init()` called before invoking any other UI Kit method. +## Methods -## API Reference +You can access the methods using the `CometChatUIKit` class. This class provides access to all the public methods exposed by the CometChat UI Kit. -### Initialization +### Init -#### Init +As a developer, you need to invoke this method every time before you use any other methods provided by the UI Kit. -You must invoke this method before using any other methods provided by the UI Kit. This initialization ensures the UI Kit and Chat SDK function correctly in your application. Call this as one of the first lines of code in your application's lifecycle. +This initialization is a critical step that ensures the UI Kit and Chat SDK function correctly and as intended in your application. Typical practice is to make this one of the first lines of code executed in your application's lifecycle when it comes to implementing CometChat. `CometChatUIKit.init()` must be called before rendering any UI Kit components or calling any SDK methods. Initialization must complete before login. @@ -53,12 +47,12 @@ Auth Key is for development/testing only. In production, generate Auth Tokens on -Replace `APP_ID`, `REGION`, and `AUTH_KEY` with values from the CometChat Dashboard. `Auth Key` is optional — use [Auth Token](#login-using-auth-token) for production. +Make sure you replace the **APP\_ID**, **REGION** and **AUTH\_KEY** with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#login-using-auth-token) to log in securely. -The `UIKitSettings` is an important parameter of the `init()` function. It serves as the base settings object, housing properties such as `appId`, `region`, and `authKey`. +As a developer, the `UIKitSettings` is an important parameter of the `init()` function. It functions as a base settings object, housing properties such as `appId`, `region`, and `authKey`, contained within `UIKitSettings`. -#### UIKitSettings Properties +Here's the table format for the properties available in `UIKitSettings`: | Method | Type | Description | | --------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | @@ -75,11 +69,13 @@ The `UIKitSettings` is an important parameter of the `init()` function. It serve | **clientHost** | `String` | Sets a custom client host URL | | **dateTimeFormatterCallback** | `DateTimeFormatterCallback` | Sets a custom date/time formatter for consistent formatting across all UI components | -#### Usage +*** + +The concluding code block: -```dart +```dart highlight={3-5} UIKitSettings uiKitSettings = (UIKitSettingsBuilder() ..subscriptionType = CometChatSubscriptionType.allUsers ..autoEstablishSocketConnection = true @@ -98,24 +94,20 @@ CometChatUIKit.init( }, ); ``` - - -> **What this does:** Creates a `UIKitSettings` object with your app ID, region, and auth key, then initializes the CometChat UI Kit. On success, the SDK and UI Kit are ready for use. On error, the callback provides failure details. - ---- + -### Authentication + -#### Login using Auth Key +*** -Only the `UID` of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, use [Auth Token](#login-using-auth-token) instead of Auth Key. +### Login using Auth Key -#### Usage +Only the `UID` of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, we suggest you use [AuthToken](#login-using-auth-token) instead of Auth Key. -```dart +```dart highlight={1} String uid = "user1"; CometChatUIKit.login( @@ -128,26 +120,26 @@ CometChatUIKit.login( }, ); ``` + - -> **What this does:** Logs in a user by their `UID` using the Auth Key configured during initialization. On success, the `User` object is returned. On error, the callback provides failure details. + ---- +*** -#### Login using Auth Token +### Login using Auth Token Production-safe authentication that does not expose the Auth Key in client code. 1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. + 2. [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database. -3. Load the Auth Token in your client and pass it to the `loginWithAuthToken()` method. -#### Usage +3. Load the Auth Token in your client and pass it to the `loginWithAuthToken()` method. -```dart +```dart highlight={1} String authToken = "AUTH_TOKEN"; CometChatUIKit.loginWithAuthToken( @@ -160,191 +152,178 @@ CometChatUIKit.loginWithAuthToken( }, ); ``` - - -> **What this does:** Logs in a user using a server-generated Auth Token instead of an Auth Key. This is the recommended approach for production apps because the Auth Key never appears in client code. On success, the `User` object is returned. + ---- + -#### Logout +*** -The CometChat UI Kit and Chat SDK effectively handle the session of the logged-in user within the framework. Before a new user logs in, it is crucial to clean this data to avoid potential conflicts or unexpected behavior. This can be achieved by invoking the `logout()` function. +### Logout -#### Usage +The CometChat UI Kit and Chat SDK effectively handle the session of the logged-in user within the framework. Before a new user logs in, it is crucial to clean this data to avoid potential conflicts or unexpected behavior. This can be achieved by invoking the `.logout()` function ```dart -CometChatUIKit.logout( - onSuccess: (s) { - // Logout successful - }, - onError: (e) { - // Handle logout error - }, -); +CometChatUIKit.logout(onSuccess: (s) { + // TODO("Not yet implemented") +} , onError: (e) { + // TODO("Not yet implemented") +}); ``` - - -> **What this does:** Logs out the current user, clears the session data, and tears down the internal event system. Call this before logging in a different user to avoid conflicts. - ---- + -### User Management + -#### Create User +*** -You can dynamically create users on CometChat using the `createUser()` function. This is useful when users are registered or authenticated by your system and then need to be created on CometChat. +### Create User -#### Usage +As a developer, you can dynamically create users on CometChat using the `.createUser()` function. This can be extremely useful for situations where users are registered or authenticated by your system and then need to be created on CometChat. ```dart -User user = User(uid: "user_uid", name: "user_name"); - -CometChatUIKit.createUser( - user, - onSuccess: (user) { - // User created successfully - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.createUser(userObject, onSuccess: (user) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); ``` - - -> **What this does:** Creates a new user on CometChat with the specified UID and name. On success, the created `User` object is returned. On error, the callback provides failure details. + ---- + -#### Update User +*** -You can update user details using the `updateUser()` function. This should ideally be achieved at your backend using the Restful APIs, but can also be done client-side when needed. +### Update User -#### Usage +As a developer, you can update user details using the `.updateUser()` function. This should ideally be achieved at your backend using the Restful APIs, but can also be done client-side when needed. ```dart -User user = User(uid: "user_uid", name: "updated_name"); - -CometChatUIKit.updateUser( - user, - onSuccess: (user) { - // User updated successfully - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.updateUser(userObject, onSuccess: (user) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); ``` - - -> **What this does:** Updates an existing user's details on CometChat. On success, the updated `User` object is returned. + ---- + -#### Get Logged In User +*** -You can check if there is any existing session in the SDK and retrieve the details of the logged-in user using the `getLoggedInUser()` function. +### Get Logged In User -#### Usage +You can check if there is any existing session in the SDK and retrieve the details of the logged-in user using the `.getLoggedInUser()` function. ```dart -CometChatUIKit.getLoggedInUser( - onSuccess: (user) { - if (user != null) { - // User is logged in - } else { - // No user logged in - } - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.getLoggedInUser(onSuccess: (user) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); ``` + - -> **What this does:** Checks for an existing session in the SDK. Returns the logged-in user details or `null` if no user is logged in. + ---- +*** ### DateFormatter -By providing a custom implementation of the `DateTimeFormatterCallback`, you can globally configure how time and date values are displayed across all UI components in the CometChat UI Kit. This ensures consistent formatting for labels such as "Today", "Yesterday", "X minutes ago", and more, throughout the entire application. +By providing a custom implementation of the DateTimeFormatterCallback, you can globally configure how time and date values are displayed across all UI components in the CometChat UI Kit. This ensures consistent formatting for labels such as "Today", "Yesterday", "X minutes ago", and more, throughout the entire application. Each method in the interface corresponds to a specific case: -- `time(int? timestamp)` → Custom full timestamp format -- `today(int? timestamp)` → Called when a message is from today -- `yesterday(int? timestamp)` → Called for yesterday's messages -- `lastWeek(int? timestamp)` → Messages from the past week -- `otherDays(int? timestamp)` → Older messages -- `minute(int? timestamp)` / `hour(int? timestamp)` → Exact time unit -- `minutes(int? diffInMinutesFromNow, int? timestamp)` → e.g., "5 minutes ago" -- `hours(int? diffInHourFromNow, int? timestamp)` → e.g., "2 hours ago" - -#### Usage +* time(int? timestamp) → Custom full timestamp format +* today(int? timestamp) → Called when a message is from today +* yesterday(int? timestamp) → Called for yesterday’s messages +* lastWeek(int? timestamp) → Messages from the past week +* otherDays(int? timestamp) → Older messages +* minute(int? timestamp) / hour(int? timestamp) → Exact time unit +* minutes(int? diffInMinutesFromNow, int? timestamp) → e.g., "5 minutes ago" +* hours(int? diffInHourFromNow, int? timestamp) → e.g., "2 hours ago" + ```dart import 'package:cometchat_chat_uikit/cometchat_chat_uikit.dart'; import 'package:intl/intl.dart'; +/// Custom implementation of DateTimeFormatterCallback +/// to format time and date display in the CometChat UI. class DateFormatter extends DateTimeFormatterCallback { + /// Formatter for displaying full time like "10:45 PM" final DateFormat fullTimeFormatter = DateFormat('hh:mm a'); + + /// Formatter for displaying date like "23 Jun 2025" final DateFormat dateFormatter = DateFormat('dd MMM yyyy'); + /// Returns formatted time (e.g., "10:45 PM") for a given timestamp. @override String? time(int? timestamp) { if (timestamp == null) return null; return fullTimeFormatter.format(DateTime.fromMillisecondsSinceEpoch(timestamp)); } + /// Returns a static label for messages sent today. @override - String? today(int? timestamp) => "Today"; + String? today(int? timestamp) { + return "Today"; + } + /// Returns a static label for messages sent yesterday. @override - String? yesterday(int? timestamp) => "Yesterday"; + String? yesterday(int? timestamp) { + return "Yesterday"; + } + /// Returns a static label for messages sent last week. @override - String? lastWeek(int? timestamp) => "Last Week"; + String? lastWeek(int? timestamp) { + return "Last Week"; + } + /// Returns formatted date (e.g., "23 Jun 2025") for other days. @override String? otherDays(int? timestamp) { if (timestamp == null) return null; return dateFormatter.format(DateTime.fromMillisecondsSinceEpoch(timestamp)); } + /// Returns relative time in minutes (e.g., "5 mins ago"). @override String? minutes(int? diffInMinutesFromNow, int? timestamp) { if (diffInMinutesFromNow == null) return null; return "$diffInMinutesFromNow mins ago"; } + /// Returns relative time in hours (e.g., "2 hrs ago"). @override String? hours(int? diffInHourFromNow, int? timestamp) { if (diffInHourFromNow == null) return null; return "$diffInHourFromNow hrs ago"; } + /// (Optional) Returns formatted hour (e.g., "3 PM") if used by SDK. @override String? hour(int? timestamp) { if (timestamp == null) return null; return DateFormat('h a').format(DateTime.fromMillisecondsSinceEpoch(timestamp)); } + /// (Optional) Returns formatted minute value (e.g., "09") if used by SDK. @override String? minute(int? timestamp) { if (timestamp == null) return null; @@ -352,47 +331,71 @@ class DateFormatter extends DateTimeFormatterCallback { } } -// Apply the custom formatter during initialization +// Build CometChat UIKit settings UIKitSettings uiKitSettings = (UIKitSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..region = "your_region" - ..appId = "your_appID" - ..authKey = "your_authKey" - ..dateTimeFormatterCallback = DateFormatter() -).build(); + // Set subscription type (e.g., receive messages from all users) + ..subscriptionType = CometChatSubscriptionType.allUsers + + // Set your CometChat region + ..region = AppCredentials.region + + // Automatically connect to socket server + ..autoEstablishSocketConnection = true + + // CometChat App ID and Auth Key + ..appId = AppCredentials.appId + ..authKey = AppCredentials.authKey + + // Enable calling feature + ..callingExtension = CometChatCallingExtension() + + // Load default chat extensions (e.g., polls, stickers, reactions) + ..extensions = CometChatUIKitChatExtensions.getDefaultExtensions() + // Load default AI features (e.g., Smart Replies, Sentiment Analysis) + ..aiFeature = CometChatUIKitChatAIFeatures.getDefaultAiFeatures() + + // Inject the custom date and time formatter + ..dateTimeFormatterCallback = DateFormatter() + ) + .build(); + +// Initialize CometChat UIKit with the configured settings CometChatUIKit.init( uiKitSettings: uiKitSettings, + + // Callback when initialization is successful onSuccess: (successMessage) async { - // Initialization successful + // On success }, + + // Callback when initialization fails onError: (e) { - // Handle error + shouldGoToHomeScreen.value = false; + if (kDebugMode) { + debugPrint("Initialization failed with error: ${e.details}"); + } }, ); + + ``` + - -> **What this does:** Configures a custom `DateTimeFormatterCallback` on `UIKitSettings` and passes it to `CometChatUIKit.init()`. This globally overrides how timestamps appear across all UI Kit components — today's messages show "Today", yesterday's show "Yesterday", recent messages show "X mins ago" or "X hrs ago", last week's show "Last Week", and older messages show the full date in "dd MMM yyyy" format. + ---- +*** ### Base Message #### Text Message -To send a text message to a single user or a group, use the `sendTextMessage()` function. This function requires a `TextMessage` object as its argument, which contains the necessary information for delivering the message. - - -`CometChatUIKit.sendTextMessage()` automatically adds the message to the [MessageList](/ui-kit/flutter/message-list) and [Conversations](/ui-kit/flutter/conversations) components, handling all related cases for you. In contrast, `CometChat.sendTextMessage()` only sends the message without updating these UI Kit components. - - -#### Usage +Sends a text message in a 1:1 or group chat. Takes a `TextMessage` object. -```dart +```dart highlight={1-2} String receiverID = "UID"; String messageText = "Hello world!"; @@ -412,9 +415,11 @@ CometChatUIKit.sendTextMessage( }, ); ``` + + -```dart +```dart highlight={1-2} String receiverID = "GUID"; String messageText = "Hello world!"; @@ -434,26 +439,20 @@ CometChatUIKit.sendTextMessage( }, ); ``` + - -> **What this does:** Creates a `TextMessage` targeting a user or group, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components. + ---- +*** #### Media Message -To send a media message to a single user or a group, use the `sendMediaMessage()` function. This function requires a `MediaMessage` object as its argument, which contains the necessary information for delivering the message. - - -`CometChatUIKit.sendMediaMessage()` automatically adds the message to the [MessageList](/ui-kit/flutter/message-list) and [Conversations](/ui-kit/flutter/conversations) components, handling all related cases for you. In contrast, `CometChat.sendMediaMessage()` only sends the message without updating these UI Kit components. - - -#### Usage +Sends a media message in a 1:1 or group chat. Takes a `MediaMessage` object. -```dart +```dart highlight={1-2} String receiverID = "UID"; String filePath = "/path/to/file"; @@ -474,9 +473,11 @@ CometChatUIKit.sendMediaMessage( }, ); ``` + + -```dart +```dart highlight={1-2} String receiverID = "GUID"; String filePath = "/path/to/file"; @@ -497,30 +498,20 @@ CometChatUIKit.sendMediaMessage( }, ); ``` + - -> **What this does:** Creates a `MediaMessage` with a file path and message type, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components. + ---- +*** #### Custom Message -To send a custom message (neither text nor media) to a single user or a group, use the `sendCustomMessage()` function. This function requires a `CustomMessage` object as its argument, which contains the necessary information for delivering the message. - - -`CometChatUIKit.sendCustomMessage()` automatically adds the message to the [MessageList](/ui-kit/flutter/message-list) and [Conversations](/ui-kit/flutter/conversations) components, handling all related cases for you. In contrast, `CometChat.sendCustomMessage()` only sends the message without updating these UI Kit components. - - - -To display custom messages in the [MessageList](/ui-kit/flutter/message-list), you must create and register a new [MessageTemplate](/ui-kit/flutter/message-template) that defines how to render your custom message type. - - -#### Usage +Sends a custom message (neither text nor media) in a 1:1 or group chat. Takes a `CustomMessage` object. -```dart +```dart highlight={1,3-4} String receiverID = "UID"; Map customData = { "latitude": "50.6192171633316", @@ -545,9 +536,11 @@ CometChatUIKit.sendCustomMessage( }, ); ``` + + -```dart +```dart highlight={1,3-4} String receiverID = "GUID"; Map customData = { "latitude": "50.6192171633316", @@ -572,188 +565,133 @@ CometChatUIKit.sendCustomMessage( }, ); ``` + - -> **What this does:** Creates a `CustomMessage` with a custom type string and data payload, then sends it through the UI Kit. The message automatically appears in the Message List and Conversations components. + ---- +*** ### Interactive Message #### Form Message -To send a Form message to a single user or a group, use the `sendFormMessage()` function. This function requires a `FormMessage` object as its argument, which contains the necessary information to create a form bubble for that message. - -#### Usage +As a developer, if you need to send a Form message to a single user or a group, you'll need to utilize the `sendFormMessage()` function. This function requires a `FormMessage` object as its argument, which contains the necessary information to create a form bubble for that messages ```dart -CometChatUIKit.sendFormMessage( - formMessageObject, - onSuccess: (message) { - // Form message sent successfully - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.sendFormMessage(formMessageObject, onSuccess: (p0) { + // TODO("Not yet implemented") +}, onError: (p0) { + // TODO("Not yet implemented") +}); ``` + - -> **What this does:** Sends a `FormMessage` that renders as an interactive form bubble in the chat. Users can fill out form fields and submit responses. + ---- +*** #### Card Message -To send a Card message to a single user or a group, use the `sendCardMessage()` function. This function requires a `CardMessage` object as its argument, which contains the necessary information to create a card bubble for the message. - -#### Usage +As a developer, if you need to send a Card message to a single user or a group, you'll need to utilize the `sendCardMessage()` function. This function requires a `CardMessage` object as its argument, which contains the necessary information to create a card bubble for the messages ```dart -CometChatUIKit.sendCardMessage( - cardMessageObject, - onSuccess: (message) { - // Card message sent successfully - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.sendCardMessage(cardMessageObject, onSuccess: (p0) { + // TODO("Not yet implemented") +}, onError: (p0) { + // TODO("Not yet implemented") +}); ``` + - -> **What this does:** Sends a `CardMessage` that renders as an interactive card bubble in the chat with customizable actions. + ---- +*** #### Scheduler Message -To send a Scheduler message to a single user or a group, use the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object as its argument, which contains the necessary information to create a scheduler bubble for the message. - -#### Usage +As a developer, if you need to send a Scheduler message to a single user or a group, you'll need to utilize the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object as its argument, which contains the necessary information to create a SchedulerMessage bubble for the messages ```dart -CometChatUIKit.sendSchedulerMessage( - schedulerMessageObject, - onSuccess: (message) { - // Scheduler message sent successfully - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.sendSchedulerMessage(schedulerMessageObject, onSuccess: (p0) { + // TODO("Not yet implemented") +}, onError: (p0) { + // TODO("Not yet implemented") +}); ``` + - -> **What this does:** Sends a `SchedulerMessage` that renders as an interactive scheduling bubble in the chat for booking appointments or meetings. + ---- +*** #### Custom Interactive Message -To send a custom interactive message to a single user or a group, use the `sendCustomInteractiveMessage()` function. This function requires an `InteractiveMessage` object as its argument, which contains the necessary information to create a custom interactive message bubble. - -#### Usage +As a developer, if you need to send a Interactive message to a single user or a group, you'll need to utilize the `sendCustomInteractiveMessage()` function. This function requires a `InteractiveMessage` object as its argument, which contains the necessary information to create a custom interactive message bubble for the messages ```dart -CometChatUIKit.sendCustomInteractiveMessage( - interactiveMessageObject, - onSuccess: (message) { - // Custom interactive message sent successfully - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.sendCustomInteractiveMessage(interactiveMessageObject, onSuccess: (p0) { + // TODO("Not yet implemented") +}, onError: (p0) { + // TODO("Not yet implemented") +}); ``` + + -> **What this does:** Sends a custom `InteractiveMessage` that can be rendered with your own custom interactive UI. - ---- +*** ### Reactions #### Add Reaction -You can add a reaction to a message using the `addReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. - -#### Usage +As a developer, you can add a reaction to a message using the `addReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. ```dart -CometChatUIKit.addReaction( - messageId, - "👍", - onSuccess: (message) { - // Reaction added successfully - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.addReaction(messageId, "👍", onSuccess: (message) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); ``` + - -> **What this does:** Adds a reaction emoji to the specified message. The UI Kit automatically updates the Message List and Reactions components to reflect the change. + ---- +*** #### Remove Reaction -You can remove a reaction from a message using the `removeReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. - -#### Usage +As a developer, you can remove a reaction from a message using the `removeReaction()` function. This will update the UI of `CometChatMessageList` and `CometChatReactions` accordingly. ```dart -CometChatUIKit.removeReaction( - messageId, - "👍", - onSuccess: (message) { - // Reaction removed successfully - }, - onError: (e) { - // Handle error - }, -); +CometChatUIKit.removeReaction(messageId, "👍", onSuccess: (message) { + // TODO("Not yet implemented") +}, onError: (e) { + // TODO("Not yet implemented") +}); ``` - - -> **What this does:** Removes a reaction emoji from the specified message. The UI Kit automatically updates the Message List and Reactions components to reflect the change. + ---- + -## Next Steps - - - - Listen and respond to UI Kit events. - - - Set up CometChat Flutter UI Kit. - - - Display and customize chat messages. - - - Manage conversation lists. - - +*** From 5e3d4495eb67281a4bd22c3f4b074a1a070e1dfe Mon Sep 17 00:00:00 2001 From: Swapnil Godambe Date: Mon, 23 Mar 2026 19:13:01 +0530 Subject: [PATCH 106/106] Update upgrading-from-v4.mdx --- ui-kit/flutter/upgrading-from-v4.mdx | 453 ++++++++++++++++++++++++++- 1 file changed, 452 insertions(+), 1 deletion(-) diff --git a/ui-kit/flutter/upgrading-from-v4.mdx b/ui-kit/flutter/upgrading-from-v4.mdx index 201b44f7c..ea2c9de2f 100644 --- a/ui-kit/flutter/upgrading-from-v4.mdx +++ b/ui-kit/flutter/upgrading-from-v4.mdx @@ -135,4 +135,455 @@ Custom view properties have undergone a comprehensive overhaul to ensure consist This consistent naming convention makes it easier for developers to understand and apply customizations across various components, streamlining the development process. -For a comprehensive overview of newly added, renamed, and removed properties, refer to the [Property Changes](/ui-kit/flutter/property-changes) Documentation. \ No newline at end of file +The following sections provide a comprehensive overview of newly added, renamed, and removed properties for each component. + +## Conversations + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| scrollController | ScrollController? | Controller to handle scrolling behavior in the conversations list. | +| datePadding | EdgeInsets? | Provides padding for the date component. | +| dateHeight | double? | Provides height for the date component. | +| dateBackgroundIsTransparent | bool? | Controls the background transparency of the date component. | +| dateWidth | double? | Provides width for the date component. | +| badgeWidth | double? | Provides width for the badge component. | +| badgeHeight | double? | Provides height for the badge component. | +| badgePadding | EdgeInsetsGeometry? | Provides padding for the badge component. | +| statusIndicatorWidth | double? | Provides width for the status indicator. | +| statusIndicatorHeight | double? | Provides height for the status indicator. | +| statusIndicatorBorderRadius | BorderRadiusGeometry? | Provides border radius for the status indicator. | +| avatarMargin | EdgeInsetsGeometry? | Provides margin for the avatar component. | +| avatarPadding | EdgeInsetsGeometry? | Provides padding for the avatar component. | +| avatarWidth | double? | Provides width for the avatar component. | +| avatarHeight | double? | Provides height for the avatar component. | +| deleteConversationOptionVisibility | bool | Controls visibility of delete conversation option (default: true). | +| groupTypeVisibility | bool | Controls visibility of group type icon (default: true). | +| setOptions | Function? | Sets custom options for conversation long press actions. | +| addOptions | Function? | Adds additional options to conversation long press actions. | +| loadingStateView | WidgetBuilder? | Custom widget for loading state view. | +| leadingView | Function? | Custom widget for leading view of conversation items. | +| titleView | Function? | Custom widget for title view of conversation items. | +| controllerTag | String? | Tag for controller management. | +| onLoad | OnLoad< Conversation >? | Callback when conversations are loading. | +| onEmpty | OnEmpty? | Callback when conversation list is empty. | +| submitIcon | Widget? | Custom submit icon for selection mode. | +| dateTimeFormatterCallback | DateTimeFormatterCallback? | Callback for custom date and time formatting. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| conversationsStyle | conversationsStyle | ConversationsStyle → CometChatConversationsStyle | Style configuration (type changed from ConversationsStyle to CometChatConversationsStyle). | +| tailView | trailingView | Function? | Custom widget for trailing view of conversation items (renamed from tailView to trailingView). | +| disableUsersPresence | usersStatusVisibility | bool | Controls user status visibility (inverted logic: disableUsersPresence=false becomes usersStatusVisibility=true). | +| hideReceipt/disableReceipt | receiptsVisibility | bool | Controls receipt visibility (inverted logic: hideReceipt=false becomes receiptsVisibility=true). | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| theme | CometChatTheme? | Theme configuration for the conversations component. | +| errorStateText | String? | Custom text for error state display. | +| emptyStateText | String? | Custom text for empty state display. | +| stateCallBack | Function? | Callback for state changes in the conversations component. | +| loadingStateText | String? | Custom text for loading state display. | +| options | Function? | Options configuration for conversation items. | +| avatarStyle | AvatarStyle? | Style configuration for avatar components. | +| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicators. | +| badgeStyle | BadgeStyle? | Style configuration for badge components. | +| receiptStyle | ReceiptStyle? | Style configuration for receipt indicators. | +| hideSeparator | bool | Controls visibility of separators between conversation items. | +| dateStyle | DateStyle? | Style configuration for date components. | +| disableTyping | bool? | Controls typing indicator functionality. | +| deleteConversationDialogStyle | ConfirmDialogStyle? | Style configuration for delete conversation confirmation dialog. | +| disableMentions | bool? | Controls mention functionality in conversations. | + +## Users + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| scrollController | ScrollController? | Sets controller for scrolling behavior in the users list. | +| height | double? | Provides height to the widget. | +| width | double? | Provides width to the widget. | +| stickyHeaderVisibility | bool | Hide alphabets used to separate users (default: false). | +| searchKeyword | String? | Used to set searchKeyword to fetch initial list with. | +| onLoad | OnLoad< User >? | Callback triggered when list is fetched and loaded. | +| onEmpty | OnEmpty? | Callback triggered when the list is empty. | +| setOptions | Function? | Sets list of actions available on the long press of list item. | +| addOptions | Function? | Adds into the current list of actions available on the long press of list item. | +| trailingView | Widget? Function(BuildContext, User)? | Custom widget for trailing view of each user item. | +| leadingView | Widget? Function(BuildContext, User)? | Custom widget for leading view of each user item. | +| titleView | Widget? Function(BuildContext, User)? | Custom widget for title view of each user item. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| controller | scrollController | ScrollController? | Scroll controller for the list (renamed from controller to scrollController). | +| disableUsersPresence | usersStatusVisibility | bool → bool | Controls user status visibility (inverted logic: disableUsersPresence=false becomes usersStatusVisibility=true). | +| hideSectionSeparator | stickyHeaderVisibility | bool → bool | Controls section separator visibility (inverted logic: hideSectionSeparator=false becomes stickyHeaderVisibility=true). | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| theme | CometChatTheme? | Theme configuration for the users component. | +| errorStateText | String? | Custom text for error state display. | +| emptyStateText | String? | Custom text for empty state display. | +| stateCallBack | Function? | Callback to access controller functions from parent. | +| hideError | bool? | Toggle visibility of error dialog. | +| listItemStyle | ListItemStyle? | Style configuration for individual list items. | +| options | Function? | Options configuration for user items. | +| avatarStyle | AvatarStyle? | Style configuration for avatar components. | +| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicators. | +| hideSeparator | bool? | Toggle visibility of separator between items. | +| hideSectionSeparator | bool? | Toggle visibility of section separators. | +| selectionIcon | Widget? | Custom selection icon widget. | + +## Groups + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| scrollController | ScrollController? | Sets controller for scrolling behavior in the groups list. | +| height | double? | Provides height to the widget. | +| width | double? | Provides width to the widget. | +| searchKeyword | String? | Used to set searchKeyword to fetch initial list with. | +| onLoad | OnLoad< Group >? | Callback triggered when list is fetched and loaded. | +| onEmpty | OnEmpty? | Callback triggered when the list is empty. | +| groupTypeVisibility | bool | Hide the group type icon which is visible on the group icon (default: true). | +| setOptions | Function? | Sets list of actions available on the long press of list item. | +| addOptions | Function? | Adds into the current list of actions available on the long press of list item. | +| trailingView | Widget? Function(BuildContext, Group)? | Custom widget for trailing view of each group item. | +| leadingView | Widget? Function(BuildContext, Group)? | Custom widget for leading view of each group item. | +| titleView | Widget? Function(BuildContext, Group)? | Custom widget for title view of each group item. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| controller | scrollController | ScrollController? | Scroll controller for the list (renamed from controller to scrollController). | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| theme | CometChatTheme? | Theme configuration for the groups component. | +| errorStateText | String? | Custom text for error state display. | +| emptyStateText | String? | Custom text for empty state display. | +| listItemStyle | ListItemStyle? | Style configuration for individual list items. | +| options | Function? | Options configuration for group items. | +| avatarStyle | AvatarStyle? | Style configuration for avatar components. | +| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicators. | +| hideSeparator | bool | Toggle visibility of separator between items. | +| selectionIcon | Widget? | Custom selection icon widget. | + +## Group Members + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| height | double? | Provides height to the widget. | +| width | double? | Provides width to the widget. | +| controllerTag | String? | Tag to access the widget's GetXController. | +| searchKeyword | String? | Used to set searchKeyword to fetch initial list with. | +| onLoad | OnLoad< GroupMember >? | Callback triggered when list is fetched and loaded. | +| onEmpty | OnEmpty? | Callback triggered when the list is empty. | +| leadingView | Widget? Function(BuildContext, GroupMember)? | Custom widget for leading view of each group member item. | +| titleView | Widget? Function(BuildContext, GroupMember)? | Custom widget for title view of each group member item. | +| usersStatusVisibility | bool | Hide status indicator of user which is visible on user avatar (default: true). | +| hideKickMemberOption | bool? | Defines whether a member can be kicked or not. | +| hideBanMemberOption | bool? | Defines whether a member can be banned or not. | +| hideScopeChangeOption | bool? | Defines whether a member's scope can be changed or not. | +| setOptions | Function? | Sets list of actions available on the long press of list item. | +| addOptions | Function? | Adds into the current list of actions available on the long press of list item. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| groupMemberStyle | style | GroupMembersStyle → CometChatGroupMembersStyle | Style configuration (type changed from GroupMembersStyle to CometChatGroupMembersStyle). | +| tailView | trailingView | Function → Function | Custom widget for trailing view (renamed from tailView to trailingView). | +| disableUsersPresence | usersStatusVisibility | bool → bool | Controls user status visibility (inverted logic: disableUsersPresence=false becomes usersStatusVisibility=true). | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| theme | CometChatTheme? | Theme configuration for the group members component. | +| title | String? | Sets title for the list. | +| errorStateText | String? | Text to be displayed when error occurs. | +| emptyStateText | String? | Text to be displayed when the list is empty. | +| listItemStyle | ListItemStyle? | Style configuration for individual list items. | +| avatarStyle | AvatarStyle? | Style configuration for avatar components. | +| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicator. | +| groupScopeStyle | GroupScopeStyle? | Styling properties for group scope (integrated into main style). | + +## Message Header + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| trailingView | List< Widget >? Function(User?, Group?, BuildContext)? | Custom widgets for trailing view in the message header. | +| height | double? | Sets height for the message header component. | +| padding | EdgeInsetsGeometry? | Sets padding for the message header component. | +| hideVideoCallButton | bool? | Controls visibility of video call button in the header. | +| hideVoiceCallButton | bool? | Controls visibility of voice call button in the header. | +| titleView | Widget? Function(Group?, User?, BuildContext)? | Custom widget for title view in the message header. | +| leadingStateView | Widget? Function(Group?, User?, BuildContext)? | Custom widget for leading state view in the message header. | +| auxiliaryButtonView | Widget? Function(Group?, User?, BuildContext)? | Custom widget for auxiliary button view in the message header. | +| usersStatusVisibility | bool | Controls visibility of user status indicator (default: true). | +| dateTimeFormatterCallback | DateTimeFormatterCallback? | Callback for custom date and time formatting. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| hideBackButton | showBackButton | bool → bool | Controls back button visibility (inverted logic: hideBackButton=false becomes showBackButton=true). | +| disableUserPresence | usersStatusVisibility | bool → bool | Controls user presence visibility (inverted logic: disableUserPresence=false becomes usersStatusVisibility=true). | +| appBarOptions | trailingView | Function → Function | Custom widgets for header options (renamed from appBarOptions to trailingView). | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| theme | CometChatTheme? | Theme configuration for the message header component. | +| avatarStyle | AvatarStyle? | Style configuration for avatar in the header. | +| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicator in the header. | +| privateGroupIcon | Widget? | Custom icon for private groups in the header. | +| protectedGroupIcon | Widget? | Custom icon for protected groups in the header. | +| disableTyping | bool | Controls typing indicator functionality in the header. | + +## Message List + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| style | CometChatMessageListStyle? | Sets style for message list (replaces messageListStyle). | +| receiptsVisibility | bool | Controls visibility of read receipts (default: true). | +| avatarVisibility | bool | Toggle visibility for avatar (default: true, renamed from showAvatar). | +| padding | EdgeInsetsGeometry? | Sets padding for the message list. | +| margin | EdgeInsetsGeometry? | Sets margin for the message list. | +| width | double? | Sets width for the message list. | +| height | double? | Sets height for the message list. | +| reactionsRequestBuilder | ReactionsRequestBuilder? | Used to fetch the reactions of a particular message. | +| onLoad | OnLoad< BaseMessage >? | Callback triggered when list is fetched and loaded. | +| onEmpty | OnEmpty? | Callback triggered when the list is empty. | +| onReactionClick | Function(String?, BaseMessage)? | Override the click of a reaction pill. | +| onReactionLongPress | Function(String?, BaseMessage)? | Override when user long presses on a reaction pill. | +| onReactionListItemClick | Function(String?, BaseMessage?)? | Override when a reaction list item is clicked. | +| hideStickyDate | bool | Hide the sticky date separator. | +| hideReplyInThreadOption | bool | Defines whether Reply In Thread option should be visible. | +| hideTranslateMessageOption | bool | Defines whether Translate Message option should be visible. | +| hideEditMessageOption | bool | Defines whether Edit Message option should be visible. | +| hideDeleteMessageOption | bool | Defines whether Delete Message option should be visible. | +| hideReactionOption | bool | Defines whether Reaction option should be visible. | +| hideMessagePrivatelyOption | bool | Defines whether Message Privately option should be visible. | +| hideCopyMessageOption | bool | Defines whether Copy Message option should be visible. | +| hideMessageInfoOption | bool | Defines whether Message Info option should be visible. | +| hideGroupActionMessages | bool | Defines whether action messages in groups should be visible. | +| enableConversationStarters | bool | Controls conversation starter generation in new conversations. | +| enableSmartReplies | bool | Controls smart replies generation in chat. | +| hideShareMessageOption | bool | Defines whether Share Message option should be visible. | +| smartRepliesDelayDuration | int | Milliseconds delay after which Smart Replies are triggered. | +| smartRepliesKeywords | List< String > | Keywords that trigger Smart Replies. | +| addTemplate | List< CometChatMessageTemplate >? | Add custom message templates to existing templates. | +| dateTimeFormatterCallback | DateTimeFormatterCallback? | Callback for custom date and time formatting. | +| hideModerationView | bool | Defines whether moderation view should be hidden. | +| hideDateSeparator | bool | Hide the date separator (default: false). | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| messageListStyle | style | MessageListStyle → CometChatMessageListStyle | Style configuration (type changed). | +| controller | scrollController | ScrollController? | Scroll controller for the list. | +| showAvatar | avatarVisibility | bool → bool | Toggle visibility for avatar. | +| disableReceipt/hideReceipt | receiptsVisibility | bool → bool | Controls receipt visibility (inverted logic). | +| addReactionIconTap | addMoreReactionTap | Function → Function | Callback for adding more reactions. | +| dateSeparatorPattern | dateSeparatorPattern | Function(DateTime) → Function(DateTime) | Signature clarified with parameter name. | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| hideError | bool? | Toggle visibility of error dialog. | +| theme | CometChatTheme? | Theme configuration for the message list. | +| avatarStyle | AvatarStyle? | Style configuration for avatar (integrated into main style). | +| scrollToBottomOnNewMessages | bool? | Auto-scroll to bottom on new messages. | +| newMessageIndicatorText | String? | Custom text for new message indicator. | +| timestampAlignment | TimeAlignment | Alignment for message timestamps. | +| messageInformationConfiguration | MessageInformationConfiguration? | Configuration for message information. | +| reactionListConfiguration | ReactionListConfiguration? | Configuration for reaction list. | +| reactionsConfiguration | ReactionsConfiguration? | Configuration for reactions. | +| reactionsStyle | ReactionsStyle? | Style configuration for reactions. | +| emojiKeyboardStyle | EmojiKeyboardStyle? | Style configuration for emoji keyboard. | +| disableReceipt | bool? | (Deprecated) Controls visibility of read receipts. | +| hideReceipt | bool? | Controls visibility of read receipts (replaced by receiptsVisibility). | + +## Message Composer + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| padding | EdgeInsetsGeometry? | Provides padding to the message composer. | +| messageInputPadding | EdgeInsetsGeometry? | Sets the padding to the message input field. | +| recorderStartButtonIcon | Widget? | Defines the icon of the start button for voice recording. | +| recorderPauseButtonIcon | Widget? | Defines the icon of the pause button for voice recording. | +| recorderDeleteButtonIcon | Widget? | Defines the icon of the delete button for voice recording. | +| recorderStopButtonIcon | Widget? | Defines the icon of the stop button for voice recording. | +| recorderSendButtonIcon | Widget? | Defines the icon of the send button for voice recording. | +| hideSendButton | bool? | Controls visibility of send button. | +| hideAttachmentButton | bool? | Controls visibility of attachment button. | +| hideStickersButton | bool? | Controls visibility of sticker button. | +| hideImageAttachmentOption | bool? | Controls visibility of image attachment option. | +| hideVideoAttachmentOption | bool? | Controls visibility of video attachment option. | +| hideAudioAttachmentOption | bool? | Controls visibility of audio attachment option. | +| hideFileAttachmentOption | bool? | Controls visibility of file attachment option. | +| hidePollsOption | bool? | Controls visibility of poll option. | +| hideCollaborativeDocumentOption | bool? | Controls visibility of collaborative document option. | +| hideCollaborativeWhiteboardOption | bool? | Controls visibility of collaborative whiteboard option. | +| hideTakePhotoOption | bool? | Controls visibility of take photo option. | +| sendButtonIcon | Widget? | Custom send button icon. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| hideVoiceRecording | hideVoiceRecordingButton | bool? → bool? | Renamed for clarity (hideVoiceRecording to hideVoiceRecordingButton). | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| theme | CometChatTheme? | Theme configuration for the message composer. | +| hideLiveReaction | bool | Controls live reaction functionality (feature removed). | +| liveReactionIcon | Widget? | Custom live reaction icon (feature removed). | +| liveReactionIconURL | String? | Path for live reaction icon (feature removed). | +| recordIcon | Widget? | Icon for recording start (replaced by recorderStartButtonIcon). | +| playIcon | Widget? | Icon for playing recording (integrated into recorder). | +| deleteIcon | Widget? | Icon for deleting recording (replaced by recorderDeleteButtonIcon). | +| stopIcon | Widget? | Icon for stopping recording (replaced by recorderStopButtonIcon). | +| submitIcon | Widget? | Icon for submitting recording (replaced by recorderSendButtonIcon). | +| pauseIcon | Widget? | Icon for pausing recording (replaced by recorderPauseButtonIcon). | +| mediaRecorderStyle | MediaRecorderStyle? | Style for media recorder (integrated into main style). | + +## Incoming Call + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| callSettingsBuilder | CallSettingsBuilder? | Used to set the call settings for the incoming call. | +| height | double? | Sets the height of the incoming call widget. | +| width | double? | Sets the width of the incoming call widget. | +| callIcon | Widget? | Custom call icon for the incoming call display. | +| titleView | Widget? Function(BuildContext, Call)? | Custom widget for title view in the incoming call. | +| subTitleView | Widget? Function(BuildContext, Call)? | Custom widget for subtitle view in the incoming call. | +| leadingView | Widget? Function(BuildContext, Call)? | Custom widget for leading view in the incoming call. | +| itemView | Widget? Function(BuildContext, Call)? | Custom widget for complete item view in the incoming call. | +| trailingView | Widget? Function(BuildContext, Call)? | Custom widget for trailing view in the incoming call. | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| theme | CometChatTheme? | Theme configuration for the incoming call component. | +| subtitle | String? | Custom subtitle text (replaced by subTitleView function). | +| declineButtonIconUrl | String? | Custom decline button icon URL. | +| declineButtonIconUrlPackage | String? | Package name for decline button icon. | +| cardStyle | CardStyle? | Style configuration for the card layout. | +| declineButtonStyle | ButtonStyle? | Style configuration for decline button. | +| acceptButtonIconUrl | String? | Custom accept button icon URL. | +| acceptButtonIconUrlPackage | String? | Package name for accept button icon. | +| acceptButtonStyle | ButtonStyle? | Style configuration for accept button. | +| avatarStyle | AvatarStyle? | Style configuration for avatar (integrated into main style). | +| ongoingCallConfiguration | OngoingCallConfiguration? | Configuration for ongoing call settings. | + +## Outgoing Call + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| callSettingsBuilder | CallSettingsBuilder? | Used to set the call settings for the outgoing call. | +| height | double? | Sets the height of the outgoing call widget. | +| width | double? | Sets the width of the outgoing call widget. | +| avatarView | Widget? Function(BuildContext, Call)? | Custom widget for avatar view in the outgoing call. | +| titleView | Widget? Function(BuildContext, Call)? | Custom widget for title view in the outgoing call. | +| cancelledView | Widget? Function(BuildContext, Call)? | Custom widget for cancelled/decline button view in the outgoing call. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| subtitle | subtitleView | String? → Widget? Function(BuildContext, Call)? | Subtitle changed from static text to custom widget function. | +| declineButtonIconUrl | declineButtonIcon | String? → Widget? | Decline button icon changed from URL-based to Widget-based. | +| onDecline | onCancelled | Function(BuildContext, Call)? → Function(BuildContext, Call)? | Callback renamed from onDecline to onCancelled for clarity. | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| theme | CometChatTheme? | Theme configuration for the outgoing call component. | +| subtitle | String? | Custom subtitle text (replaced by subtitleView function). | +| declineButtonText | String? | Custom decline button text. | +| declineButtonIconUrl | String? | Custom decline button icon URL (replaced by declineButtonIcon widget). | +| declineButtonIconUrlPackage | String? | Package name for decline button icon. | +| cardStyle | CardStyle? | Style configuration for the card layout. | +| buttonStyle | ButtonStyle? | Style configuration for decline button. | +| avatarStyle | AvatarStyle? | Style configuration for avatar (integrated into main style). | +| ongoingCallConfiguration | OngoingCallConfiguration? | Configuration for ongoing call settings. | + +## Call Buttons + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| callSettingsBuilder | CallSettingsBuilder Function(User?, Group?, bool?)? | Used to configure the meet settings builder for call initialization. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| hideVoiceCall | hideVoiceCallButton | bool? → bool? | Renamed for clarity (hideVoiceCall to hideVoiceCallButton). | +| hideVideoCall | hideVideoCallButton | bool? → bool? | Renamed for clarity (hideVideoCall to hideVideoCallButton). | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| voiceCallIconText | String? | Text label for the voice call icon. | +| voiceCallIconHoverText | String? | Hover text for the voice call icon. | +| videoCallIconText | String? | Text label for the video call icon. | +| videoCallIconHoverText | String? | Hover text for the video call icon. | +| onVoiceCallClick | Function(BuildContext, User?, Group?)? | Custom callback for voice call button click. | +| onVideoCallClick | Function(BuildContext, User?, Group?)? | Custom callback for video call button click. | +| ongoingCallConfiguration | OngoingCallConfiguration? | Configuration for ongoing call settings. | + +## Call Logs + +### New Properties +| Name | Type | Description | +| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | +| hideAppbar | bool | Toggle visibility for app bar (default: false). | +| appBarOptions | List< Widget >? | List of options to be visible in app bar. | +| onCallLogIconClicked | Function(CallLog)? | Callback triggered on clicking of the call log icon (audio/video icon). | +| onItemLongPress | Function(CallLog)? | Callback triggered on long pressing of the call log item. | +| onLoad | OnLoad< CallLog >? | Callback triggered when list is fetched and loaded. | +| onEmpty | OnEmpty? | Callback triggered when the list is empty. | +| setOptions | Function? | Sets list of actions available on the long press of list item. | +| addOptions | Function? | Adds into the current list of actions available on the long press of list item. | +| leadingStateView | Widget? Function(BuildContext, CallLog)? | Custom widget for leading view of each call log item. | +| titleView | Widget? Function(BuildContext, CallLog)? | Custom widget for title view of each call log item. | +| audioCallIcon | Widget? | Custom audio call icon. | +| videoCallIcon | Widget? | Custom video call icon. | +| incomingCallIcon | Widget? | Custom incoming call icon. | +| outgoingCallIcon | Widget? | Custom outgoing call icon. | +| missedCallIcon | Widget? | Custom missed call icon. | + +### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| tailView | trailingView | Function → Function | Custom widget for trailing view (renamed from tailView to trailingView). | + +### Removed Properties +| Name | Type | Description | +| ----------- | ------------ | ---------------------------------------------------------------------------------- | +| title | String? | Title of the call log list component. | +| emptyStateText | String? | Text to be displayed when the state is empty. | +| errorStateText | String? | Text to be displayed when error occurs. | +| loadingIconUrl | String? | URL to be displayed when loading. | +| avatarStyle | AvatarStyle? | Style configuration for avatar (integrated into main style). | +| theme | CometChatTheme? | Theme configuration for the call logs component. | +| hideSeparator | bool? | Toggle visibility of separator. | +| onInfoIconClick | Function(CallLog)? | Callback triggered on clicking of the info icon. | +| infoIconUrl | String? | Custom info icon URL. | +| listItemStyle | ListItemStyle? | Style configuration for individual list items. | +| incomingAudioCallIcon | String? | Custom incoming audio call icon URL (replaced by incomingCallIcon widget). | +| incomingVideoCallIcon | String? | Custom incoming video call icon URL (replaced by incomingCallIcon widget). | +| outgoingAudioCallIcon | String? | Custom outgoing audio call icon URL (replaced by outgoingCallIcon widget). | +| outgoingVideoCallIcon | String? | Custom outgoing video call icon URL (replaced by outgoingCallIcon widget). | +| missedAudioCallIcon | String? | Custom missed audio call icon URL (replaced by missedCallIcon widget). | +| missedVideoCallIcon | String? | Custom missed video call icon URL (replaced by missedCallIcon widget). | \ No newline at end of file