diff --git a/lib/shared/avatar-utils.js b/lib/shared/avatar-utils.js --- a/lib/shared/avatar-utils.js +++ b/lib/shared/avatar-utils.js @@ -1,9 +1,14 @@ // @flow +import invariant from 'invariant'; import stringHash from 'string-hash'; import { selectedThreadColors } from './thread-utils.js'; +import { threadInfoSelector } from '../selectors/thread-selectors.js'; import type { ClientEmojiAvatar, ClientAvatar } from '../types/avatar-types.js'; +import { type ThreadType, threadTypes } from '../types/thread-types.js'; +import { useResolvedOptionalThreadInfo } from '../utils/entity-helpers.js'; +import { useSelector } from '../utils/redux-utils.js'; const defaultAnonymousUserEmojiAvatar: ClientEmojiAvatar = { color: selectedThreadColors[4], @@ -57,4 +62,52 @@ return getDefaultAvatar(user.username); } -export { getAvatarForUser }; +function useGetAvatarForThread( + thread: ?{ + +id: string, + +type: ThreadType, + +avatar?: ?ClientAvatar, + +color: string, + +parentThreadID: ?string, + ... + }, +): ClientAvatar { + const viewer = useSelector(state => state.currentUserInfo); + + const parentThreadID = thread?.parentThreadID; + const parentThreadInfo = useSelector(state => + parentThreadID ? threadInfoSelector(state)[parentThreadID] : null, + ); + const resolvedParentThreadInfo = + useResolvedOptionalThreadInfo(parentThreadInfo); + + if (!thread) { + return defaultAnonymousUserEmojiAvatar; + } + + if (thread.avatar) { + return thread.avatar; + } + + if (thread.type === threadTypes.SIDEBAR) { + invariant( + resolvedParentThreadInfo, + 'parentThreadInfo should be set for sidebars', + ); + + return resolvedParentThreadInfo.avatar + ? resolvedParentThreadInfo.avatar + : getDefaultAvatar( + resolvedParentThreadInfo.id, + resolvedParentThreadInfo.color, + ); + } + + if (thread.type === threadTypes.PRIVATE) { + return getAvatarForUser(viewer); + } + + return getDefaultAvatar(thread.id, thread.color); +} + +export { getAvatarForUser, useGetAvatarForThread }; diff --git a/lib/types/thread-types.js b/lib/types/thread-types.js --- a/lib/types/thread-types.js +++ b/lib/types/thread-types.js @@ -2,6 +2,7 @@ import invariant from 'invariant'; +import type { ClientAvatar } from './avatar-types.js'; import type { Shape } from './core.js'; import type { CalendarQuery, RawEntryInfo } from './entry-types.js'; import type { Media } from './media-types.js'; @@ -212,6 +213,7 @@ +type: ThreadType, +name: ?string, +uiName: string | ThreadEntity, + +avatar?: ?ClientAvatar, +description: ?string, +color: string, // hex, without "#" or "0x" +creationTime: number, // millisecond timestamp @@ -230,6 +232,7 @@ +type: ThreadType, +name: ?string, +uiName: string, + +avatar?: ?ClientAvatar, +description: ?string, +color: string, // hex, without "#" or "0x" +creationTime: number, // millisecond timestamp