bigbuffet-rw/app/soapbox/reducers/chat_message_lists.js

67 lines
2.1 KiB
JavaScript
Raw Normal View History

import {
CHATS_FETCH_SUCCESS,
CHAT_MESSAGES_FETCH_SUCCESS,
CHAT_MESSAGE_SEND_REQUEST,
CHAT_MESSAGE_SEND_SUCCESS,
CHAT_MESSAGE_DELETE_SUCCESS,
} from 'soapbox/actions/chats';
2020-08-26 15:29:22 -07:00
import { STREAMING_CHAT_UPDATE } from 'soapbox/actions/streaming';
import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet } from 'immutable';
const initialState = ImmutableMap();
const idComparator = (a, b) => {
2020-09-07 14:07:05 -07:00
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
const updateList = (state, chatId, messageIds) => {
2020-08-26 14:54:44 -07:00
const ids = state.get(chatId, ImmutableOrderedSet());
const newIds = ids.union(messageIds).sort(idComparator);
return state.set(chatId, newIds);
};
const importMessage = (state, chatMessage) => {
return updateList(state, chatMessage.chat_id, [chatMessage.id]);
};
const importMessages = (state, chatMessages) => (
state.withMutations(map =>
chatMessages.forEach(chatMessage =>
importMessage(map, chatMessage)))
);
const importLastMessages = (state, chats) =>
state.withMutations(mutable =>
2020-08-26 18:20:14 -07:00
chats.forEach(chat => {
if (chat.last_message) importMessage(mutable, chat.last_message);
}));
const replaceMessage = (state, chatId, oldId, newId) => {
2020-09-29 14:50:57 -07:00
return state.update(chatId, chat => chat.delete(oldId).add(newId).sort(idComparator));
};
export default function chatMessageLists(state = initialState, action) {
switch(action.type) {
case CHAT_MESSAGE_SEND_REQUEST:
return updateList(state, action.chatId, [action.uuid]);
case CHATS_FETCH_SUCCESS:
return importLastMessages(state, action.chats);
2020-08-26 15:29:22 -07:00
case STREAMING_CHAT_UPDATE:
2020-08-26 22:24:11 -07:00
if (action.chat.last_message &&
action.chat.last_message.account_id !== action.me)
return importMessages(state, [action.chat.last_message]);
2020-08-26 18:20:14 -07:00
else
2020-08-26 22:24:11 -07:00
return state;
case CHAT_MESSAGES_FETCH_SUCCESS:
return updateList(state, action.chatId, action.chatMessages.map(chat => chat.id));
case CHAT_MESSAGE_SEND_SUCCESS:
return replaceMessage(state, action.chatId, action.uuid, action.chatMessage.id);
case CHAT_MESSAGE_DELETE_SUCCESS:
return state.update(action.chatId, chat => chat.delete(action.messageId));
default:
2020-08-26 22:24:11 -07:00
return state;
}
};