Sfoglia il codice sorgente

add ability to delete chat

unknown 3 anni fa
parent
commit
e2eb58b6c6

File diff suppressed because it is too large
+ 1 - 1
.eslintcache


+ 2 - 1
src/App.tsx

@@ -37,7 +37,8 @@ function App() {
   }
 
   useEffect(() => {
-    if(!localStorage.isChecked) localStorage.isChecked = 'true'
+    if (!localStorage.isChecked) localStorage.isChecked = 'true'
+    if (localStorage.isNew) localStorage.removeItem('isNew')
   }, [])
 
    useEffect(() => {

+ 26 - 2
src/api-data/index.ts

@@ -149,7 +149,7 @@ const getContacts = async <T>(): Promise<T | undefined> => {
   }
 };
 
-const getChat = async <T>(id:string): Promise<T | undefined> => {
+const getChatById = async <T>(id:string): Promise<T | undefined> => {
   try {
     const { data: { data } } = await axios.get(`/chats/${id}`);
     return data
@@ -162,6 +162,27 @@ const getChat = async <T>(id:string): Promise<T | undefined> => {
 const startChat = async <T>(id:string): Promise<T | undefined> => {
   try {
     const { data: { data } } = await axios.post('/chats', { id });
+    console.log(data)
+    return data
+  } catch (e) {
+    forbidden(e)
+    return undefined
+  }
+};
+
+const removeChatForBoth = async <T>(id:string): Promise<T | undefined> => {
+  try {
+    const { data: { data } } = await axios.delete(`/chats/both/${id}`);
+    return data
+  } catch (e) {
+    forbidden(e)
+    return undefined
+  }
+};
+
+const removeChatForMe = async <T>(id:string): Promise<T | undefined> => {
+  try {
+    const { data: { data } } = await axios.delete(`/chats/me/${id}`);
     return data
   } catch (e) {
     forbidden(e)
@@ -212,6 +233,7 @@ const typingChat = async <T>(id:string,typing:boolean): Promise<T | undefined> =
 const getChats = async <T>(): Promise<T | undefined> => {
   try {
     const { data: { data } } = await axios.get('/chats');
+    console.log(data)
     return data
   } catch (e) {
     forbidden(e)
@@ -295,7 +317,9 @@ export {
   updateContact,
   getContacts,
   startChat,
-  getChat,
+  removeChatForBoth,
+  removeChatForMe,
+  getChatById,
   muteChat,
   sortChat,
   seenChat,

+ 11 - 4
src/components/HomePage/LeftBar/ChatsList/index.tsx

@@ -14,8 +14,10 @@ import AlertInfo from '../../../reusableComponents/AlertInfo'
 import DoneAllIcon from '@mui/icons-material/DoneAll';
 import { firstLetter, slicedWord, timeStampEU,notification,playNotificationWithoutPermission } from '../../../../helpers'
 import { getState } from '../../../../redux/chats/selector'
+import { getChatMemo } from '../../../../redux/chat/selector'
 import { asyncGetChats } from '../../../../redux/chats/operations'
 import { asyncStartChatById } from '../../../../redux/chat/operations'
+import { actionRemoveChat } from '../../../../redux/chat/action'
 import { actionScroll } from '../../../../redux/control/action'
 
 const StyledBadge = styled(Badge)(({ theme }) => ({
@@ -178,7 +180,8 @@ const ChatsList = () => {
   const dispatch = useDispatch()
   const ref = useRef<any>(null)
   const [selectedIndex, setSelectedIndex] = useState<number>(1);
-  const { total, chats , lastMessages,lastOnline } = useSelector(getState)
+  const { total, chats, lastMessages, lastOnline } = useSelector(getState)
+  const chat = useSelector(getChatMemo)
 
   const handleListItemClick = (i: number, companionId: string) => {
     dispatch(asyncStartChatById(companionId))
@@ -204,11 +207,15 @@ const ChatsList = () => {
     const handleNotification= (companionId: string) => {
       dispatch(asyncStartChatById(companionId))
       dispatch(actionScroll(true))
-   }
+    }
+    if (!chats.find((el) => el.companionId === chat.companionId)) {
+      dispatch(actionRemoveChat())
+    }
     if (ref.current) {
-      ref.current.forEach(({total,seen,_id}: any,i:number) => {
+      ref.current.forEach(({total,seen}: any,i:number) => {
         const oldDifferent = total - seen
         const chat = chats[i]
+        if(chat === undefined) return
         const newDifferent = chat.total - chat.seen
         if (newDifferent > oldDifferent && !chat.mute) {
           playNotificationWithoutPermission('http://localhost:3000/recive.mp3')
@@ -217,7 +224,7 @@ const ChatsList = () => {
       })
     }
       ref.current = chats
-  }, [chats,dispatch])  
+  }, [chats,chat,dispatch])  
 
   return total !== '0' ? (
     <List className={classes.list} component="nav"

+ 8 - 12
src/components/HomePage/LeftBar/ContactsList/index.tsx

@@ -42,16 +42,16 @@ const useStyles = makeStyles({
 })
 
 interface IContactList {
-  value: string
+  value: string,
+  handleClick: any
 }
-const  ContactsList = ({value} : IContactList) => {
+const  ContactsList = ({value,handleClick} : IContactList) => {
   const classes = useStyles()
   const dispatch = useDispatch()
-  const { total, contacts } = useSelector(getState)
-  const [selectedIndex, setSelectedIndex] = useState<number>(1);  
-  const handleListItemClick = async (i:number, companionId:string) => {
-     setSelectedIndex(i);
-     await dispatch(asyncStartChatById(companionId))
+  const { total, contacts } = useSelector(getState) 
+  const handleListItemClick = ( companionId:string) => {
+     handleClick()
+     dispatch(asyncStartChatById(companionId))
   }
 
   const filteredContacts = () => contacts.filter((el) => {
@@ -73,11 +73,7 @@ const  ContactsList = ({value} : IContactList) => {
       className={classes.list} component="nav"
       aria-label="main mailbox folders">
       {arr.length > 0? arr.map(({name,lastName,avatarUrl,color,createdAt,companionId,number }, i: number) => 
-        <ListItemButton
-          key={number}
-          selected={selectedIndex === i}
-          onClick={() => handleListItemClick(i,companionId)}
-          >
+        <ListItemButton onClick={() => handleListItemClick(companionId)} key={number}>
           <ListItemIcon className={classes.listItem_iconAvatar}>
             <Avatar alt={name} src={avatarUrl?`http://localhost:3000/${avatarUrl}`:undefined}
                  sx={{ background: color, width: 54, height: 54 }}>

+ 1 - 1
src/components/HomePage/LeftBar/index.tsx

@@ -74,7 +74,7 @@ const LeftBar = () => {
           createPortal(<MenuBar handleSelectedMenu={handleSelectedMenu} />, modalRoot.current)}
         {iMenu === 0 && <NotDone name='Saved Messages' />}
         {iMenu === 1 && <NotDone name='Archive Chats' />}
-        {iMenu === 2 && <ContactsList value={value}/>}
+        {iMenu === 2 && <ContactsList handleClick={handleClick} value={value}/>}
         {iMenu === 3 && <NotDone name='Settings' />}
         {iMenu === 4 && <NotDone name='Night Mode' />}
         {iMenu === 5 && <NotDone name='Animations' />}

+ 5 - 4
src/components/HomePage/RightBar/HeaderBar/Buttons/DeleteModal/index.tsx

@@ -4,6 +4,7 @@ import { makeStyles } from '@material-ui/core'
 import { useSelector } from 'react-redux';
 
 import { getChat } from '../../../../../../redux/chat/selector';
+import { removeChatForBoth,removeChatForMe } from '../../../../../../api-data';
 import { firstLetter,slicedWord } from '../../../../../../helpers';
 
 const useStyles = makeStyles({
@@ -40,13 +41,13 @@ const useStyles = makeStyles({
 
 const DeleteModal = ({setModal}:{setModal:any}) => {
   const classes = useStyles()
-  const {name,lastName,avatarUrl,color} = useSelector(getChat)
+  const {name,lastName,avatarUrl,color,companionId} = useSelector(getChat)
 
   const handleDeleteModal = (e: any) => {
     const id = e.target.id
     if (id === 'overlay' || id === 'cancel')  return setModal(false)
-    if (id === 'deleteForMeAnd') console.log('deleteForMeAnd')
-    if (id === 'deleteForMe') console.log('deleteForMeAnd')
+    if (id === 'deleteForBoth') removeChatForBoth(companionId)
+    if (id === 'deleteForMe') removeChatForMe(companionId)
   }  
   return (
     <div onClick={handleDeleteModal} className={classes.overlay} id='overlay'>
@@ -61,7 +62,7 @@ const DeleteModal = ({setModal}:{setModal:any}) => {
          <p style={{color: '#050505'}}>{`Are you sure you want to delete the
           chat with ${`${firstLetter(name)}${slicedWord(name, 15, 1)} 
             ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}?`}</p>
-          <Button id='deleteForMeAnd' variant="text" color="error" style={{fontWeight:500,fontSize:18}}>
+          <Button id='deleteForBoth' variant="text" color="error" style={{fontWeight:500,fontSize:18}}>
             {`DELETE FOR ME AND ${`${firstLetter(name)}${slicedWord(name, 15, 1)} 
             ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}`}
           </Button>

+ 2 - 2
src/components/HomePage/RightBar/HeaderBar/RightListsAndBars/CredentialsList/ProfilePicture/index.tsx

@@ -1,5 +1,5 @@
 import { makeStyles } from '@material-ui/core'
-import { firstLetter,slicedWord,timeStamp } from '../../../../../../../helpers'
+import { firstLetter,slicedWord,timeStampEU } from '../../../../../../../helpers'
 import { useSelector } from 'react-redux';
 import { getChat } from '../../../../../../../redux/chat/selector'
 
@@ -47,7 +47,7 @@ const ProfilePicture = () => {
         {`${firstLetter(name)}${firstLetter(lastName)}`}</div>}
       <span className={classes.nameTile}>{`${firstLetter(name)}${slicedWord(name, 15, 1)}
         ${firstLetter(lastName)}${slicedWord(lastName, 15, 1)}`}</span>
-      <span className={classes.timeTile}>{online === 'true'?'online':`last seen ${timeStamp(online)}`}</span>
+      <span className={classes.timeTile}>{online === 'true'?'online':`last seen ${timeStampEU(online)}`}</span>
     </div>
   )
 }

+ 7 - 2
src/redux/chat/action/index.ts

@@ -4,12 +4,17 @@ import { TChat } from '../../../typescript/redux/chat/types'
 const actionSelectChat = createAction('selectChat/success', (value:TChat) => ({
   payload: value,
 }));
-const actionGetChat = createAction('getChat/success', (value:TChat) => ({
+const actionGetChatById = createAction('getChatById/success', (value:TChat) => ({
   payload: value,
 }));
 
+const actionRemoveChat = createAction('deleteChat/success', () => ({
+  payload:{}
+}));
+
 
 export {
   actionSelectChat,
-  actionGetChat
+  actionGetChatById,
+  actionRemoveChat
 };

+ 4 - 4
src/redux/chat/operations/index.ts

@@ -1,8 +1,8 @@
 import {
   actionSelectChat,
-  actionGetChat
+  actionGetChatById
 } from '../action';
-import { startChat,getChat } from '../../../api-data';
+import { startChat,getChatById } from '../../../api-data';
 
 import { TChat } from '../../../typescript/redux/chat/types'
 
@@ -15,8 +15,8 @@ const asyncStartChatById = (id:string) => async (dispatch:any) => {
 
 const asyncGetChatById = (id:string) => async (dispatch:any) => {
   try {
-    const data = await getChat<TChat>(id)
-    data&&dispatch(actionGetChat(data))
+    const data = await getChatById<TChat>(id)
+    data&&dispatch(actionGetChatById(data))
   } catch(e) {}
 };
 

+ 7 - 5
src/redux/chat/reducer/index.ts

@@ -3,7 +3,8 @@ import { IChatPayload,IChatState } from '../../../typescript/redux/chat/interfac
 
 import {
   actionSelectChat,
-  actionGetChat
+  actionGetChatById,
+  actionRemoveChat
 } from '../action';
 
 const initialState: IChatState = {
@@ -29,15 +30,16 @@ const initialState: IChatState = {
   },
 }
 
-
-
 const reducerChat = createReducer(initialState, {
   [actionSelectChat.type]: (_,{ payload:chat }:IChatPayload) => {
     return {chat}
   },
-  [actionGetChat.type]: (_,{ payload:chat }:IChatPayload) => {
+  [actionGetChatById.type]: (_,{ payload:chat }:IChatPayload) => {
     return {chat}
-  },  
+  },
+  [actionRemoveChat.type]: (_state,_) => {
+    return initialState
+  },    
 });
 
 export default reducerChat;