@@ -2,42 +2,70 @@ import { useEffect } from 'react';
22
33import uniqBy from 'lodash/uniqBy' ;
44
5- import type { Channel , Event } from 'stream-chat' ;
5+ import type { Channel , ChannelFilters , ChannelSort , Event } from 'stream-chat' ;
66
77import { useChatContext } from '../../../../contexts/chatContext/ChatContext' ;
88
99import type { DefaultStreamChatGenerics } from '../../../../types/types' ;
1010import { getChannel } from '../../utils' ;
11+ import { findLastPinnedChannelIndex , findPinnedAtSortOrder } from '../utils' ;
1112
1213type Parameters < StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics > =
1314 {
1415 setChannels : React . Dispatch < React . SetStateAction < Channel < StreamChatGenerics > [ ] | null > > ;
1516 onAddedToChannel ?: (
1617 setChannels : React . Dispatch < React . SetStateAction < Channel < StreamChatGenerics > [ ] | null > > ,
1718 event : Event < StreamChatGenerics > ,
19+ filters ?: ChannelFilters < StreamChatGenerics > ,
20+ sort ?: ChannelSort < StreamChatGenerics > ,
1821 ) => void ;
22+ filters ?: ChannelFilters < StreamChatGenerics > ;
23+ sort ?: ChannelSort < StreamChatGenerics > ;
1924 } ;
2025
2126export const useAddedToChannelNotification = <
2227 StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics ,
2328> ( {
2429 onAddedToChannel,
2530 setChannels,
31+ filters,
32+ sort,
2633} : Parameters < StreamChatGenerics > ) => {
2734 const { client } = useChatContext < StreamChatGenerics > ( ) ;
2835
2936 useEffect ( ( ) => {
3037 const handleEvent = async ( event : Event < StreamChatGenerics > ) => {
3138 if ( typeof onAddedToChannel === 'function' ) {
32- onAddedToChannel ( setChannels , event ) ;
39+ onAddedToChannel ( setChannels , event , filters , sort ) ;
3340 } else {
3441 if ( event . channel ?. id && event . channel ?. type ) {
3542 const channel = await getChannel < StreamChatGenerics > ( {
3643 client,
3744 id : event . channel . id ,
3845 type : event . channel . type ,
3946 } ) ;
40- setChannels ( ( channels ) => ( channels ? uniqBy ( [ channel , ...channels ] , 'cid' ) : channels ) ) ;
47+
48+ const pinnedAtSort = findPinnedAtSortOrder ( { sort } ) ;
49+
50+ setChannels ( ( channels ) => {
51+ if ( ! channels ) return channels ;
52+
53+ // handle pinning
54+ let lastPinnedChannelIndex : number | null = null ;
55+
56+ const newChannels = [ ...channels ] ;
57+
58+ if ( pinnedAtSort === 1 || pinnedAtSort === - 1 ) {
59+ lastPinnedChannelIndex = findLastPinnedChannelIndex ( { channels : newChannels } ) ;
60+ const newTargetChannelIndex =
61+ typeof lastPinnedChannelIndex === 'number' ? lastPinnedChannelIndex + 1 : 0 ;
62+
63+ newChannels . splice ( newTargetChannelIndex , 0 , channel ) ;
64+ return newChannels ;
65+ }
66+
67+ return uniqBy ( [ channel , ...channels ] , 'cid' ) ;
68+ } ) ;
4169 }
4270 }
4371 } ;
0 commit comments