Browse Source

sortChat - I did it

sheva77 3 years ago
parent
commit
548c3a141b

+ 1 - 1
chat_final_bootstrap/src/Actions/ActionLogin.js

@@ -49,7 +49,7 @@ export const actionUserInfo = (userId) => async (dispatch) => {
         dispatch(actionAuthInfo(userData.data.UserFindOne)); // получить доп инфу о юзере
         if (userData.data.UserFindOne.chats) {
             userData.data.UserFindOne.chats.forEach(async (chat) => {
-                // получить по 10 первых сообщений и каждого из моих чатов
+                // получить по 10 первых сообщений из каждого из моих чатов
                 await dispatch(actionSearchMessagesByChatId(chat._id));
             });
         }

+ 3 - 11
chat_final_bootstrap/src/Actions/ActionsGql.js

@@ -103,6 +103,9 @@ export const actionSearchMessagesByChatId = (_chatId, skip = 0, searchStr = "",
             // и поменять в store.auth.chats в соответствующем чате поле createdAt на данные
             // из поля createdAt последнего прибывшего сообщения
             // теперь store.auth.chats...createdAt будет говорить о дате последнего изменения в этом чате
+            // надо для сортировки списка чатов
+            // а ыообще надо "попросить" backend-ера внести в сущность Chat поле "lastModified"
+            // либо "lastMessageCreatedAt" - снимет кучу проблем
 
             // console.log("MessageFind", _chatId, messages.data.MessageFind[messages.data.MessageFind.length - 1].createdAt);
 
@@ -140,17 +143,6 @@ export const actionSearchMessagesByChatId = (_chatId, skip = 0, searchStr = "",
     }
 };
 
-const messageCountByChatId = async (id) => {
-    let count = await gql(
-        `query MessageCountByChatId ($chatId:String){
-            MessageCount(query: $chatId)
-        }`,
-        { chatId: JSON.stringify([{ "chat._id": id }]) }
-    );
-
-    // if (!count.data.errors) setRes(count.data.MessageCount);
-};
-
 // получить все сообщения из чата с такм-то _id
 export const actionGetMessagesByChatId = (_chatId) => async (dispatch) => {
     let ChatFindOne = await dispatch(

+ 1 - 1
chat_final_bootstrap/src/Actions/ActionsMsg.js

@@ -13,7 +13,7 @@ export const actionMsgInsertInHead = (msgArr) => {
 export const actionCurChatId = (curChatId) => ({ type: "CURRENTID", curChatId });
 
 export const actionUpdateChatCreatedAt = (_chatId, lastMsgCreatedAt) => ({
-    type: "UPDATE_CHAT_CREATEDAT",
+    type: "UPDATE_CHAT_LASTMODIFIED",
     _chatId,
     lastMsgCreatedAt,
 });

+ 2 - 9
chat_final_bootstrap/src/Components/ChatMessages.js

@@ -87,6 +87,7 @@ const MessagesList = ({ messages, myId, chatId, getMoreMessages = null }) => {
     // console.log(isNeedMoreMessages.current, arrayOfMessages && arrayOfMessages.length);
 
     // скролл в самый низ при приходе новых сообщений, scrollIntoView({ behavior: "smooth" }) - плавно
+    // от плавности прийдется отказаться, так как успевает сработатьт запрос на чтение новой порции сообщений
     const scrollToBottom = () => {
         if (height - offset < 10) {
             messagesEndRef.current.scrollIntoView();
@@ -151,16 +152,8 @@ const CMessagesList = connect(
 const Messages = ({ _id = "", chatInfo, messages, getMsg }) => {
     if (chatInfo) chatInfo = chatInfo.filter((chat) => chat._id === _id);
 
-    // id чата,
-
-    // console.log("Messages - id - ", _id);
-    // console.log(
-    //     "Messages - - ",
-    //     !(messages && messages[_id] && messages[_id][0] && messages[_id][0].chat && messages[_id][0].chat._id)
-    // );
-
     let avatar = chatInfo && chatInfo[0] && chatInfo[0].avatar && chatInfo[0].avatar.url;
-    let title = chatInfo && chatInfo[0] && chatInfo[0].title.trim();
+    let title = chatInfo && chatInfo[0] && chatInfo[0].title && chatInfo[0].title.trim();
 
     useEffect(() => {
         if (

+ 0 - 18
chat_final_bootstrap/src/Components/ChatsList.js

@@ -60,28 +60,10 @@ const ChatItem = ({ _id = "", avatar, title, currentChatId }) => {
 };
 
 const List = ({ arrayOfChats, userId, currentChatId }) => {
-    // console.log(arrayOfChats, msgsObj);
     // arrayOfChats - массив всех чатов пользователя
 
     if (!arrayOfChats) return <></>;
 
-    // сортировка массива чатов по полю createdAt
-    // у кого createdAt больше (свежее) - тот в начало массива
-    // надо "попросить" backend-ера внести в сущность Chat поле "lastModified"
-    // либо "lastMessageCreatedAt"
-
-    // arrayOfChats.sort((a, b) => {
-    //     if (!a.messages) return 1;
-    //     if (!b.messages) return -1;
-    //     return +b.messages[b.messages.length - 1].createdAt - +a.messages[a.messages.length - 1].createdAt;
-    // });
-
-    //FIXME:
-    arrayOfChats.sort((a, b) => b.createdAt - a.createdAt);
-
-    // console.log("chatsList - arrayOfChats.sort: ", arrayOfChats);
-    // console.log("chatsList - : ", currentChatId);
-
     return (
         <ul className="list-group" role="tablist">
             {arrayOfChats.map((a) => (

+ 0 - 1
chat_final_bootstrap/src/Pages/PageMain.js

@@ -18,7 +18,6 @@ const MessageInput = ({ curChatId: { curChatId } = {}, messageUpsert }) => {
 
     // отправка по Enter
     const sendMsgByEnterKey = (e) => {
-        console.log(e);
         if (["NumpadEnter", "Enter"].includes(e.code) && !e.shiftKey && text.trim()) {
             sendMsg();
         }

+ 19 - 5
chat_final_bootstrap/src/Reducers/index.js

@@ -42,7 +42,8 @@ function authReducer(state, action) {
 
     if (action.type === "INFO") {
         // console.log("INFO **************** ", action.userInfo);
-        return {
+
+        let tempObj = {
             ...state,
             payload: action.userInfo.login,
             payloadId: action.userInfo._id,
@@ -50,19 +51,33 @@ function authReducer(state, action) {
             avatarUrl: action.userInfo.url,
             chats: action.userInfo.chats,
         };
+
+        // для сортировки чатов по дате
+        if (Array.isArray(tempObj.chats)) {
+            tempObj.chats = tempObj.chats.map((chat) => {
+                chat.lastModified = chat.createdAt;
+                return chat;
+            });
+        }
+
+        return { ...tempObj };
     }
 
     // для корректной сортировки чатов по дате последнего сообщения
-    if (action.type === "UPDATE_CHAT_CREATEDAT") {
+    if (action.type === "UPDATE_CHAT_LASTMODIFIED") {
         if (Array.isArray(state.chats)) {
             for (let i in state.chats) {
-                if (state.chats[i]._id === action._chatId) {
+                if (state.chats[i]._id === action._chatId && state.chats[i].lastModified < action.lastMsgCreatedAt) {
                     // надо пересобрать объект, чтобы React "почуствовал" изменения
-                    state.chats[i] = { ...state.chats[i], createdAt: action.lastMsgCreatedAt };
+                    state.chats[i] = { ...state.chats[i], lastModified: action.lastMsgCreatedAt };
                 }
             }
         }
 
+        if (Array.isArray(state.chats)) {
+            state.chats.sort((a, b) => b.lastModified - a.lastModified);
+        }
+
         // теперь пересобрать массив, чтобы React "почуствовал" изменения
         if (Array.isArray(state.chats)) {
             state.chats = [...state.chats];
@@ -102,7 +117,6 @@ function msgReduser(state = {}, action) {
 }
 
 function newChatUsersReduser(state = {}, action) {
-    // console.log(action);
     if (["LOGOUT", "LOGIN"].includes(action.type)) return {};
 
     if (action.type === "ADD_USER_TO_CHAT_LIST") {