-
Notifications
You must be signed in to change notification settings - Fork 346
/
Copy pathuseConverseAck.ts
56 lines (49 loc) · 1.5 KB
/
useConverseAck.ts
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
import { useRef } from 'react';
import { useAppDispatch, useAppSelector } from './useAppSelector';
import _debounce from 'lodash/debounce';
import { isValidStr } from '../../utils/string-helper';
import { chatActions } from '../slices';
import { updateAck } from '../../model/converse';
import { useEvent } from '../../hooks/useEvent';
const updateAckDebounce = _debounce(
(converseId: string, lastMessageId: string) => {
updateAck(converseId, lastMessageId);
},
1000,
{ leading: true, trailing: true }
);
/**
* 会话已读信息管理
*/
export function useConverseAck(converseId: string) {
const dispatch = useAppDispatch();
const converseLastMessage = useAppSelector(
(state) => state.chat.lastMessageMap[converseId]
);
const lastMessageIdRef = useRef('');
lastMessageIdRef.current = useAppSelector(
(state) => state.chat.ack[converseId] ?? ''
);
/**
* 更新会话最新消息
*/
const updateConverseAck = useEvent((lastMessageId: string) => {
if (
isValidStr(lastMessageIdRef.current) &&
lastMessageId <= lastMessageIdRef.current
) {
// 更新的数字比较小,跳过
return;
}
dispatch(chatActions.setConverseAck({ converseId, lastMessageId }));
updateAckDebounce(converseId, lastMessageId);
lastMessageIdRef.current = lastMessageId;
});
/**
* 标记为会话已读
*/
const markConverseAllAck = useEvent(() => {
updateConverseAck(converseLastMessage);
});
return { updateConverseAck, markConverseAllAck };
}