Providers and Hooks

This page documents the providers and hooks available in the Ably Chat React UI Components library. These providers and hooks are used to manage state and provide functionality to the components.

Provider Setup

The Ably Chat React UI Components 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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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-components';

// Create Ably Realtime client
const ablyClient = new Ably.Realtime({
  key: '{{API_KEY}}', // Replace with your Ably API key
  clientId: 'your-chat-client-id',
});

const chatClient = new ChatClient(ablyClient);

function App() {
  return (
    <ChatClientProvider client={chatClient}>
      <ChatSettingsProvider>
        <ThemeProvider>
          <AvatarProvider>
            {/* Your Chat UI components */}
          </AvatarProvider>
        </ThemeProvider>
      </ChatSettingsProvider>
    </ChatClientProvider>
  );
}

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

PropDescription
childrenChild components that will have access to chat settings
initialGlobalSettingsInitial global settings (merged with defaults)
initialRoomSettingsInitial room-specific settings mapping

ChatSettings

SettingDescription
allowMessageUpdatesOwnWhether users can update their messages after sending
allowMessageUpdatesAnyWhether users can update any message in the room
allowMessageDeletesOwnWhether users can delete their messages
allowMessageDeletesAnyWhether users can delete any message in the room
allowMessageReactionsWhether users can add reactions to messages

Example

React

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import { ChatSettingsProvider } from '@ably/chat-react-ui-components';
const globalSettings = {
  allowMessageUpdatesOwn: false,
  allowMessageDeletesOwn: true,
  allowMessageReactions: true,
};

const roomSettings = {
  'general': { allowMessageUpdatesOwn: true },
  'announcements': {
    allowMessageUpdates: false,
    allowMessageDeletes: false,
  },
};

  <ChatSettingsProvider
    initialGlobalSettings={globalSettings}
    initialRoomSettings={roomSettings}>
    <ChatApp />
  </ChatSettingsProvider>;

useChatSettings Hook

The useChatSettings hook provides access to the chat settings context.

Returns

PropertyDescription
globalSettingsGlobal settings that apply to all rooms
roomSettingsRoom-specific settings mapping
getEffectiveSettingsFunction to get effective settings for a room

Example

React

1

2

3

4

5

6

7

8

9

10

import { useChatSettings } from '@ably/chat-react-ui-components';
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

PropDescription
childrenChild components that will have access to the theme context
optionsConfiguration options for theme management
onThemeChangeCallback fired when the theme changes

ThemeOptions

OptionDescription
persistWhether to persist theme preference to localStorage
detectSystemThemeWhether to detect and use system theme preference
defaultThemeInitial theme to use if no preference is found (light/dark)

Example

React

1

2

3

4

5

6

7

8

9

10

11

12

13

import { ThemeProvider } from '@ably/chat-react-ui-components';
<ThemeProvider
  options={{
    persist: true,
    detectSystemTheme: true,
    defaultTheme: 'dark'
  }}
  onThemeChange={(theme, prev) => {
    console.log(`Theme changed from ${prev} to ${theme}`);
  }}
>
  <ChatApplication />
</ThemeProvider>

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

PropertyDescription
themeCurrent theme (light/dark)
setThemeFunction to set the theme
toggleThemeFunction to toggle between light and dark themes
isDarkWhether the current theme is dark
isLightWhether the current theme is light
supportsSystemThemeWhether the browser supports system theme detection
getSystemThemeFunction to get the current system theme
resetToSystemThemeFunction to reset to the system theme
onThemeChangeFunction to register a theme change callback

Examples

React

1

2

3

4

5

6

7

8

9

10

11

12

// Basic theme usage
import { useTheme } from '@ably/chat-react-ui-components';
const { theme, toggleTheme } = useTheme();

return (
  <button
    onClick={toggleTheme}
    className={theme === 'dark' ? 'bg-gray-800' : 'bg-white'}
  >
    Switch to {theme === 'dark' ? 'Light' : 'Dark'} Mode
  </button>
);
React

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// Using boolean helpers
import { useTheme } from '@ably/chat-react-ui-components';
const { isDark, setTheme } = useTheme();

return (
  <div className={isDark ? 'dark-mode' : 'light-mode'}>
    <button onClick={() => setTheme('light')}>
      Light Mode
    </button>
    <button onClick={() => setTheme('dark')}>
      Dark Mode
    </button>
  </div>
);
React

1

2

3

4

5

6

7

8

9

10

11

12

13

// System theme integration
import { useTheme } from '@ably/chat-react-ui-components';
const { supportsSystemTheme, getSystemTheme, resetToSystemTheme } = useTheme();

return (
  <div>
    {supportsSystemTheme && (
      <button onClick={resetToSystemTheme}>
        Use System Theme ({getSystemTheme()})
      </button>
    )}
  </div>
);
React

1

2

3

4

5

6

7

8

9

10

11

12

13

// Theme change notifications
import { useEffect } from 'react';
import { useTheme } from '@ably/chat-react-ui-components';
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

PropDescription
childrenChild components that will have access to the avatar context
optionsConfiguration options for avatar management

