-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathuseChannelPreviewDisplayAvatar.ts
More file actions
70 lines (60 loc) · 2.01 KB
/
useChannelPreviewDisplayAvatar.ts
File metadata and controls
70 lines (60 loc) · 2.01 KB
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
68
69
70
import { useMemo } from 'react';
import type { Channel, StreamChat } from 'stream-chat';
import { useChatContext } from '../../../contexts/chatContext/ChatContext';
import type { DefaultStreamChatGenerics } from '../../../types/types';
export const getChannelPreviewDisplayAvatar = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
>(
channel: Channel<StreamChatGenerics>,
client: StreamChat<StreamChatGenerics>,
) => {
const currentUserId = client?.user?.id;
const channelId = channel?.id;
const channelData = channel?.data;
const channelName = channelData?.name;
const channelImage = channelData?.image;
if (channelImage) {
return {
id: channelId,
image: channelImage,
name: channelName,
};
} else if (currentUserId) {
const members = Object.values(channel.state?.members);
const otherMembers = members.filter((member) => member.user?.id !== currentUserId);
if (otherMembers.length === 1) {
return {
id: otherMembers[0].user?.id,
image: otherMembers[0].user?.image,
name: channelName || otherMembers[0].user?.name,
};
}
return {
ids: otherMembers.slice(0, 4).map((member) => member.user?.id || ''),
images: otherMembers.slice(0, 4).map((member) => member.user?.image || ''),
names: otherMembers.slice(0, 4).map((member) => member.user?.name || ''),
};
}
return {
id: channelId,
name: channelName,
};
};
/**
* Hook to set the display avatar for channel preview
* @param {*} channel
*
* @returns {object} e.g., { image: 'http://dummyurl.com/test.png', name: 'Uhtred Bebbanburg' }
*/
export const useChannelPreviewDisplayAvatar = <
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics,
>(
channel: Channel<StreamChatGenerics>,
) => {
const { client } = useChatContext<StreamChatGenerics>();
const displayAvatar = useMemo(
() => getChannelPreviewDisplayAvatar(channel, client),
[channel, client],
);
return displayAvatar;
};