# Providers and Hooks This page documents the providers and hooks available in the Ably Chat React UI Kit. These providers and hooks are used to manage state and provide functionality to the components. ## Provider Setup The components in the Ably Chat React UI Kit rely on several React context providers to provide necessary state and context. The `ChatClientProvider` is the core provider that manages access to the Ably Chat client, and should be placed at the root of your application. Other providers like the `ChatSettingsProvider`, `ThemeProvider` and `AvatarProvider` can be used to manage themes, avatars, and chat settings respectively. These providers should be placed at the highest level of any component tree that contains Chat UI components. ### 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': { allowMessageUpdates: false, allowMessageDeletes: 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.allowMessageUpdates) { // 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 | | `getAvatarForRoom` | Get avatar for a room | | `setUserAvatar` | Set avatar for a user | | `setRoomAvatar` | Set avatar for a room | | `resetUserAvatar` | Reset avatar for a user | | `resetRoomAvatar` | Reset avatar for a room | | `exportAvatars` | Export all avatars as a JSON string | | `importAvatars` | Import avatars from a JSON string | | `onAvatarChange` | Register an avatar change callback | ### Examples You can use the `useAvatar` hook to manage user and room avatars in your chat application: #### React ``` import { useState, useCallback } from 'react'; import { useAvatar } from '@ably/chat-react-ui-kit'; // Basic usage function UserAvatar({ clientId, displayName }) { const { getAvatarForUser } = useAvatar(); const avatar = getAvatarForUser(clientId, displayName); return (
{avatar.src ? ( {displayName} ) : ( avatar.initials )}
); } // Setting a user avatar function UserAvatarManager() { const { getAvatarForUser, setUserAvatar } = useAvatar(); const [userId] = useState('user-123'); const [displayName] = useState('John Doe'); const avatar = getAvatarForUser(userId, displayName); const handleAddUser = useCallback(() => { // When adding a new user, set their avatar with custom properties setUserAvatar(userId, { color: 'bg-blue-500', initials: 'JD', src: 'https://example.com/avatar.jpg' }); }, [setUserAvatar, userId]); return (
{avatar.src ? ( {displayName} ) : ( 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}

); } ```