### React
```
import * as Ably from 'ably';
import { ChatClient } from '@ably/chat';
import { ChatClientProvider } from '@ably/chat/react';
import { ThemeProvider, AvatarProvider, ChatSettingsProvider } from '@ably/chat-react-ui-kit';
// Create Ably Realtime client
const ablyClient = new Ably.Realtime({
key: 'your-api-key', // Replace with your Ably API key
clientId: 'your-chat-client-id',
});
const chatClient = new ChatClient(ablyClient);
function App() {
return (
{/* Your Chat UI components */}
);
}
```
## ChatSettingsProvider
The `ChatSettingsProvider` manages global and room-level chat settings across the application.
### Features
- Provides default settings for message edits, deletes, and reactions
- Allows overriding settings globally or per room
- Provides a method to get effective settings for a room by merging global and room-specific settings
### Props
| Prop | Description |
|------|-------------|
| `children` | Child components that will have access to chat settings |
| `initialGlobalSettings` | Initial global settings (merged with defaults) |
| `initialRoomSettings` | Initial room-specific settings mapping |
### ChatSettings
| Setting | Description |
|---------|-------------|
| `allowMessageUpdatesOwn` | Whether users can update their messages after sending |
| `allowMessageUpdatesAny` | Whether users can update any message in the room |
| `allowMessageDeletesOwn` | Whether users can delete their messages |
| `allowMessageDeletesAny` | Whether users can delete any message in the room |
| `allowMessageReactions` | Whether users can add reactions to messages |
### Example
#### React
```
import { ChatSettingsProvider } from '@ably/chat-react-ui-kit';
const globalSettings = {
allowMessageUpdatesOwn: false,
allowMessageDeletesOwn: true,
allowMessageReactions: true,
};
const roomSettings = {
'general': { allowMessageUpdatesOwn: true },
'announcements': {
allowMessageUpdatesOwn: false,
allowMessageUpdatesAny: false,
allowMessageDeletesOwn: false,
allowMessageDeletesAny: false,
},
};
;
```
## useChatSettings Hook
The `useChatSettings` hook provides access to the chat settings context.
### Returns
| Property | Description |
|----------|-------------|
| `globalSettings` | Global settings that apply to all rooms |
| `roomSettings` | Room-specific settings mapping |
| `getEffectiveSettings` | Function to get effective settings for a room |
### Example
#### React
```
import { useChatSettings } from '@ably/chat-react-ui-kit';
const { getEffectiveSettings } = useChatSettings();
// Get settings for a specific room
const roomSettings = getEffectiveSettings('general');
// Check if message editing is allowed in this room
if (roomSettings.allowMessageUpdatesOwn || roomSettings.allowMessageUpdatesAny) {
// Show edit button
}
```
## ThemeProvider
The `ThemeProvider` manages theme state, persistence, and system theme integration across the application. All the components have pre-defined styles that adapt to the current theme.
### Features
- Light/dark theme management with type safety
- Persistent theme preference in localStorage
- System theme preference detection and integration
- Change notifications for theme updates
- Performance optimizations with memoization
- Accessibility support with proper DOM updates
### Props
| Prop | Description |
|------|-------------|
| `children` | Child components that will have access to the theme context |
| `options` | Configuration options for theme management |
| `onThemeChange` | Callback fired when the theme changes |
### ThemeOptions
| Option | Description |
|--------|-------------|
| `persist` | Whether to persist theme preference to localStorage |
| `detectSystemTheme` | Whether to detect and use system theme preference |
| `defaultTheme` | Initial theme to use if no preference is found (light/dark) |
### Example
#### React
```
import { ThemeProvider } from '@ably/chat-react-ui-kit';
{
console.log(`Theme changed from ${prev} to ${theme}`);
}}
>
```
## useTheme Hook
The `useTheme` hook provides access to the theme context for theme management. It allows you to get the current theme, set a new theme, toggle between themes, and register callbacks for theme changes.
### Returns
| Property | Description |
|----------|-------------|
| `theme` | Current theme (light/dark) |
| `setTheme` | Function to set the theme |
| `toggleTheme` | Function to toggle between light and dark themes |
| `isDark` | Whether the current theme is dark |
| `isLight` | Whether the current theme is light |
| `supportsSystemTheme` | Whether the browser supports system theme detection |
| `getSystemTheme` | Function to get the current system theme |
| `resetToSystemTheme` | Function to reset to the system theme |
| `onThemeChange` | Function to register a theme change callback |
### Examples
#### React
```
// Basic theme usage
import { useTheme } from '@ably/chat-react-ui-kit';
const { theme, toggleTheme } = useTheme();
return (
);
```
#### React
```
// Using boolean helpers
import { useTheme } from '@ably/chat-react-ui-kit';
const { isDark, setTheme } = useTheme();
return (
);
```
#### React
```
// System theme integration
import { useTheme } from '@ably/chat-react-ui-kit';
const { supportsSystemTheme, getSystemTheme, resetToSystemTheme } = useTheme();
return (
{supportsSystemTheme && (
)}
);
```
#### React
```
// Theme change notifications
import { useEffect } from 'react';
import { useTheme } from '@ably/chat-react-ui-kit';
const { onThemeChange } = useTheme();
useEffect(() => {
const cleanup = onThemeChange((newTheme, previousTheme) => {
console.log(`Theme changed from ${previousTheme} to ${newTheme}`);
// Update analytics, save preferences, etc.
});
return cleanup;
}, [onThemeChange]);
```
## AvatarProvider
The `AvatarProvider` manages avatar data for users and rooms across the application. It provides methods to generate, cache, and persist avatars, as well as handle avatar changes.
### Features
- Generates and caches avatars for users and rooms
- Persists avatars to localStorage
- Provides methods to get, set, and update avatars
- Supports custom color palettes
- Handles caching and cache size limits
- Provides callbacks for avatar change events
### Props
| Prop | Description |
|------|-------------|
| `children` | Child components that will have access to the avatar context |
| `options` | Configuration options for avatar management |
### AvatarOptions
| Option | Description |
|--------|-------------|
| `persist` | Whether to persist avatars to localStorage |
| `customColors` | Custom color palette for avatar generation |
| `maxCacheSize` | Maximum number of cached avatars (0 = unlimited) |
| `onError` | Error handler callback |
### Example
#### React
```
import { AvatarProvider } from '@ably/chat-react-ui-kit';
console.error('Avatar error:', error),
}}
>
;
```
## useAvatar Hook
The `useAvatar` hook provides access to the avatar context with comprehensive avatar management.
### Returns
| Property | Description |
|----------|-------------|
| `getAvatarForUser` | Get avatar for a user if it exists in cache (returns `AvatarData \| undefined`) |
| `createAvatarForUser` | Create avatar for a user and add to cache (returns `AvatarData`) |
| `getAvatarForRoom` | Get avatar for a room if it exists in cache (returns `AvatarData \| undefined`) |
| `createAvatarForRoom` | Create avatar for a room and add to cache (returns `AvatarData`) |
| `setUserAvatar` | Update an existing user avatar or create a new one |
| `setRoomAvatar` | Update an existing room avatar or create a new one |
| `getUserAvatars` | Get all cached user avatars |
| `getRoomAvatars` | Get all cached room avatars |
| `clearUserAvatars` | Clear all user avatars from cache |
| `clearRoomAvatars` | Clear all room avatars from cache |
| `clearAllAvatars` | Clear all avatars from cache |
| `exportAvatars` | Export all avatar data for backup/migration |
| `importAvatars` | Import avatar data from backup/migration |
| `onAvatarChange` | Register a callback for avatar change events |
### Examples
You can use the `useAvatar` hook to manage user and room avatars in your chat application:
#### React
```
import { useState, useEffect, useCallback } from 'react';
import { useAvatar } from '@ably/chat-react-ui-kit';
// Basic usage - getAvatarForUser returns undefined if avatar doesn't exist
function UserAvatar({ clientId, displayName }) {
const { getAvatarForUser, createAvatarForUser } = useAvatar();
const [avatar, setAvatar] = useState(undefined);
// Use useEffect to avoid state mutations during render
useEffect(() => {
const existingAvatar = getAvatarForUser(clientId);
if (existingAvatar) {
setAvatar(existingAvatar);
} else {
const newAvatar = createAvatarForUser(clientId, displayName);
setAvatar(newAvatar);
}
}, [getAvatarForUser, createAvatarForUser, clientId, displayName]);
if (!avatar) return null;
return (
{avatar.src ? (
) : (
avatar.initials
)}
);
}
// Setting a user avatar
function UserAvatarManager() {
const { getAvatarForUser, createAvatarForUser, setUserAvatar } = useAvatar();
const [userId] = useState('user-123');
const [displayName] = useState('John Doe');
const [avatar, setAvatar] = useState(undefined);
useEffect(() => {
const existingAvatar = getAvatarForUser(userId);
if (existingAvatar) {
setAvatar(existingAvatar);
} else {
const newAvatar = createAvatarForUser(userId, displayName);
setAvatar(newAvatar);
}
}, [getAvatarForUser, createAvatarForUser, userId, displayName]);
const handleUpdateAvatar = useCallback(() => {
// Update the user's avatar with custom properties
setUserAvatar(userId, {
color: 'bg-blue-500',
initials: 'JD',
src: 'https://example.com/avatar.jpg'
});
}, [setUserAvatar, userId]);
if (!avatar) return null;
return (
{avatar.src ? (
) : (
avatar.initials
)}
{displayName}
User ID: {userId}
);
}
```
You can also use the `useAvatar` hook to manage avatars for rooms, reset avatars, and handle avatar changes:
#### React
```
import { useEffect } from 'react';
import { useAvatar } from '@ably/chat-react-ui-kit';
// Listen for avatar changes
const { onAvatarChange } = useAvatar();
useEffect(() => {
const cleanup = onAvatarChange((type, id, avatar, prev) => {
console.log(`${type} avatar changed for ${id}`);
});
return cleanup;
}, [onAvatarChange]);
```
#### React
```
import { useAvatar } from '@ably/chat-react-ui-kit';
// Backup and restore avatars
const { exportAvatars, importAvatars } = useAvatar();
// Backup all avatars
const backup = exportAvatars();
// Restore from backup
importAvatars(backup);
```
## useUserAvatar Hook
The `useUserAvatar` hook provides a simplified way to manage avatar data for a specific user. On render, it automatically retrieves the current avatar data for the user and provides a function to update it.
If no avatar data exists, it will generate a default avatar based on the user's client ID and display name. Avatar data is stored in a useState, and updates are automatically reflected in the UI.
### Props
| Prop | Description |
|------|-------------|
| `clientId` | The unique identifier for the user |
| `displayName` | Optional human-readable display name for the user |
### Returns
| Property | Description |
|----------|-------------|
| `userAvatar` | The current state of avatar data for the user, kept up-to-date automatically |
| `setUserAvatar` | Function to update the user avatar with new data |
### Example
#### React
```
import { useUserAvatar } from '@ably/chat-react-ui-kit';
// Basic usage
function UserProfile({ userId, name }) {
const { userAvatar, setUserAvatar } = useUserAvatar({
clientId: userId,
displayName: name
});
return (
{userAvatar?.displayName}
);
}
```
## useRoomAvatar Hook
The `useRoomAvatar` hook provides a simplified way to manage avatar data for a specific room. On render, it automatically retrieves the current avatar data for the room and provides a function to update it.
If no avatar data exists, it will generate a default avatar based on the room name and display name. Avatar data is stored in a useState, and updates are automatically reflected in the UI.
### Props
| Prop | Description |
|------|-------------|
| `roomName` | The unique identifier for the room |
| `displayName` | Optional human-readable display name for the room |
### Returns
| Property | Description |
|----------|-------------|
| `roomAvatar` | The current avatar data for the room |
| `setRoomAvatar` | Function to update the room avatar with new data |
### Example
#### React
```
import { useRoomAvatar } from '@ably/chat-react-ui-kit';
// Basic usage
function RoomHeader({ roomId, roomTitle }) {
const { roomAvatar, setRoomAvatar } = useRoomAvatar({
roomName: roomId,
displayName: roomTitle
});
return (
{roomAvatar?.displayName}
);
}
```
## Related Topics
- [Overview](https://ably.com/docs/chat/react-ui-kit.md?source=llms.txt): Learn more about the Ably Chat React UI Kit and how to use it to quickly build chat interfaces in your React applications.
- [Setup](https://ably.com/docs/chat/react-ui-kit/setup.md?source=llms.txt): Install, configure and instantiate the Chat React UI Kit.
- [Components](https://ably.com/docs/chat/react-ui-kit/components.md?source=llms.txt): Comprehensive documentation for the Ably Chat React UI Kit.
- [Customisation](https://ably.com/docs/chat/react-ui-kit/component-styling.md?source=llms.txt): A guide to styling components in the Ably Chat React UI Kit with and without Tailwind CSS.
## Documentation Index
To discover additional Ably documentation:
1. Fetch [llms.txt](https://ably.com/llms.txt?source=llms.txt) for the canonical list of available pages.
2. Identify relevant URLs from that index.
3. Fetch target pages as needed.
Avoid using assumed or outdated documentation paths.