Browse Source

update chat

sheva77 3 years ago
parent
commit
ccb313f844

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

@@ -33,6 +33,7 @@ export const actionUserInfo = (userId) => async (dispatch) => {
                             chats {
                                 _id
                                 title
+                                owner{_id}
                                 avatar {url}
                                 members{_id login nick avatar{url}}
                                 }

+ 11 - 2
chat_final_bootstrap/src/Actions/ActionsGqlUpsert.js

@@ -51,9 +51,15 @@ const actionMediaUpsert = ({ chatId, mediaId }) => async (dispatch) => {
     );
 };
 
-export const actionCreateNewChat = ({ title, members, avaFile }) => async (dispatch) => {
+export const actionCreateNewChat = ({ _id, title, members, avaFile }) => async (dispatch) => {
     members = members.map((mem) => ({ _id: mem._id }));
 
+    let tempObj = { title, members };
+
+    if (_id) {
+        tempObj._id = _id;
+    }
+
     let chatData = await dispatch(
         actionPromise(
             "ChatUpsert",
@@ -66,7 +72,7 @@ export const actionCreateNewChat = ({ title, members, avaFile }) => async (dispa
                         members{login}
                     }
                 }`,
-                { newChat: { title, members } }
+                { newChat: tempObj }
             )
         )
     );
@@ -90,5 +96,8 @@ export const actionCreateNewChat = ({ title, members, avaFile }) => async (dispa
         await dispatch(actionUserInfo(members[0]._id));
 
         history.push(`/main/${chatData.data.ChatUpsert._id}`);
+    } else {
+        alert("Ошибка создания/обновления чата");
+        history.goBack();
     }
 };

+ 1 - 0
chat_final_bootstrap/src/App.js

@@ -39,6 +39,7 @@ const App = () => (
                 <Switch>
                     <Route path="/about" component={PageAbout} exact />
                     <Route path="/newchat" component={CPageNewChat} exact />
+                    <Route path="/newchat/:_chatId" component={CPageNewChat} exact />
                     <Route path="/upload" component={PageUpload} exact />
                     <Route path="/" component={PageLogin} exact />
                     <Route path="/main/:_chatId" component={CPageMain} exact />

+ 23 - 22
chat_final_bootstrap/src/Components/ChatMessages.js

@@ -170,34 +170,35 @@ const Messages = ({ _id = "", chatInfo, messages, getMsg }) => {
     }, [_id]);
 
     return (
+        // шапка - Лого чата, title...
         <div className="mb-2">
             {chatInfo && chatInfo[0] && (
-                <div className="position-relative  mb-3 border-bottom border-2 border-success ">
+                <div className="position-relative  mb-3 border-bottom border-2 border-success text-dark">
                     <div className="d-flex justify-content-start align-items-center">
-                        <div className="avatarka">
-                            {avatar ? (
-                                <img
-                                    src={`${urlUploadConst}/${avatar}`}
-                                    className=" border border-2 border-success"
-                                ></img>
-                            ) : (
-                                <div className="d-flex justify-content-center align-items-center bg-success border border-2 border-success gradient">
-                                    <div className="fs-5 text-light fw-bolder">
-                                        {title &&
-                                            `${title.split(" ")[0][0].toUpperCase()}` +
-                                                `${
-                                                    (title.split(" ").slice(1).pop() &&
-                                                        title.split(" ").slice(1).pop()[0].toUpperCase()) ||
-                                                    ""
-                                                }`}
+                        <Link to={`/newchat/${_id}`} className="noUnderLine">
+                            <div className="avatarka">
+                                {avatar ? (
+                                    <img
+                                        src={`${urlUploadConst}/${avatar}`}
+                                        className=" border border-2 border-success"
+                                    ></img>
+                                ) : (
+                                    <div className="d-flex justify-content-center align-items-center bg-success border border-2 border-success gradient">
+                                        <div className="fs-5 text-light fw-bolder">
+                                            {title &&
+                                                `${title.split(" ")[0][0].toUpperCase()}` +
+                                                    `${
+                                                        (title.split(" ").slice(1).pop() &&
+                                                            title.split(" ").slice(1).pop()[0].toUpperCase()) ||
+                                                        ""
+                                                    }`}
+                                        </div>
                                     </div>
-                                </div>
-                            )}
-                        </div>
-
+                                )}
+                            </div>
+                        </Link>
                         <div className="fs-4 fw-bolder ms-2">{`${title}`}</div>
                     </div>
-
                     <span className="position-absolute bottom-0 end-0  badge rounded-pill bg-secondary">
                         {` _chatId: ${_id}`} <span className="visually-hidden">id чата</span>
                     </span>

+ 42 - 13
chat_final_bootstrap/src/Components/NewChatDashBoard.js

@@ -1,6 +1,6 @@
 import { ButtonToMain } from "../Components";
 import { urlUploadConst } from "../const";
-import { actionDelUserFromChatList, actionCreateNewChat } from "../Actions";
+import { actionDelUserFromChatList, actionCreateNewChat, actionAddUserToChatList } from "../Actions";
 import { connect } from "react-redux";
 import { useEffect } from "react";
 import { useState } from "react";
@@ -42,22 +42,41 @@ const CMemberItem = connect(
     { dellFromList: actionDelUserFromChatList }
 )(MemberItem);
 
-const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
+const NewChatDashBoard = ({ members = {}, chatUpsert = null, _chatId, myChats = [], addUserToList }) => {
     const [chatMembers, setChatMembers] = useState(Object.values(members));
     const [inpTitle, setInpTitle] = useState("");
-    const uploadRef = useRef(null);
-    const uploadImgRef = useRef(null);
+    const uploadRef = useRef(null); // ссылка на input type=file для авы
+    const inputTiylegRef = useRef(null);
     const [srcAva, setSrcAva] = useState("");
 
-    // console.log(members);
+    // достаем из redux даные о чате, который хотим редактировать
+    useEffect(() => {
+        if (_chatId) {
+            let chatInfo = {};
+
+            myChats = myChats.filter((chat) => chat._id === _chatId); // оставляем в myChats только редактируемый
+            chatInfo = myChats && myChats[0];
+
+            if (chatInfo && Object.keys(chatInfo).length) {
+                inputTiylegRef.current.value = chatInfo.title;
+                setInpTitle(chatInfo.title);
+                chatInfo.members.forEach((mem) => {
+                    if (typeof addUserToList === "function") {
+                        addUserToList(mem);
+                    }
+                });
+            }
+        }
+    }, [myChats]);
 
     useEffect(() => {
         setChatMembers(Object.values(members));
     }, [members]);
 
     const doCreateNewChat = () => {
-        if (typeof createNewChat === "function") {
-            createNewChat({
+        if (typeof chatUpsert === "function") {
+            chatUpsert({
+                _id: _chatId,
                 title: inpTitle,
                 members: chatMembers,
                 avaFile: uploadRef.current && uploadRef.current.files && uploadRef.current.files[0],
@@ -66,7 +85,6 @@ const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
     };
 
     function previewFile() {
-        let preview = uploadImgRef.current;
         let file = uploadRef.current && uploadRef.current.files && uploadRef.current.files[0];
         let reader = new FileReader();
 
@@ -85,7 +103,7 @@ const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
     return (
         <>
             <div className="ChatDashBoard bg-light">
-                <h5>New Chat:</h5>
+                <h5>{_chatId ? "Update chat:" : "New Chat:"}</h5>
                 <table className="table table-bordered align-middle">
                     <tbody>
                         <tr>
@@ -95,6 +113,7 @@ const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
                                     className="form-control mb-2 p-2 border border-success border-2"
                                     placeholder="Input title for new chat"
                                     onChange={(e) => setInpTitle(e.target.value)}
+                                    ref={inputTiylegRef}
                                 ></input>
                             </td>
                         </tr>
@@ -153,7 +172,13 @@ const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
                     </tbody>
                 </table>
                 <button className="btn-success gradient rounded" disabled={!inpTitle} onClick={doCreateNewChat}>
-                    Create new chat
+                    {_chatId ? "Update chat" : "Create new chat"}
+                    {/*  */}
+                    {/*  */}
+                    {/*  */}
+                    {/*  */}
+                    {/*  */}
+                    {/*  */}
                 </button>
                 {!inpTitle && <span className="text-danger"> You should fill in the 'Chat title' field.</span>}
             </div>
@@ -161,6 +186,10 @@ const NewChatDashBoard = ({ members = {}, createNewChat = null }) => {
     );
 };
 
-export const CNewChatDashBoard = connect((s) => ({ members: s.newChatUsers }), { createNewChat: actionCreateNewChat })(
-    NewChatDashBoard
-);
+export const CNewChatDashBoard = connect(
+    (s, { _chatId }) => ({ myChats: s.auth.chats, members: s.newChatUsers, _chatId }),
+    {
+        chatUpsert: actionCreateNewChat,
+        addUserToList: actionAddUserToChatList,
+    }
+)(NewChatDashBoard);

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

@@ -66,9 +66,7 @@ export const CMessageInput = connect((s) => ({ curChatId: s.curChatId }), { mess
 
 //prettier-ignore
 const PageMain = ({
-    match: {
-        params: { _chatId },
-    },
+    match: {        params: { _chatId },    },
     _userId,
     messages, // из редакса через коннект
     getMesagesList = null,

+ 4 - 2
chat_final_bootstrap/src/Pages/PageNewChat.js

@@ -14,9 +14,11 @@ import logo from "../images/logo23.png";
 import chat_square_text from "../icons/chat-square-text.svg";
 import userEvent from "@testing-library/user-event";
 
-const PageNewChat = ({ doSearchUsers = null }) => {
+// prettier-ignore
+const PageNewChat = ({ doSearchUsers = null, match: { params: { _chatId = "" } = {} } = {} }) => {
     const [searchUserStr, setSearchUserStr] = useState("");
 
+
     // если не залогинены - вперед к регистрации/логину
     if (!store.getState().auth || !store.getState().auth.login) {
         history.push("/");
@@ -53,7 +55,7 @@ const PageNewChat = ({ doSearchUsers = null }) => {
                         <CAllUsersList searchUserStr={searchUserStr} />
                     </div>
                     <div className="col-md-8">
-                        <CNewChatDashBoard />
+                        <CNewChatDashBoard _chatId={_chatId}/>
                     </div>
                 </div>
             </div>