For AI agents: Find a documentation index at https://talkjs.com/llms.txt (full content at https://talkjs.com/llms-full.txt). Get a markdown version of any page by appending .md to its URL path.

Chatbox

Display a single conversation.

View as Markdown

The Chatbox component represents a chatbox UI for a single conversation, and integrates with the user's TalkJS session.

Chatbox

fun Chatbox(appId, userId, conversationId, chatHeaderVisible, enterSendsMessage, focusedMessageId, messageFieldPlaceholder, messageFieldSpellcheck, messageFieldVisible, token, baseTheme, themePath, themeCustom, customCssPath, onSendMessage, onBackButtonClick, onDeleteMessage, onFocusMessage, onMessageAction, beforePermissionPrompt, onMissingPermission, modifier, key, controller)

The TalkJS Chatbox UI. Displays a single conversation.

Parameters

appId
: String

Your app's unique TalkJS ID. You can find it on the Settings page of the TalkJS dashboard.

userId
: String

The ID of the current user.

If the given user ID doesn't exist, a "Something went wrong" message will be displayed.

conversationId (optional)
: String?

The ID of the conversation to display.

If the conversation doesn't exist or if the current user isn't a participant of the current conversation, a "Conversation not found" message will be displayed (after a timeout). If you create the conversation in parallel (eg via the REST API or via the Data API), it will show in the chatbox automatically. This means that you can safely point a chatbox at a conversation that might not yet exist. This way the chatbox UI and the conversation can load in parallel, which results in snappier UX.

Passing null deselects the current conversation and shows an empty panel. This may be useful for Inbox-like scenarios where you want to keep the chatbox loaded, without showing a conversation.

In the background, the Chatbox keeps active subscriptions to recent conversations, so that switching back and forth between conversations has snappy UX.

chatHeaderVisible (optional)
: Boolean?

Sets whether the chat header is visible.

Defaults to true.

enterSendsMessage (optional)
: Boolean?

When true, pressing Enter will send a message.

Defaults to true.

focusedMessageId (optional)
: String?

The ID of the currently focused message.

Whenever this value changes to a valid message ID, the relevant message will be scrolled into view.

Also update your local focusedMessageId state in onFocusMessage so that it stays in sync with the UI's internals.

Note that updating the selected conversation through this parameter will not trigger the onFocusMessage callback.

messageFieldPlaceholder (optional)
: String?

Adds custom placeholder text for the message input field.

The default placeholder text is "Say something..."

messageFieldSpellcheck (optional)
: Boolean?

Sets whether spellcheck is enabled in the message field.

Defaults to false.

messageFieldVisible (optional)
: Boolean?

Sets whether the message input field is visible.

Defaults to true.

token (optional)
: String?

A token to authenticate the session with.

See the Authentication guide and Token reference for details and examples.

Required when authentication is enabled, otherwise optional.

baseTheme (optional)
: BaseTheme?

The base theme to start from.

Defaults to DEFAULT.

themePath (optional)
: String?

Path to a custom theme file, relative to the app's assets folder.

themeCustom (optional)
: JsonElement?

Arbitrary custom data passed down to the theme.

Whatever data you pass here will be made available for use in the theme module loaded via themePath.

customCssPath (optional)
: String?

Path to a custom CSS file, relative to the app's assets folder.

onSendMessage (optional)
: ((event: SendMessageEvent) -> Unit)?

Callback that triggers when the user sends a message with the TalkJS UI.

event is the event object describing the message sending action.

onBackButtonClick (optional)
: ((event: BackButtonClickEvent) -> Unit)?

Fired when the back button in the chat header is clicked.

By default this back button is only shown inside an inbox on small screens. You can change this behavior in the ChatHeader theme.

onDeleteMessage (optional)
: ((event: DeleteMessageEvent) -> Unit)?

Callback that triggers when the user deletes a message with the TalkJS UI.

event is the event object describing the message deletion.

onFocusMessage (optional)
: ((event: FocusMessageEvent) -> Unit)?

Callback that triggers when a message is focused or unfocused.

event is the event object describing the message focus action.

Note that updating the focused message through the focusedMessageId parameter will not trigger this callback.

onMessageAction (optional)
: ((event: MessageActionEvent) -> Unit)?

This event fires when the user clicks an action button or an action Link inside a message.

The event's action and params fields specify the name of action and its parameters, if any.

See Action Buttons and Links for more info.

beforePermissionPrompt (optional)
: (suspend (request: PermissionPromptRequest) -> Unit)?

Callback that triggers when the user initiates an action that will require a permissions request from the system, but right before actually requesting the permission from the system.