AvatarOptions

OptionDescription
persistWhether to persist avatars to localStorage
customColorsCustom color palette for avatar generation
maxCacheSizeMaximum number of cached avatars (0 = unlimited)
onErrorError handler callback

Example

React

1

2

3

4

5

6

7

8

9

10

11

import { AvatarProvider } from '@ably/chat-react-ui-components';
<AvatarProvider
  options={{
    persist: true,
    customColors: ['bg-blue-500', 'bg-red-500', 'bg-green-500'],
    maxCacheSize: 50,
    onError: (error) => console.error('Avatar error:', error),
  }}
>
  <ChatApplication />
</AvatarProvider>;

useAvatar Hook

The useAvatar hook provides access to the avatar context with comprehensive avatar management.

Returns

PropertyDescription
getAvatarForUserGet avatar for a user
getAvatarForRoomGet avatar for a room
setUserAvatarSet avatar for a user
setRoomAvatarSet avatar for a room
resetUserAvatarReset avatar for a user
resetRoomAvatarReset avatar for a room
exportAvatarsExport all avatars as a JSON string
importAvatarsImport avatars from a JSON string
onAvatarChangeRegister an avatar change callback

Examples

You can use the useAvatar hook to manage user and room avatars in your chat application:

React

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

import { useState, useCallback } from 'react';
import { useAvatar } from '@ably/chat-react-ui-components';

// Basic usage
function UserAvatar({ clientId, displayName }) {
  const { getAvatarForUser } = useAvatar();
  const avatar = getAvatarForUser(clientId, displayName);

  return (
    <div className={`w-10 h-10 rounded-full flex items-center justify-center text-white font-medium ${avatar.color}`}>
      {avatar.src ? (
        <img
          src={avatar.src}
          alt={displayName}
          className="w-full h-full rounded-full object-cover"
        />
      ) : (
        avatar.initials
      )}
    </div>
  );
}

// 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 (
    <div className="p-4 space-y-4">
      <div className="flex items-center gap-4">
        <div className={`w-16 h-16 rounded-full flex items-center justify-center text-white font-medium ${avatar.color}`}>
          {avatar.src ? (
            <img src={avatar.src} alt={displayName} className="w-full h-full rounded-full object-cover" />
          ) : (
            avatar.initials
          )}
        </div>
        <div>
          <div className="font-medium">{displayName}</div>
          <div className="text-sm text-gray-500">User ID: {userId}</div>
        </div>
      </div>

      <div className="flex gap-2">
        <button
          onClick={handleAddUser}
          className="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600"
        >
          Add User
        </button>
      </div>
    </div>
  );
}

You can also use the useAvatar hook to manage avatars for rooms, reset avatars, and handle avatar changes:

React

1

2

3

4

5

6

7

8

9

10

11

12

import { useEffect } from 'react';
import { useAvatar } from '@ably/chat-react-ui-components';
// 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

1

2

3

4

5

6

7

8

9

import { useAvatar } from '@ably/chat-react-ui-components';
// 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

PropDescription
clientIdThe unique identifier for the user
displayNameOptional human-readable display name for the user

Returns

PropertyDescription
userAvatarThe current state of avatar data for the user, kept up-to-date automatically
setUserAvatarFunction to update the user avatar with new data

Example

React

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

import { useUserAvatar } from '@ably/chat-react-ui-components';

// Basic usage
function UserProfile({ userId, name }) {
  const { userAvatar, setUserAvatar } = useUserAvatar({
    clientId: userId,
    displayName: name
  });

  return (
    <div className="flex items-center gap-3">
      <Avatar
        src={userAvatar?.src}
        color={userAvatar?.color}
        initials={userAvatar?.initials}
        alt={userAvatar?.displayName}
      />
      <div>
        <h3>{userAvatar?.displayName}</h3>
        <button
          onClick={() => setUserAvatar({
            color: 'bg-blue-500',
            src: 'https://example.com/new-avatar.jpg'
          })}
        >
          Update Avatar
        </button>
      </div>
    </div>
  );
}

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

PropDescription
roomNameThe unique identifier for the room
displayNameOptional human-readable display name for the room

Returns

PropertyDescription
roomAvatarThe current avatar data for the room
setRoomAvatarFunction to update the room avatar with new data

Example

React

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

import { useRoomAvatar } from '@ably/chat-react-ui-components';

// Basic usage
function RoomHeader({ roomId, roomTitle }) {
  const { roomAvatar, setRoomAvatar } = useRoomAvatar({
    roomName: roomId,
    displayName: roomTitle
  });

  return (
    <div className="flex items-center gap-3">
      <Avatar
        src={roomAvatar?.src}
        color={roomAvatar?.color}
        initials={roomAvatar?.initials}
        alt={roomAvatar?.displayName}
      />
      <h2>{roomAvatar?.displayName}</h2>
      <button
        onClick={() => setRoomAvatar({
          displayName: 'Updated Room Name',
          color: 'bg-green-500'
        })}
      >
        Edit Room
      </button>
    </div>
  );
}
Select...