Ivar 3 éve
szülő
commit
f9a20ba9cc

+ 2 - 0
src/actions/chatsActions.js

@@ -74,7 +74,9 @@ export const actionFullChatList = (userId, currentCount, limitCount=50) => (
    async (dispatch) => {
       let payload = await dispatch(actionGetChatsByUser(userId, currentCount, limitCount))
       if (payload) {
+
          await dispatch(actionChatList(payload))
+
       }
    }
 )

+ 7 - 9
src/actions/index.js

@@ -12,17 +12,16 @@ import {
 
    actionFullChatList
 } from './chatsActions'
-
 import {
    actionGetMsgsByChat,
    actionMsgsCount,
    actionSendMsg,
-} from './msgActions'
 
+   actionFullMsgsByChat,
+} from './msgActions'
 import {
    actionUploadFile,
 } from './mediaActions'
-
 import {
    actionFindUsers
 } from './findActions'
@@ -41,19 +40,18 @@ export {
    actionGetChatsByUser,
    actionGetAllChats,
 
-   actionFullChatList
-} 
-
+   actionFullChatList,
+}
 export {
    actionGetMsgsByChat,
    actionMsgsCount,
    actionSendMsg,
-} 
 
+   actionFullMsgsByChat,
+}
 export {
    actionUploadFile,
-} 
-
+}
 export {
    actionFindUsers
 } 

+ 75 - 1
src/actions/msgActions.js

@@ -20,6 +20,9 @@ export const actionGetMsgsByChat = (chatId, skipCount=0, limitCount=50) => (
             login
          }
          text