You can use this callback to inform the user that they will need to grant a system permission in order to perform an action.

request is an object describing the permission request.

onMissingPermission (optional)
: ((event: MissingPermissionEvent) -> Unit)?

Callback that triggers when the user attempts to initiate an action that requires a specific system permission, but that permission was not granted.

event is the event object describing the missing permission.

modifier
: Modifier
key (optional)
: String?
controller
: ChatboxController

A reference to the ChatboxController.

Returns

Unit

rememberChatboxController

fun rememberChatboxController(): ChatboxController

Returns

ChatboxController

class ChatboxController

A collection of actions available on the Chatbox UI.

Method Overview

constructor
clickBackButton

Emits the onBackButtonClick callback of Chatbox.

deleteMessage

Deletes the message with the given ID.

editMessage

Edit the message with the given ID.

focusMessage

Scrolls to the message with the given messageId and marks it as "focused".

If null is passed the focusedMessage will be cleared.

focusMessageField

Focus the message field. If it is not mounted yet, it will be focused once the selected conversation has rendered it.

getMessageFieldText

Get the plaintext from the message field

jumpToNextHighlight

Searches for messages downwards that contains highlighted strings. If a message is found, the UI will scroll that message into view.

Strings are highlighted when you explicitly call setHighlightedStrings or when a user types a word/phrase into the ChatSearchBox.

jumpToPreviousHighlight

Searches for a message upwards that contains highlighted strings. If a message is found, the UI will scroll that message into view.

Strings are highlighted when you explicitly call setHighlightedStrings or when a user types a word/phrase into the ChatSearchBox.

sendFileMessage

Send a file message to the current conversation.

sendLocationMessage

Send a location message to the current conversation.

sendMessage

Send a text message to the current conversation.

setEditing

Enable/disable editing of a given message.

setHighlightedStrings

Highlights certain strings in messages

setMessageFieldText

Set the plaintext in the message field

setReferencedMessage

Set/unset the message that's currently being replied to.

setSearchQuery

Sets the query used by the in-conversation search UI.

toggleReaction

Toggle the given emoji reaction for the given message. If the current user already added this reaction, it's removed, and otherwise, it's added.

Called from the theme's Message component when the user clicks on an existing emoji reaction.

toggleSearchBox

Toggles whether the ChatSearchBox should be visible or not.

constructor

ChatboxController()

clickBackButton

suspend fun chatboxController.clickBackButton()

Emits the onBackButtonClick callback of Chatbox.

Called from the default ChatHeader theme component for the "back" button which is shown when the chatbox is part of an inbox that's being rendered in mobile mode.

Returns

Unit

deleteMessage

suspend fun chatboxController.deleteMessage(messageId)

Deletes the message with the given ID.

Parameters

messageId
: String

Returns

Unit

editMessage

suspend fun chatboxController.editMessage(messageId, text, custom)
suspend fun chatboxController.editMessage(messageId, content, custom)

Edit the message with the given ID.

Parameters

messageId
: String
text (optional)
: String?
custom (optional)
: Map<String, String?>?
content
: List<SendContentBlock>

Returns

Unit

focusMessage

suspend fun chatboxController.focusMessage(messageId): MessageSnapshot?

Scrolls to the message with the given messageId and marks it as "focused".

If null is passed the focusedMessage will be cleared.

Parameters

messageId (optional)
: String?

Returns

MessageSnapshot?

The message snapshot if a message with the given ID was found and was scrolled to, or null otherwise.

focusMessageField

suspend fun chatboxController.focusMessageField()

Focus the message field. If it is not mounted yet, it will be focused once the selected conversation has rendered it.

Returns

Unit

getMessageFieldText

suspend fun chatboxController.getMessageFieldText(): String

Get the plaintext from the message field

Returns

String

The text

jumpToNextHighlight

suspend fun chatboxController.jumpToNextHighlight(): MessageSnapshot?

Searches for messages downwards that contains highlighted strings. If a message is found, the UI will scroll that message into view.

Strings are highlighted when you explicitly call setHighlightedStrings or when a user types a word/phrase into the ChatSearchBox.

Returns

MessageSnapshot?

The message snapshot if a message was found, or null otherwise.

jumpToPreviousHighlight

suspend fun chatboxController.jumpToPreviousHighlight(): MessageSnapshot?

Searches for a message upwards that contains highlighted strings. If a message is found, the UI will scroll that message into view.

Strings are highlighted when you explicitly call setHighlightedStrings or when a user types a word/phrase into the ChatSearchBox.

Returns

MessageSnapshot?

The message snapshot if a message was found, or null otherwise.

sendFileMessage

suspend fun chatboxController.sendFileMessage(fileToken, custom)

