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

69 lines
2.3 KiB
TypeScript
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';
import { normalizeChatMessage } from 'soapbox/normalizers';
2020-08-25 18:33:49 -07:00
import type { AnyAction } from 'redux';
type ChatMessageRecord = ReturnType<typeof normalizeChatMessage>;
type APIEntity = Record<string, any>;
type APIEntities = Array<APIEntity>;
2020-08-25 18:33:49 -07:00
type State = ImmutableMap<string, ChatMessageRecord>;
const importMessage = (state: State, message: APIEntity) => {
return state.set(message.id, normalizeChatMessage(message));
2020-08-26 11:39:38 -07:00
};
const importMessages = (state: State, messages: APIEntities) =>
state.withMutations(mutable =>
messages.forEach(message => importMessage(mutable, message)));
const importLastMessages = (state: State, chats: APIEntities) =>
2020-08-26 11:39:38 -07:00
state.withMutations(mutable =>
2020-08-26 18:20:14 -07:00
chats.forEach(chat => {
if (chat.last_message)
importMessage(mutable, chat.last_message);
2020-08-26 18:20:14 -07:00
}));
2020-08-26 11:39:38 -07:00
const initialState: State = ImmutableMap();
export default function chatMessages(state = initialState, action: AnyAction) {
switch (action.type) {
2022-05-11 14:06:35 -07:00
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,
}));
case CHATS_FETCH_SUCCESS:
case CHATS_EXPAND_SUCCESS:
return importLastMessages(state, action.chats);
case CHAT_MESSAGES_FETCH_SUCCESS:
return importMessages(state, action.chatMessages);
case CHAT_MESSAGE_SEND_SUCCESS:
return importMessage(state, fromJS(action.chatMessage)).delete(action.uuid);
case STREAMING_CHAT_UPDATE:
return importLastMessages(state, [action.chat]);
case CHAT_MESSAGE_DELETE_REQUEST:
return state.update(action.messageId, chatMessage =>
chatMessage!.set('pending', true).set('deleting', true));
2022-05-11 14:06:35 -07:00
case CHAT_MESSAGE_DELETE_SUCCESS:
return state.delete(action.messageId);
default:
return state;
2020-08-25 18:33:49 -07:00
}
2021-08-03 12:22:51 -07:00
}