优化
This commit is contained in:
67
client/shared/redux/hooks/useConverseAck.ts
Normal file
67
client/shared/redux/hooks/useConverseAck.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { useRef } from 'react';
|
||||
import { useAppDispatch, useAppSelector } from './useAppSelector';
|
||||
import _debounce from 'lodash/debounce';
|
||||
import { isLocalMessageId, isValidStr } from '../../utils/string-helper';
|
||||
import { chatActions } from '../slices';
|
||||
import { updateAck } from '../../model/converse';
|
||||
import { useMemoizedFn } from '../../hooks/useMemoizedFn';
|
||||
|
||||
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 setConverseAck = useMemoizedFn(
|
||||
(converseId: string, lastMessageId: string) => {
|
||||
if (isLocalMessageId(lastMessageId)) {
|
||||
// 跳过本地消息
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
isValidStr(lastMessageIdRef.current) &&
|
||||
lastMessageId <= lastMessageIdRef.current
|
||||
) {
|
||||
// 更新的数字比较小,跳过
|
||||
return;
|
||||
}
|
||||
|
||||
dispatch(chatActions.setConverseAck({ converseId, lastMessageId }));
|
||||
updateAckDebounce(converseId, lastMessageId);
|
||||
lastMessageIdRef.current = lastMessageId;
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* 更新会话最新消息
|
||||
*/
|
||||
const updateConverseAck = useMemoizedFn((lastMessageId: string) => {
|
||||
setConverseAck(converseId, lastMessageId);
|
||||
});
|
||||
|
||||
/**
|
||||
* 标记为会话已读
|
||||
*/
|
||||
const markConverseAllAck = useMemoizedFn(() => {
|
||||
updateConverseAck(converseLastMessage);
|
||||
});
|
||||
|
||||
return { updateConverseAck, markConverseAllAck };
|
||||
}
|
||||
Reference in New Issue
Block a user