Send a file message to the current conversation.

Parameters

fileToken
: FileToken
custom (optional)
: Map<String, String>?

Returns

Unit

sendLocationMessage

suspend fun chatboxController.sendLocationMessage(location, custom)

Send a location message to the current conversation.

Parameters

location
: Coordinates
custom (optional)
: Map<String, String>?

Returns

Unit

sendMessage

suspend fun chatboxController.sendMessage(text, custom, referencedMessage)
suspend fun chatboxController.sendMessage(content, custom, referencedMessage)

Send a text message to the current conversation.

Parameters

text
: String
custom (optional)
: Map<String, String>?
referencedMessage (optional)
: String?
content
: List<SendContentBlock>

Returns

Unit

setEditing

suspend fun chatboxController.setEditing(messageId)

Enable/disable editing of a given message.

Parameters

messageId (optional)
: String?

When null is provided, editing mode will be disabled

Returns

Unit

setHighlightedStrings

suspend fun chatboxController.setHighlightedStrings(words)

Highlights certain strings in messages

The TalkJS search feature includes the ability to highlight certain strings in messages. Call this method to highlight certain strings without having the user invoke the search feature. Call again with an empty array to disable highlighting.

Note: like the search feature, this option only works on the Growth plan and up.

Parameters

words
: List<String>

Returns

Unit

setMessageFieldText

suspend fun chatboxController.setMessageFieldText(text)

Set the plaintext in the message field

Parameters

text
: String

Returns

Unit

setReferencedMessage

suspend fun chatboxController.setReferencedMessage(messageId)

Set/unset the message that's currently being replied to.

Parameters

messageId (optional)
: String?

When null is provided, the "replying to" message is cleared

Returns

Unit

setSearchQuery

suspend fun chatboxController.setSearchQuery(query)

Sets the query used by the in-conversation search UI.

This updates the search box value and highlighted strings at the same time.

Parameters

query
: String

Returns

Unit

toggleReaction

suspend fun chatboxController.toggleReaction(messageId, emoji, force)

Toggle the given emoji reaction for the given message. If the current user already added this reaction, it's removed, and otherwise, it's added.

Called from the theme's Message component when the user clicks on an existing emoji reaction.

Parameters

messageId
: String

The ID of the message you want to toggle the reaction on. This message must exist in the current conversation.

emoji
: String

The emoji you want to toggle. Must be a string of a single unicode emoji glyph, eg "🎉".

force (optional)
: Boolean?

If included, turns the toggle into a one way-only operation. Setting to true will add this reaction for the current user and setting to false will remove it if it was already added for the current user

Returns

Unit

toggleSearchBox

suspend fun chatboxController.toggleSearchBox(force)

Toggles whether the ChatSearchBox should be visible or not.

Parameters

force (optional)
: Boolean?

If included, turns the toggle into a one way-only operation. Setting to true will enable the search box, and setting to false will disable it.

Returns

Unit

Examples

The following gives some examples of how to use the Chatbox component.

Create a chatbox with an existing user and conversation

Create a chatbox and pass it an existing user and conversation:

Chatbox(
    appId = "<APP_ID>",
    userId = "sample_user_alice",
    conversationId = "sample_conversation",
)

Create a chatbox with a new user and conversation

The Kotlin Data API, which lets you read, subscribe to, and update your chat data, is included with Android Components.

Import getTalkSession into the file where you want to use it:

import com.talkjs.core.getTalkSession

Then create the session, user, and conversation:

class ChatViewModel : ViewModel() {
    val appId = "<APP_ID>"
    val userId = "sebastian"
    val conversationId = "my_conversation"

    init {
        val session = getTalkSession(appId = appId, userId = userId)

        viewModelScope.launch {
            session.currentUser.createIfNotExists(name = "Sebastian")
            session.conversation(conversationId).createIfNotExists()
        }
    }
}

Pass the new user and conversation to your chatbox:

val viewModel = viewModel<ChatViewModel>()

Chatbox(
    appId = viewModel.appId,
    userId = viewModel.userId,
    conversationId = viewModel.conversationId,
)

Hide the chat header

Hide the chat header:

Chatbox(
    appId = "<APP_ID>",
    userId = "sample_user_alice",
    conversationId = "sample_conversation",
    chatHeaderVisible = false,
)

If you hide the chat header, other UI elements remain visible by default.

Respond to events

Respond to a sent message event by printing details to the log:

Chatbox(
    appId = "<APP_ID>",
    userId = "sample_user_alice",
    conversationId = "sample_conversation",
    onSendMessage = { event ->
        Log.d("Chat", "Message sent: ${event.message}")
    },
)