### Development setup and verification
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/README.md
Install dependencies, run the local docs and component playground, and run the full verification chain (format, types, lint, tests, build, pack, storybook). Requires Node 22.14.0 or newer.
```bash
npm ci
```
```bash
npm run storybook # local docs + component playground
```
```bash
npm run verify # format + types + lint + tests + build + pack + storybook
```
--------------------------------
### Update package registration and app setup
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/07-migration-from-v2.mdx
Shows the diff for replacing the v2 `register()` call with the V3 plugin and component imports. The V3 setup requires installing the plugin with `app.use(AdvancedChatPlugin({ strings: { … } }))` and importing the styles.
```diff
- import { register } from 'vue-advanced-chat'
- register()
+ import { AdvancedChatPlugin, AdvancedChat } from '@advanced-chat/components'
+ import '@advanced-chat/components/styles'
const app = createApp(App)
+ app.use(AdvancedChatPlugin({ strings: { … } }))
app.mount('#app')
```
--------------------------------
### Vue 3 quick example - main.ts
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/README.md
Sets up the Vue app with the AdvancedChatPlugin and imports the component styles.
```ts
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import { AdvancedChatPlugin } from '@advanced-chat/components'
import '@advanced-chat/components/styles'
createApp(App).use(AdvancedChatPlugin()).mount('#app')
```
--------------------------------
### Set up local environment with nvm and npm ci
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/CONTRIBUTING.md
Use the checked-in .nvmrc to select Node.js 22.14.0, then install dependencies with npm ci (not npm install) to validate the lockfile.
```sh
nvm use
npm ci
```
--------------------------------
### Install vue-advanced-chat v2.1.2
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/README.md
Install the stable v2 line (2.1.2) of vue-advanced-chat via npm.
```bash
npm install vue-advanced-chat
```
--------------------------------
### Install V3 package with npm
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/README.md
Install the V3 package using npm. Vue 3.5+ is a peer dependency.
```bash
npm install @advanced-chat/components@next
```
--------------------------------
### Vue 3 quick example - App.vue
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/README.md
Defines the App.vue component using the AdvancedChat component with current user, chats, and messages.
```vue
```
--------------------------------
### Install Playwright Chromium for browser tests
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/CONTRIBUTING.md
Install Playwright Chromium when needed for browser tests.
```sh
npx playwright install chromium
```
--------------------------------
### Local + Server-Driven Hybrid Example
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-local-search.mdx
Vue component demonstrating a hybrid search: local filtering with useLocalSearch and optional server-driven results via a custom onSearch callback. The custom flag toggles between local and remote modes.
```vue
{{ chat.name }}
```
--------------------------------
### Wire the plugin in main.ts
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/01-quick-start.mdx
Registers the AdvancedChatPlugin and imports the required stylesheet. The plugin provides the localized strings dictionary; without it, components fall back to bundled English strings and warn under import.meta.env.DEV. The CSS import is required because styles are not inlined.
```ts
import { createApp } from 'vue'
import App from './App.vue'
import { AdvancedChatPlugin } from '@advanced-chat/components'
import '@advanced-chat/components/styles'
const app = createApp(App)
app.use(
AdvancedChatPlugin({
// Optional — override any subset of the bundled English strings.
strings: {
'chats.search.placeholder': 'Search conversations',
},
}),
)
app.mount('#app')
```
--------------------------------
### Chat-row selection example
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-message-selection.mdx
Vue component demonstrating bulk selection of chat rows using useMessageSelection. Includes script setup with toggle, cancel, and archive actions, plus a template with selection mode buttons and row highlighting.
```vue
{{ chat.name }}
```
--------------------------------
### Read strings outside setup() with getLocalizationStrings
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/04-localization.mdx
Use `getLocalizationStrings('en')` to retrieve the dictionary in non-component contexts, such as formatting a notification body. The returned object is typed as `Strings`.
```ts
import { getLocalizationStrings } from '@advanced-chat/components'
const strings = getLocalizationStrings('en')
const failedMessageText = strings['chat.message.failure']
```
--------------------------------
### Import the Strings type
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/04-localization.mdx
Import the `Strings` type from the package to get a typed map of all keys the components read. Hover the type in your editor for the complete list of keys.
```ts
import type { Strings } from '@advanced-chat/components'
```
--------------------------------
### Render the chat in App.vue
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/01-quick-start.mdx
A complete chat component with in-memory data. When a user chooses an @ suggestion, the composer stores a stable <@user-id> token in payload.content and includes resolved users in payload.mentionedUsers; persist content as emitted. MessageTemplate resolves known ids against the chat's users array, so later name changes do not invalidate stored messages. This minimal example disables file selection.
```vue
```
--------------------------------
### Setup: Override strings via AdvancedChatPlugin
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/04-localization.mdx
Configure the plugin with a `Partial` object to override bundled English strings. The plugin deep-merges overrides on top of defaults; omitted keys keep their defaults. If the plugin is skipped, components fall back to English and emit a `console.warn` under `import.meta.env.DEV` (silenced in production).
```ts
import { createApp } from 'vue'
import { AdvancedChatPlugin } from '@advanced-chat/components'
import App from './App.vue'
createApp(App)
.use(
AdvancedChatPlugin({
strings: {
'chats.empty': 'No conversations yet',
'chat.message.placeholder': 'Send a message to your team',
},
}),
)
.mount('#app')
```
--------------------------------
### Vue message-list pagination with useInfiniteScroll
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-infinite-scroll.mdx
Pagination example for a message list using the useInfiniteScroll composable. The sentinel element triggers onLoadMore when scrolled into view; call setLoading(false) after new data arrives. fetchOlderMessages is an app-owned API placeholder to replace with your backend implementation.
```vue
Loading older messages…
{{ message.content }}
```
--------------------------------
### Use advanced-chat-components with Properties and Events
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/08-web-components.mdx
Assign objects and arrays as DOM properties; use attributes for simple strings, numbers, and booleans. The example sets up the chat with a current user, chats, and event listener for 'send-message'.
```html
```
--------------------------------
### Custom composer example with useReplyEdit
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-reply-edit.mdx
A Vue component wiring useReplyEdit into a custom message list and composer. dispatch handles built-in reply/edit actions and passes custom actions through; resetReply and resetEdit clear the respective refs.
```vue
```
--------------------------------
### Vite SSR mounted flag with async chat surface
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/06-ssr.mdx
For non-Nuxt Vite SSR setups, render the same fallback during the server pass and the client's initial hydration render. Set a mounted flag in onMounted before rendering a lazily imported chat surface. Unlike const isSsr = import.meta.env.SSR, mounted is false for both the server render and the client's initial render, so the fallback hydrates against matching markup; the async chat module is requested only after mount.
```vue
```
--------------------------------
### Import Styles type
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/03-theming.mdx
The supported CSS custom properties are typed via the exported `Styles` interface. Import it to get the full list with field names when hovering over the type in your editor.
```ts
import type { Styles } from '@advanced-chat/components'
```
--------------------------------
### Localization
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/api-reference.mdx
Exports for localization support, including types and functions to get localized strings.
```APIDOC
## Localization
### Localization
- **Type**: `'en' | 'auto'`
- **Description**: Locale configuration type.
### Strings
- **Type**: Full string-key map (frozen as a typed contract — adding a key is a breaking change for typed consumers).
- **Description**: Type representing the string keys.
### getLocalizationStrings
- **Function**: `(locale: Localization) => Strings`
- **Description**: Returns the localized strings. The `'auto'` case calls `negotiateLocale()` internally.
### useLocalizationStrings
- **Composable**: `inject`-based accessor for component code; falls back to `'auto'` and warns under DEV when no plugin is installed.
- **Description**: Composable for accessing localized strings.
### negotiateLocale
- **Function**: `() => 'en'`
- **Description**: Lowercases `navigator.language` and returns the first supported matching prefix (`'en'` only today).
```
--------------------------------
### Vue component using useAutocomplete for slash-command menu
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-autocomplete.mdx
Example of a slash-command menu in Vue 3 with TypeScript. It uses the useAutocomplete composable from '@advanced-chat/components' to filter commands based on the message input, handle keyboard navigation, and commit selection. The component includes a textarea and a listbox with mouse and keyboard interactions.
```vue
{{ cmd.label }}
```
--------------------------------
### useThemeStyles composable for reactive theming outside Layout
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/03-theming.mdx
Call useThemeStyles to get reactive CSS variables when rendering primitives like Message outside of Layout. It accepts a ref of type Theme ('auto' by default) and returns a Ref to bind to a wrapper's :style. Handles prefers-color-scheme changes for 'auto' and cleans up the listener on unmount.
```ts
import { ref } from 'vue'
import { useThemeStyles, type Theme } from '@advanced-chat/components'
const theme = ref('auto')
const cssVars = useThemeStyles(theme)
// cssVars is a Ref; bind it to :style on a wrapper.
```
--------------------------------
### Override map with base and overrides
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/03-theming.mdx
Pass an object to the `theme` prop to override individual CSS variables on top of the resolved palette. The `base` field picks the starting palette (`'light'` or `'dark'`), and `overrides` is a `Partial` deep-merged on top.
```vue
```
--------------------------------
### Use the web-component entrypoint
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/07-migration-from-v2.mdx
Shows how to use the framework-independent web-component entrypoint. Importing the entrypoint auto-registers ``; no default `register()` call is needed. Assign typed properties rather than serialized attributes, and DOM event payloads are direct `CustomEvent.detail` values.
```ts
import '@advanced-chat/components/web-component'
import '@advanced-chat/components/web-component/styles'
import type { AdvancedChatHTMLElement } from '@advanced-chat/components/web-component'
const chat = document.querySelector('advanced-chat-components')!
chat.currentUser = { id: 'me' }
chat.chats = chats
chat.messages = messages
chat.addEventListener('send-message', (event) => {
persist(event.detail)
})
```
--------------------------------
### Web component usage with HTML and JavaScript
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/README.md
Shows how to use the web component in plain HTML/JS, assigning properties and listening for the send-message event.
```html
```
--------------------------------
### Browser host integration with ChatKitty adapter
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/cookbook/chatkitty-byoc.mdx
Integrates the advanced-chat web component with a ChatKitty adapter in a browser host. Sets up the adapter, initializes the element, and handles chat selection, message fetching, sending, and file opening. Includes event listeners and cleanup.
```TypeScript
import '@advanced-chat/components/web-component'
import '@advanced-chat/components/web-component/styles'
import type { ChatModel, MessageModel, User } from '@advanced-chat/components'
import type {
AdvancedChatEventMap,
AdvancedChatHTMLElement,
} from '@advanced-chat/components/web-component'
type SendMessagePayload = Omit & {
reply?: NonNullable
}
interface ChatKittyAdapter {
currentUser(): Promise
listChats(): Promise
listMessages(chatId: ChatModel['id']): Promise<{
messages: MessageModel[]
exhausted: boolean
}>
openChat(chatId: ChatModel['id']): Promise
loadOlderMessages(
chatId: ChatModel['id'],
before: MessageModel['id'],
): Promise<{
messages: MessageModel[]
exhausted: boolean
}>
sendMessage(payload: SendMessagePayload): Promise
openAuthorizedFile(file: NonNullable[number]): Promise
subscribe(onChange: () => void): () => void
}
declare function createAdapterForYourDeployment(): ChatKittyAdapter
declare function refreshUiModels(): Promise
const adapter: ChatKittyAdapter = createAdapterForYourDeployment()
const element = document.querySelector('advanced-chat-components')
if (!element) throw new Error('Missing host')
element.currentUser = await adapter.currentUser()
const chats = await adapter.listChats()
element.chats = chats
element.chatsLoaded = true
element.showAddChat = false
element.messageActions = []
element.selectionActions = []
element.showReactionEmojis = false
let selectionVersion = 0
const selectChat = async (chat: ChatModel) => {
const version = ++selectionVersion
// The event does not update the element's public properties for the host.
element.chat = chat
element.messages = []
element.loadingMessages = true
element.messagesLoaded = false
try {
await adapter.openChat(chat.id)
const page = await adapter.listMessages(chat.id)
if (version !== selectionVersion || element.chat?.id !== chat.id) return
element.messages = [...page.messages]
element.messagesLoaded = page.exhausted
} catch (error) {
if (version === selectionVersion) {
element.messagesLoaded = true
element.status = 'error'
element.statusMessage = 'Unable to open this conversation.'
}
console.error(error)
} finally {
if (version === selectionVersion) element.loadingMessages = false
}
}
const initialChat = chats[0]
if (initialChat) {
await selectChat(initialChat)
} else {
element.chat = null
element.messages = []
element.loadingMessages = false
element.messagesLoaded = true
}
const onOpenChat = (event: AdvancedChatEventMap['open-chat']) => {
element.status = 'ready'
element.statusMessage = ''
void selectChat(event.detail)
}
const onFetchMessages = async () => {
const chat = element.chat
const currentMessages = element.messages ?? []
const oldest = currentMessages[0]
if (!chat || !oldest || element.loadingMessages || element.messagesLoaded) return
const version = selectionVersion
element.loadingMessages = true
try {
const page = await adapter.loadOlderMessages(chat.id, oldest.id)
if (version !== selectionVersion || element.chat?.id !== chat.id) return
const latestMessages = element.messages ?? []
const loadedIds = new Set(latestMessages.map((message) => message.id))
element.messages = [
...page.messages.filter((message) => !loadedIds.has(message.id)),
...latestMessages,
]
element.messagesLoaded = page.exhausted
} catch (error) {
console.error(error)
} finally {
if (version === selectionVersion) element.loadingMessages = false
}
}
const onSendMessage = (event: AdvancedChatEventMap['send-message']) => {
const { reply, ...message } = event.detail
void adapter.sendMessage(reply ? { ...message, reply } : message)
}
const onOpenFile = (event: AdvancedChatEventMap['open-file']) => {
void adapter.openAuthorizedFile(event.detail.file)
}
element.addEventListener('open-chat', onOpenChat)
element.addEventListener('fetch-messages', onFetchMessages)
element.addEventListener('send-message', onSendMessage)
element.addEventListener('open-file', onOpenFile)
const unsubscribe = adapter.subscribe(() => void refreshUiModels())
const dispose = () => {
unsubscribe()
element.removeEventListener('open-chat', onOpenChat)
element.removeEventListener('fetch-messages', onFetchMessages)
element.removeEventListener('send-message', onSendMessage)
element.removeEventListener('open-file', onOpenFile)
}
```
--------------------------------
### Run full local verification suite
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/RELEASING.md
Run before release to verify the package. Requires Node 22.14.0+ and npm 11.5.1+.
```bash
npm ci
npm run verify
```
--------------------------------
### useLocalizationStrings
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/api-reference.mdx
Composable function to access localization strings during component setup. It is a typed alternative to the $advancedChatString global helper.
```APIDOC
## useLocalizationStrings
### Description
Composable to access localization strings during component setup. Use this for typed access within Vue components.
### Usage
Call `useLocalizationStrings()` inside a component's setup function.
### Returns
- `object` - The localization dictionary.
```
--------------------------------
### AdvancedChatPlugin({ localization?, strings? })
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/rewrite/architecture.md
Creates a plugin that provides a global strings dictionary via Vue's provide/inject. Components consume it through useLocalizationStrings().
```APIDOC
## AdvancedChatPlugin({ localization?, strings? })
### Description
Creates a plugin that provides a global strings dictionary via Vue's provide/inject. Components consume it through useLocalizationStrings().
### Parameters
- **localization** (object) - Optional - Localization configuration.
- **strings** (object) - Optional - Strings dictionary.
### Returns
- **Plugin** - A Vue plugin object.
### Notes
- There is no per-instance string override prop — apps inject the strings they want once.
```
--------------------------------
### Import and use useInfiniteScroll composable
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-infinite-scroll.mdx
Initializes the composable with options for target, scroll root, exhausted flag, root margin, and onLoadMore callback. Returns loading state, setLoading, and reset functions.
```ts
import { useInfiniteScroll } from '@advanced-chat/components'
const { loading, setLoading, reset } = useInfiniteScroll({
target,
scrollRoot,
exhausted,
rootMargin,
onLoadMore,
})
```
--------------------------------
### AdvancedChatPlugin
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/api-reference.mdx
Vue plugin factory that provides the localization dictionary and the $advancedChatString global helper. Use it to install the plugin in your Vue application.
```APIDOC
## AdvancedChatPlugin
### Description
Vue plugin factory. Provides the localization dictionary and `$advancedChatString(key)` global helper.
### Usage
Call the factory to create a plugin object with an `install(app)` method, then pass it to `app.use()`.
### Parameters
- `options` (AdvancedChatOptions) - Required - Options accepted by the plugin factory.
### Returns
- `AdvancedChatPluginType` - An installable object: `{ install(app: App): void }`.
```
--------------------------------
### Run complete project gate with npm run verify
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/CONTRIBUTING.md
Run the full validation gate before final review. It checks formatting, types, lint, tests, builds, package contents, web-component contract, and static Storybook build.
```sh
npm run verify
```
--------------------------------
### Optimistic upload with background upload and persistence
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/cookbook/file-uploads.mdx
Implements optimistic message sending: appends a local-only message immediately, uploads files in the background with progress updates, then persists the message and replaces the optimistic record. Requires uploadWithProgress and writeMessage functions. The optimistic record preserves tokenized mention content and reply summary; mentionedUserIds is captured until final persistence. The reply field is omitted when the event supplies null or undefined. MessageFile.progress is clamped to 0-100 and rendered as a progress bar overlay; a value of 100 still renders the overlay, so remove the field or set it to undefined after upload completes.
```TypeScript
import { ref } from 'vue'
import type {
ChatFileItem,
MessageFileModel,
MessageModel,
MessageSummary,
User,
} from '@advanced-chat/components'
declare function uploadWithProgress(
blob: Blob,
onProgress: (progress: number) => void,
): Promise
declare function writeMessage(input: {
content: string
files: MessageFileModel[]
mentionedUserIds: User['id'][]
reply?: MessageSummary
}): Promise
const toReplySummary = (message: MessageModel): MessageSummary => ({
id: message.id,
sender: message.sender,
createdAt: message.createdAt,
...(message.content === undefined ? {} : { content: message.content }),
...(message.status === undefined ? {} : { status: message.status }),
...(message.deleted === undefined ? {} : { deleted: message.deleted }),
...(message.edited === undefined ? {} : { edited: message.edited }),
...(message.files === undefined ? {} : { files: message.files }),
})
const currentUser: User = {
id: 'me',
name: 'Alice',
status: { state: 'online' },
}
const messages = ref([])
const onSend = async (payload: {
content: string
files: ChatFileItem[]
mentionedUsers: User[]
reply?: MessageModel | null
}) => {
const optimisticId = `pending-${Date.now()}`
const mentionedUserIds = payload.mentionedUsers.map((user) => user.id)
const reply = payload.reply ? toReplySummary(payload.reply) : undefined
const localUrls = new Set(
payload.files.map((file) => file.localUrl).filter((url): url is string => Boolean(url)),
)
const localFiles: MessageFileModel[] = payload.files.map((f) => ({
name: f.name,
type: f.type,
extension: f.extension,
url: f.url, // local object URL — preview works without waiting.
progress: 0,
}))
// 1. Append the local-only message.
messages.value = [
...messages.value,
{
id: optimisticId,
sender: currentUser,
content: payload.content,
createdAt: new Date().toISOString(),
status: 'sending',
files: localFiles,
...(reply === undefined ? {} : { reply }),
},
]
const updateFile = (index: number, patch: Partial) => {
messages.value = messages.value.map((message) =>
message.id === optimisticId
? {
...message,
files: message.files?.map((file, fileIndex) =>
fileIndex === index ? { ...file, ...patch } : file,
),
}
: message,
)
}
try {
// 2. Upload in the background and replace each local URL as it completes.
for (let index = 0; index < payload.files.length; index++) {
const file = payload.files[index]!
if (!file.blob) {
if (file.url.startsWith('blob:')) {
throw new Error(`Cannot persist the local URL for ${file.name}`)
}
updateFile(index, { progress: undefined })
continue
}
const url = await uploadWithProgress(file.blob, (progress) => {
updateFile(index, { progress })
})
updateFile(index, { url, progress: undefined })
}
// 3. Persist serializable file metadata and replace the optimistic record.
const optimistic = messages.value.find((message) => message.id === optimisticId)
const files = (optimistic?.files ?? []).map(({ progress: _progress, ...file }) => file)
const persisted = await writeMessage({
content: payload.content,
files,
mentionedUserIds,
...(reply === undefined ? {} : { reply }),
})
messages.value = messages.value.map((message) =>
message.id === optimisticId ? persisted : message,
)
} catch (error) {
// This example removes the failed preview. A retry UI may retain it, but then
// it must retain and later revoke the object URLs too.
messages.value = messages.value.filter((message) => message.id !== optimisticId)
throw error
} finally {
localUrls.forEach((url) => URL.revokeObjectURL(url))
}
}
```
--------------------------------
### Run focused validation commands
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/CONTRIBUTING.md
Run formatting, type-check, lint, unit tests, and Storybook tests while developing.
```sh
npm run format:check
npm run type-check
npm run lint
npm run test:unit
npm run test:storybook
```
--------------------------------
### Per-instance overrides with Layout.styles
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/03-theming.mdx
Use `Layout.styles` to apply a separate `Partial` as the final layer for per-instance overrides. Applied order is bundled palette → `theme.overrides` → `Layout.styles`. `AdvancedChat` does not have a `styles` prop; use its object-form `theme` instead.
```vue
```
--------------------------------
### useReplyEdit(options)
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-reply-edit.mdx
Composer state machine for the built-in REPLY_ACTION / EDIT_ACTION. It translates per-message action dispatches into the replyMessage / editMessage refs that ChatFooter reads. Use it directly when wiring up a custom composer without re-implementing the mutually-exclusive reply/edit state.
```APIDOC
## useReplyEdit(options)
### Description
Composer state machine for the built-in `REPLY_ACTION` / `EDIT_ACTION`. It translates per-message action dispatches into the `replyMessage` / `editMessage` refs that `ChatFooter` reads. Use it directly when wiring up a custom composer without re-implementing the mutually-exclusive reply/edit state.
### Signature
```ts
import { useReplyEdit } from '@advanced-chat/components'
const { replyMessage, editMessage, dispatch, resetReply, resetEdit } = useReplyEdit({ resetKey })
```
### Parameters
#### Options
- **resetKey** (`MaybeRefOrGetter`) - Optional - Watching this clears both `replyMessage` and `editMessage` whenever it changes. Pass `() => activeChat.id` to clear when the active chat switches.
### Returns
- **replyMessage** (`Ref`) - Message currently being replied to, or `null`.
- **editMessage** (`Ref`) - Message currently being edited, or `null`.
- **dispatch** (`(payload: { action: Action; message: MessageModel }) => void`) - Consumes a `message-action-handler` payload. Sets `replyMessage` / `editMessage` for the built-in reply/edit actions and is otherwise a no-op; it does not emit an event.
- **resetReply** (`() => void`) - Clears `replyMessage`. Wire to `ChatFooter`'s `reset-reply-message` event.
- **resetEdit** (`() => void`) - Clears `editMessage`. Wire to `ChatFooter`'s `reset-edit-message` event.
### Example — custom composer
```vue
```
`MyMessageList`, `MyComposer`, and `openForwardModal` are intentionally app-owned parts of this composition example.
### Notes
- `dispatch` reads `payload.action.id` (string) and matches against the exported `REPLY_ACTION` / `EDIT_ACTION` constants. That means host-defined `Action` values with `id: 'reply'` work the same as the built-in constant — no identity check.
- Setting one of `replyMessage` / `editMessage` clears the other: the two are mutually exclusive. `ChatFooter` does the same.
- Custom actions (`'forward'`, `'pin'`, etc.) leave both refs untouched — `dispatch` is silent on them. Your `onMessageAction` handler still receives the original payload through whatever path you wired (here: re-emitting from the message list).
```
--------------------------------
### Locale negotiation with negotiateLocale
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/04-localization.mdx
Call `negotiateLocale()` to get the current locale. It inspects `navigator.language` and matches against supported BCP 47 prefixes (only `'en'`). If the browser language is not English, it falls back to English and logs a `console.warn` under `import.meta.env.DEV`. Under SSR, it returns `'en'` directly.
```ts
import { negotiateLocale } from '@advanced-chat/components'
negotiateLocale() // 'en'
```
--------------------------------
### Disable actions and reactions on a message with disableActions and disableReactions
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/cookbook/custom-actions.mdx
Use these Message flags to suppress the per-message dropdown menu and inline reaction picker on a specific message. The example sets both flags on a system message, though system messages already hide both by default.
```ts
import type { MessageModel, User } from '@advanced-chat/components'
const otherUser: User = {
id: 'moderator',
name: 'Moderator',
status: { state: 'online' },
}
const messages: MessageModel[] = [
{
id: '1',
sender: otherUser,
content: 'A system announcement',
createdAt: '2026-08-08T12:00:00.000Z',
system: true,
disableActions: true,
disableReactions: true,
},
]
```
--------------------------------
### useAutocomplete signature
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-autocomplete.mdx
Imports and initializes the useAutocomplete composable with options for items, selectSignal, navSignal, onCommit, and onNavigate.
```ts
import { useAutocomplete } from '@advanced-chat/components'
const { activeIndex, setActiveIndex } = useAutocomplete({
items,
selectSignal,
navSignal,
onCommit,
onNavigate,
})
```
--------------------------------
### Import and use useReplyEdit
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/composables/use-reply-edit.mdx
Import the useReplyEdit composable and destructure its returned refs and functions. The resetKey option watches a value and clears both replyMessage and editMessage when it changes.
```ts
import { useReplyEdit } from '@advanced-chat/components'
const { replyMessage, editMessage, dispatch, resetReply, resetEdit } = useReplyEdit({ resetKey })
```
--------------------------------
### Format and check docs and rewrite files
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/RELEASING.md
Use when public docs or rewrite records changed. Checks only specified files, not unrelated working-tree files.
```bash
npx prettier --check README.md CHANGELOG.md RELEASING.md "docs/**/*.mdx" "rewrite/*.md"
git diff --check
```
--------------------------------
### Data flow diagram
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/cookbook/backend-integration.mdx
Illustrates the boundary between backend, reactive refs, and AdvancedChat component props and events.
```text
backend ──> reactive refs ──> AdvancedChat (props)
│
backend <── handlers <── AdvancedChat (events)
```
--------------------------------
### Fetch older messages with getDocs
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/cookbook/backend-integration.mdx
Loads an older page of messages using getDocs with startAfter cursor. It guards against race conditions when the user switches chats and merges older messages into the list. Use this for pagination when the user scrolls up.
```typescript
const fetchMoreMessages = async () => {
const chat = activeChat.value
const cursor = oldestLoaded
if (!chat || !cursor || messagesLoaded.value || loadingMessages.value) return
loadingMessages.value = true
try {
const olderQuery = query(
collection(db, 'chats', chat.id, 'messages'),
orderBy('createdAt', 'desc'),
startAfter(cursor),
limit(PAGE_SIZE),
)
const snapshot = await getDocs(olderQuery)
// Ignore a response that completed after the user switched chats.
if (activeChat.value?.id !== chat.id) return
const loadedIds = new Set(messages.value.map((message) => message.id))
const older = snapshot.docs
.map(toMessageModel)
.reverse()
.filter((message) => !loadedIds.has(message.id))
messages.value = [...older, ...messages.value]
oldestLoaded = snapshot.docs.at(-1) ?? oldestLoaded
messagesLoaded.value = snapshot.size < PAGE_SIZE
} finally {
loadingMessages.value = false
}
}
```
--------------------------------
### Register custom web component tag with core entrypoint
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/README.md
Imports the side-effect-free core entrypoint to register a custom tag name for the web component.
```ts
import {
registerAdvancedChat,
type AdvancedChatHTMLElement,
} from '@advanced-chat/components/web-component/core'
import '@advanced-chat/components/web-component/styles'
if (typeof window !== 'undefined') {
registerAdvancedChat({ tagName: 'acme-chat' })
}
```
--------------------------------
### Svelte: Use bind:this to set properties and add event listener
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/docs/08-web-components.mdx
Use bind:this when you want an explicit property and event boundary. In onMount, set properties like currentUser, chats, chat, messages, and flags, and add a send-message event listener that logs the detail.
```svelte
```
--------------------------------
### Create and push release tag
Source: https://github.com/advanced-chat/advanced-chat-components/blob/main/RELEASING.md
Push the exact tag matching package.json with a v prefix, e.g., v3.0.0-rc.3. The tag push triggers the Release Package workflow.
```bash
git tag v3.0.0-rc.3 && git push origin v3.0.0-rc.3
```