> For the complete documentation index, see [llms.txt](https://docs.avonnicomponents.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.avonnicomponents.com/lwc-components/data-driven-components/chat.md).

# Chat

`avonni-dd-chat`

The Avonni Data Driven Chat displays records as chat messages.

## Overview

**Chat** is a data-driven Lightning Web Component that displays records as a stream of chat messages, with sent and received bubbles, participant avatars, dates, and an optional message publisher.

It runs in two modes. In **query mode** you set a `query` object and a `mapping` object: each record becomes a message, with its fields mapped to message properties using the `{{Record.FieldApiName}}` syntax, and participants resolved from the mapping. In **static mode** you set the `items` array directly (with a matching `resources` array for participant labels and avatars) and the component ignores `query` and `mapping`.

### Use Cases

* **Record conversations:** Show a threaded discussion stored in a custom `Message__c` object, filtered to one parent record.
* **Case feeds:** Render customer and agent messages as an inbound/outbound chat.
* **Activity timelines:** Present chronological notes as chat bubbles with participant avatars.
* **Live updating chats:** Refresh the conversation automatically when a platform event fires via `refresh-emp`.
* **Static transcripts:** Display a fixed set of messages with no data source for demos or previews.
* **Message composition:** Let users post new messages through the built-in publisher and handle them with the `publish` event.

***

## Use Case Examples

### Example 1: Query mode

**Scenario:** Show all messages for one account, stored in a custom `Message__c` object, ordered by creation date, refreshing live when new messages arrive.

```html
<!-- accountChat.html -->
<template>
    <avonni-dd-chat
        query={messageQuery}
        mapping={messageMapping}
        publisher={publisher}
        refresh-emp={refreshEmp}
        onpublish={handlePublish}
    ></avonni-dd-chat>
</template>
```

```js
// accountChat.js
import { LightningElement } from 'lwc';

export default class AccountChat extends LightningElement {
    messageQuery = {
        objectApiName: 'Message__c',
        filter: "AccountId__c = '001Sv00000WEgVEIA1'"
    };

    messageMapping = {
        date: '{{Record.CreatedDate}}',
        name: '{{Record.Id}}',
        participantName: '{{Record.CreatedById}}',
        participantMapping: {
            label: '{{Record.Name}}',
            name: '{{Record.Id}}',
            avatarFallbackIconName: 'standard:user'
        },
        value: '{{Record.avonni__Value__c}}'
    };

    publisher = { mode: 'rich', placeholder: 'Write a message…' };

    refreshEmp = { channelName: 'yournamespace__New_Message__e' };

    handlePublish(event) {
        const { value, participantName, mentions } = event.detail;
        // Insert a new Message__c record here.
    }
}
```

**Result:** A live chat of the account's messages, ordered by `CreatedDate`, with participant avatars resolved from the mapping and a publisher for new messages.

### Example 2: Static mode

**Scenario:** Display a fixed two-person transcript with no data source, marking "john" as the current participant so his messages render as sent.

```html
<!-- transcript.html -->
<template>
    <avonni-dd-chat
        current-participant-name={currentParticipantName}
        items={items}
        resources={resources}
        publisher={publisher}
        onpublish={handlePublish}
    ></avonni-dd-chat>
</template>
```

```js
// transcript.js
import { LightningElement } from 'lwc';

export default class Transcript extends LightningElement {
    currentParticipantName = 'john';

    resources = [
        { name: 'john', label: 'John Doe', avatarFallbackIconName: 'standard:user', avatarInitials: 'JD' },
        { name: 'jane', label: 'Jane Smith', avatarFallbackIconName: 'standard:user', avatarInitials: 'JS' }
    ];

    items = [
        { name: 'message-1', date: '2025-10-16T14:30:00.000Z', resourceName: 'jane', value: 'Did you review the proposal?' },
        { name: 'message-2', date: '2025-10-16T14:31:00.000Z', resourceName: 'john', value: 'Yes, it looks great.' }
    ];

    publisher = { mode: 'rich', placeholder: 'Write a message…', publishButtonLabel: 'Send' };

    handlePublish(event) {
        const { date, participantName, value } = event.detail;
        this.items = [
            ...this.items,
            { name: `message-${this.items.length + 1}`, date, resourceName: participantName, value }
        ];
    }
}
```

**Result:** A static two-person chat; John's messages appear as outbound (sent) and Jane's as inbound (received), with avatars resolved from `resources`. New messages are appended on `publish`.

***

## Specifications

### Attributes

| Name                       | Description                                                                                                                                                                                                                                                                                  | Type                | Default                                         | Required |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | ----------------------------------------------- | -------- |
| `current-participant-name` | Unique name of the current participant. If the messages have no type set, it is used to determine whether they are sent or received. If empty, it defaults to the current user ID.                                                                                                           | String              | `"Current user ID"`                             |          |
| `disabled`                 | If present, the chat is disabled and it is not possible to interact with it.                                                                                                                                                                                                                 | Boolean             | `false`                                         |          |
| `item-date-format`         | Object defining the date format of the chat messages.                                                                                                                                                                                                                                        | DdChatDateFormat    | —                                               |          |
| `items`                    | Array of static messages displayed in the chat. When this property is set, the chat ignores the `query` and `mapping` properties and displays the messages directly. Use the `resources` property to provide the participant labels and avatars referenced by each message's `resourceName`. | DdChatItem\[]       | —                                               |          |
| `mapping`                  | Object defining the way the records returned by the query are mapped to the chat item properties. To insert the value of a field, use the syntax `{{Record.FieldApiName}}`. For example, to use the value of the Name field, use `{{Record.Name}}`.                                          | DdChatMapping       | —                                               |          |
| `no-results-message`       | Message of the illustration displayed when no records are returned.                                                                                                                                                                                                                          | String              | `"Please publish a message to start the chat."` |          |
| `no-results-title`         | Title of the illustration displayed when no records are returned.                                                                                                                                                                                                                            | String              | `"No messages yet"`                             |          |
| `publisher`                | Object defining the chat publisher configuration.                                                                                                                                                                                                                                            | DdChatPublisher     | —                                               |          |
| `query`                    | Definition of the query to execute to get the records that will be mapped to chat messages. The order of the query is always based on the field mapped to the messages date. If empty, it defaults to the `CreatedDate` field.                                                               | DdChatQuery         | —                                               |          |
| `read-only`                | If present, the chat is read-only and the publisher is hidden.                                                                                                                                                                                                                               | Boolean             | `false`                                         |          |
| `refresh-emp`              | Platform event configuration used to refresh the chat when events occur.                                                                                                                                                                                                                     | DdElementRefreshEmp | —                                               |          |
| `resources`                | Array of resources (participants) referenced by the static `items`. Each resource's `name` is matched against the `resourceName` of the messages to resolve their label and avatar. Used only in static mode; in query mode the resources are resolved from the `mapping`.                   | DdChatResource\[]   | —                                               |          |

### Mapping

In query mode, the `mapping` object tells the chat how to build each message from a queried record. Insert a field value with the `{{Record.FieldApiName}}` syntax (for example `{{Record.Name}}`).

| Mapping Key          | Description                                                                                                                                                                 |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `date`               | Message date, for example `{{Record.CreatedDate}}`. Drives the query ordering.                                                                                              |
| `name`               | Required. Unique message key, commonly `{{Record.Id}}`.                                                                                                                     |
| `value`              | Message body (supports rich text), for example `{{Record.avonni__Value__c}}`.                                                                                               |
| `participantName`    | Unique name of the participant who sent the message, for example `{{Record.CreatedById}}`.                                                                                  |
| `participantMapping` | Object used when `participantName` maps to a relationship field; defines participant `label`, `name`, and avatar (`avatarSrc`, `avatarInitials`, `avatarFallbackIconName`). |
| `type`               | Message type: `inbound` or `outbound`. Defaults to automatic detection against the current participant.                                                                     |

In static mode, each item's `resourceName` is matched against a `resources` entry to resolve the participant `label` and avatar (`avatarSrc`, `avatarInitials`, or `avatarFallbackIconName`).

### Methods

| Name      | Description                                                   | Argument Name | Argument Type | Argument Description |
| --------- | ------------------------------------------------------------- | ------------- | ------------- | -------------------- |
| `refresh` | Refresh the query and the records displayed in the component. |               |               |                      |

### Custom Events

#### `publish`

The event fired when the user publishes a message.

The `publish` event returns the following parameters.

| Parameter         | Type      | Description                                   |
| ----------------- | --------- | --------------------------------------------- |
| `date`            | string    | Current date and time, as an ISO 8601 string. |
| `mentions`        | string\[] | Unique names of the mentioned participants.   |
| `participantName` | string    | Unique name of the current participant.       |
| `value`           | string    | Value of the message.                         |

The event properties are as follows.

| Property   | Value | Description                                                                                               |
| ---------- | ----- | --------------------------------------------------------------------------------------------------------- |
| bubbles    | false | This event does not bubble.                                                                               |
| cancelable | false | This event has no default behavior that can be canceled. You can't call `preventDefault()` on this event. |
| composed   | false | This event does not propagate outside of the component in which it was dispatched.                        |

### Styling Hooks

| CSS Variable                                         | Type  | Default   |
| ---------------------------------------------------- | ----- | --------- |
| `--avonni-dd-chat-outbound-message-color-background` | color | `#032D60` |
| `--avonni-dd-chat-outbound-message-text-color`       | color | `#FFFFFF` |
| `--avonni-dd-chat-inbound-message-color-background`  | color | `#F3F3F3` |
| `--avonni-dd-chat-inbound-message-text-color`        | color | `#2E2E2E` |

## Key Considerations

* **Query vs static:** Setting `items` switches the component to static mode and causes `query` and `mapping` to be ignored. In static mode you must supply `resources` so each message's `resourceName` resolves to a participant.
* **Mapping syntax:** Field values are inserted with `{{Record.FieldApiName}}` in query mode; the query is always ordered by the field mapped to `date` (defaulting to `CreatedDate`).
* **Current participant:** `current-participant-name` (defaulting to the current user Id) decides which messages render as sent when no message `type` is set.
* **Live refresh:** Use `refresh-emp` with a platform event `channelName` to refresh the conversation automatically; call the `refresh()` method to refresh it programmatically.
* **Publisher:** The `publish` event reports the author as `participantName`, which corresponds to the `resourceName` used by static items.
* **Best Practice:** In query mode, map `name` to the record `Id` (a stable, unique key) and map `date` to the field that determines chronological order — the query is always ordered by the mapped date field.

***

## Troubleshooting Common Issues

* **Messages appear on the wrong side:** Check `current-participant-name` (or the mapped `type`); messages from the current participant render as outbound.
* **Avatars or names missing in static mode:** Ensure every message `resourceName` matches a `resources` entry `name`.
* **Empty chat in query mode:** Confirm `query.objectApiName` and that `mapping` sets at least `name`, `value`, and `date`; verify the running user has read access to the object.
* **If issues persist:** Contact our support team at <support@avonni.app> for assistance.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.avonnicomponents.com/lwc-components/data-driven-components/chat.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
