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

59 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-01-10 14:01:24 -08:00
import { Map as ImmutableMap, fromJS } from 'immutable';
2020-08-25 19:31:34 -07:00
import {
2020-08-26 15:29:22 -07:00
CHATS_FETCH_SUCCESS,
CHATS_EXPAND_SUCCESS,
2020-08-25 19:31:34 -07:00
CHAT_MESSAGES_FETCH_SUCCESS,
CHAT_MESSAGE_SEND_REQUEST,
2020-08-25 19:31:34 -07:00
CHAT_MESSAGE_SEND_SUCCESS,
CHAT_MESSAGE_DELETE_REQUEST,
CHAT_MESSAGE_DELETE_SUCCESS,
2020-08-25 19:31:34 -07:00
} from 'soapbox/actions/chats';
2020-08-26 15:29:22 -07:00
import { STREAMING_CHAT_UPDATE } from 'soapbox/actions/streaming';
2020-08-25 18:33:49 -07:00
const initialState = ImmutableMap();
2020-08-26 11:39:38 -07:00
const importMessage = (state, message) => {
return state.set(message.get('id'), message);
2020-08-26 11:39:38 -07:00
};
const importMessages = (state, messages) =>
state.withMutations(mutable =>
messages.forEach(message => importMessage(mutable, message)));
2020-08-26 11:39:38 -07:00
const importLastMessages = (state, chats) =>
state.withMutations(mutable =>
2020-08-26 18:20:14 -07:00
chats.forEach(chat => {
if (chat.get('last_message'))
importMessage(mutable, chat.get('last_message'));
}));
2020-08-26 11:39:38 -07:00
2020-08-25 18:33:49 -07:00
export default function chatMessages(state = initialState, action) {
switch(action.type) {
case CHAT_MESSAGE_SEND_REQUEST:
return importMessage(state, fromJS({
id: action.uuid, // Make fake message to get overriden later
chat_id: action.chatId,
account_id: action.me,
content: action.params.content,
created_at: (new Date()).toISOString(),
pending: true,
}));
2020-08-26 15:29:22 -07:00
case CHATS_FETCH_SUCCESS:
case CHATS_EXPAND_SUCCESS:
return importLastMessages(state, fromJS(action.chats));
2020-08-25 18:33:49 -07:00
case CHAT_MESSAGES_FETCH_SUCCESS:
return importMessages(state, fromJS(action.chatMessages));
case CHAT_MESSAGE_SEND_SUCCESS:
return importMessage(state, fromJS(action.chatMessage)).delete(action.uuid);
2020-08-26 15:29:22 -07:00
case STREAMING_CHAT_UPDATE:
return importLastMessages(state, fromJS([action.chat]));
case CHAT_MESSAGE_DELETE_REQUEST:
return state.update(action.messageId, chatMessage =>
chatMessage.set('pending', true).set('deleting', true));
case CHAT_MESSAGE_DELETE_SUCCESS:
return state.delete(action.messageId);
2020-08-25 18:33:49 -07:00
default:
return state;
}
2021-08-03 12:22:51 -07:00
}