+         chat {
+            _id
+         }
 
          media {
             url
@@ -39,7 +42,7 @@ export const actionGetMsgsByChat = (chatId, skipCount=0, limitCount=50) => (
          }
       }     
    }`, { 
-         q: JSON.stringify([  { "chat. _id": chatId },
+         q: JSON.stringify([  { "chat._id": chatId },
                               { 
                                  sort: [{_id: -1}],  
                                  skip: [skipCount], 
@@ -50,6 +53,74 @@ export const actionGetMsgsByChat = (chatId, skipCount=0, limitCount=50) => (
    ))
 )
 
+export const actionFullMsgsByChat = (chatId, currentCount, limitCount=50) => (
+   async (dispatch) => {
+      let payload = await dispatch(actionGetMsgsByChat(chatId, currentCount, limitCount))
+      if (payload) {
+         await dispatch(actionMsgList(payload))
+      }
+   }
+)
+
+
+
+
+const actionLastMsgByChat = (chatId) => (
+   actionPromise('lastMsg', gql(`query lastMsg($q: String) {
+      MessageFindOne (query: $q){
+         _id
+         createdAt
+         owner {
+            _id
+            login
+         }
+         text
+         chat {
+            _id
+         }
+
+         media {
+            url
+         }
+         forwardWith {
+            _id
+         }
+         replies {
+            _id
+         }
+
+         replyTo {
+            _id
+         }
+         forwarded {
+            _id
+         }
+      }     
+   }`, { 
+         q: JSON.stringify([  { chat: {_id: chatId} },
+                              { 
+                                 sort: [{_id: -1}]
+                              } 
+                           ])
+      }
+   ))
+)
+
+export const actionGetAllLastMsg = (chats) => (
+   async (dispatch) => {
+
+      let msgReq = chats.map((chat) => dispatch(actionLastMsgByChat(chat._id)))
+      let msgRes = await Promise.all(msgReq)
+
+      if (msgRes) {
+         for (const msg of msgRes) {
+            await dispatch(actionMsgOne(msg))
+         }
+      }
+   }
+)
+
+
 
 
 
@@ -74,6 +145,9 @@ const actionUpdateMsg = (chatId, text, media, msgId) => (
             login
          }
          text
+         chat {
+            _id
+         }
 
          media {
             url

+ 1 - 1
src/components/ChatList.jsx

@@ -14,7 +14,7 @@ import {
  
 const Chat = ({chat}) => {
 
-  let {_id, title, owner, members} = chat
+  const {_id, title, owner, members} = chat
 
   return (
     <Link href={`/main/${_id}`}>

+ 56 - 4
src/components/MsgList.jsx

@@ -1,10 +1,62 @@
-import React, {useState, useEffect, useRef} from 'react';
+import React, {useState, useEffect, useRef} from 'react'
+import Stack from '@mui/material/Stack'
+import Box from '@mui/material/Box'
+
+
 import {connect}  from 'react-redux'
 
+import { actionFullMsgsByChat } from '../actions'
+
+
+const Msg = ({msg}) => {
+
+   const {_id, text} = msg
+
+   return (
+      <>
+         <p>
+            {text}
+         </p> 
+      </>
+   )
+}
+
+
+const MsgList = ({chats, chatId}) => {
+
+   const msgArr =  chats[chatId]?.messages
+
+   return (
+      <Box>
+         <Stack
+            direction="column-reverse"
+            justifyContent="flex-start"
+            alignItems="stretch"
+            spacing={2}
+         >
+            { msgArr ?
+               msgArr.map(msg => <Msg key={msg._id} msg={msg}/>) :
+                  <div>сообщений нема</div>         
+            }  
+
+         </Stack>
+      </Box>
+   )
+}
+const CMsgList = connect(state => ({chats: state.chats}))(MsgList)
+
+
+const MsgListWrapp = ({match:{params:{_id}}, getData}) => {
+   const [msgBlock, setMsgBlock] = useState(0)
+
+   useEffect(() => {
+      getData(_id, msgBlock, 50)
+  },[_id])
 
-const MsgList = ({}) => {
    return (
-      <></>
+      <>
+         <CMsgList chatId={_id} />
+      </>
    )
 }
-export const CMsgList = connect(state => ({chats: state.chats}))(MsgList)
+export const CMsgListWrapp= connect(null, {getData: actionFullMsgsByChat})(MsgListWrapp)

+ 2 - 2
src/components/index.js

@@ -1,6 +1,6 @@
 // универсальные компоненты, повторяющиеся на многих страницах
 import {CChatList} from './ChatList'
-import {} from './MsgList'
+import {CMsgListWrapp} from './MsgList'
 import {CPreloaded} from './Preload'
 import {MainMenu, MenuDrawer} from './MainMenu'
 import {Header} from './Header'
@@ -14,7 +14,7 @@ import {CSendingField} from './SendingField'
 
 
 export {CChatList}
-export {} 
+export {CMsgListWrapp} 
 export {CPreloaded} 
 export {MainMenu, MenuDrawer} 
 export {Header}  

+ 20 - 0
src/pages/ChatsPage.jsx

@@ -0,0 +1,20 @@
+
+
+
+
+
+
+// const ChatsPage = ({}) => {
+
+//    useEffect(() => {
+//       getData(userId)
+//     },[])
+
+//    return (
+//       <>
+//       </>
+//    )
+// }
+// export const CChatList = connect( state => ({userId: state.auth.payload.sub.id || null}),
+//                                              {getData: actionFullChatList}
+//                                                    )(ChatsPage)

+ 15 - 10
src/pages/Main.jsx

@@ -18,7 +18,8 @@ import {
    CChatList, 
    Header, 
    CUserAvatar, 
-   CSendingField
+   CSendingField,
+   CMsgListWrapp
 } from "../components"
 import {
    actionChangePass,
@@ -27,9 +28,9 @@ import {
  import {store} from "../reducers"
 
 
- const Page404 = () => (
-   <h1>Тут ведутся работы</h1>
-   )
+ const PageNoChat = () => (
+   <h1>Выбирай чат</h1>
+ )
 
 const theme = createTheme()
 export const Main = ({}) => {
@@ -67,6 +68,8 @@ export const Main = ({}) => {
                </Grid>
 
                <Grid item xs={12} sm={8}>
+
+
                   <Grid container direction="column" justifyContent="space-between" alignItems="stretch" 
                         height="100vh" sx={{backgroundColor: '#eee'}} >
                      
@@ -79,14 +82,14 @@ export const Main = ({}) => {
                         </Header>                    
                      </Grid>
 
-                     <Grid item sx={{ flexGrow: 1 }} >
+                     <Grid item sx={{ flexGrow: 0, flexShrink: 1, overflowY: "scroll" }} height="calc(100vh - 300px)" >
 
 
                            
-             {/*            <Switch> 
-                           <Route path="/main/:_id" component={} />
-                           <Route path="*" component={} /> 
-                        </Switch> */}
+                        <Switch> 
+                           <Route path="/main/:_id" component={CMsgListWrapp} />
+                           <Route path="*" component={PageNoChat} /> 
+                        </Switch>
 
                      </Grid>
 
@@ -94,7 +97,9 @@ export const Main = ({}) => {
                            <CSendingField />
                      </Grid>
 
-                  </Grid>              
+                  </Grid>  
+                  
+                              
                </Grid>
 
             </Grid>

+ 0 - 0
src/pages/MsgPage.jsx


+ 6 - 0
src/pages/index.js

@@ -2,7 +2,13 @@
 import {Login} from './Login'
 import {Register} from './Register'
 import {Main} from './Main'
+import {CChatsPage} from './ChatsPage'
+import {CMsgPage} from './MsgPage'
+
 
 export {Login} 
 export {Register} 
 export {Main} 
+export {CChatsPage} 
+export {CMsgPage} 
+

+ 48 - 34
src/reducers/chatsReducer.js

@@ -23,27 +23,31 @@
     const types = {
 
       CHATS() {
-        const newChats = {}        
-        for (const chat of payload) {
-          newChats[chat._id] = chat
-        }
+        if (payload && payload.length > 0) {
 
-        const newState = Object.fromEntries(
-          Object.entries({
-            ...state,
-            ...newChats
-          }).sort((a, b) => {
-            if (a[1].lastModified > b[1].lastModified) {
-              return 1
-            }
-            if (a[1].lastModified < b[1].lastModified) {
-              return -1
-            }
-            return 0
-          })
-        )
+          const newChats = {}        
+          for (const chat of payload) {
+            newChats[chat._id] = chat
+          }
 
-        return newState
+          const newState = Object.fromEntries(
+            Object.entries({
+              ...state,
+              ...newChats
+            }).sort((a, b) => {
+              if (a[1].lastModified > b[1].lastModified) {
+                return -1
+              }
+              if (a[1].lastModified < b[1].lastModified) {
+                return 1
+              }
+              return 0
+            })
+          )
+
+          return newState
+        }
+        return state
       },
 
       CHAT_LEFT() {   
@@ -52,25 +56,35 @@
       },
 
       MSGS() {
-        const chatId = payload[0]?.chat?._id
+        if (payload && payload.length > 0) {
+        
+          const chatId = payload[0]?.chat?._id
 
-        const msgState = [...state[chatId]?.messages, ...payload].sort((a, b) => {
-          if (a._id > b._id) {
-            return 1
-          }
-          if (a._id < b._id) {
-            return -1
-          }
-          return 0
-        })
+          // console.log(chatId, state[chatId]?.messages, payload)
 
-        const newState = {
-          ...state,
-          [chatId]: {
-            messages: msgState
+          const msgState = [
+            ...state[chatId]?.messages, 
+            ...payload
+          ].sort((a, b) => {
+            if (a._id > b._id) {
+              return -1
+            }
+            if (a._id < b._id) {
+              return 1
+            }
+            return 0
+          })
+
+          const newState = {
+            ...state,
+            [chatId]: {
+              ...state[chatId],
+              messages: msgState
+            }
           }
+          return newState
         }
-        return newState
+        return state
       }
 
     }

+ 17 - 16
src/reducers/store.js

@@ -12,7 +12,7 @@ import {
    actionChatLeft 
 } from './chatsReducer'
 
-// const { io } = require("socket.io-client");
+const { io } = require("socket.io-client");
 
 export const store =  createStore (  combineReducers({ 
                                     // promise: localStoredReducer(promiseReducer, 'promise'),
@@ -30,24 +30,25 @@ store.dispatch(actionAboutMe())
 store.subscribe(() => console.log(store.getState()))
 
 
-// const socket = io("ws://chat.fs.a-level.com.ua")
+const socket = io("ws://chat.fs.a-level.com.ua")
 
-// if (localStorage.authToken) {
-//    socket.emit('jwt', localStorage.authToken)
-// } 
+if (localStorage.authToken) {
+   socket.emit('jwt', localStorage.authToken)
+} 
 
-// socket.on('jwt_ok',   (data) => console.log(data))
-// socket.on('jwt_fail', (error) => console.log(error))
+socket.on('jwt_ok',   (data) => console.log(data))
+socket.on('jwt_fail', (error) => console.log(error))
 
-// socket.on('msg', (msg) => { 
-//     store.dispatch(actionMsgOne(msg)) 
-// })
-// socket.on('chat', (chat) => { 
-//     store.dispatch(actionChatOne(chat)) 
-// })
-// socket.on('chat_left', (chat) => { 
-//     store.dispatch(actionChatLeft(chat)) 
-// })
+socket.on('msg', (msg) => { 
+   console.log('пришло смс')
+    store.dispatch(actionMsgOne(msg)) 
+})
+socket.on('chat', (chat) => { 
+    store.dispatch(actionChatOne(chat)) 
+})
+socket.on('chat_left', (chat) => { 
+    store.dispatch(actionChatLeft(chat)) 
+})
 
 
 // combineReducers({cart: localStoredReducer(cartReducer, 'cart'),