Skip to content

Commit

Permalink
sorting of chats based on most recent
Browse files Browse the repository at this point in the history
  • Loading branch information
tomyRomero committed Dec 7, 2023
1 parent e690211 commit 7762945
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 31 deletions.
25 changes: 24 additions & 1 deletion app/(root)/chat/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,30 @@ async function Page({
pageSize: 15,
});

const chats: any[] = await getChatsWithUsersByUserId(user.id)
let chats: any[] = await getChatsWithUsersByUserId(user.id)

const sortedChats = chats.sort((chatA, chatB) => {
const lastMessageA = chatA.messages[chatA.messages.length - 1];
const lastMessageB = chatB.messages[chatB.messages.length - 1];

const dateA = new Date(lastMessageA.timestamp);
const dateB = new Date(lastMessageB.timestamp);

console.log("Timestamp A: ", lastMessageA.timestamp);
console.log("Date A: ", dateA);

console.log("Timestamp B: ", lastMessageB.timestamp);
console.log("Date B: ", dateB);

// Compare the dates (descending order, latest time first)
//@ts-ignore
return dateB - dateA;
});

if(sortedChats.length > 1)
{
chats = sortedChats;
}

return (
<section className='w-full h-screen flex flex-col bg-black rounded-xl'>
Expand Down
24 changes: 23 additions & 1 deletion app/(root)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,29 @@ export default async function RootLayout({
{
updateOnlineStatus(user.id, true);
const dbUser = await fetchUser(user.id)
const chats: any[] = await getChatsWithUsersByUserId(user.id)
let chats: any[] = await getChatsWithUsersByUserId(user.id)
const sortedChats = chats.sort((chatA, chatB) => {
const lastMessageA = chatA.messages[chatA.messages.length - 1];
const lastMessageB = chatB.messages[chatB.messages.length - 1];

const dateA = new Date(lastMessageA.timestamp);
const dateB = new Date(lastMessageB.timestamp);

console.log("Timestamp A: ", lastMessageA.timestamp);
console.log("Date A: ", dateA);

console.log("Timestamp B: ", lastMessageB.timestamp);
console.log("Date B: ", dateB);

// Compare the dates (descending order, latest time first)
//@ts-ignore
return dateB - dateA;
});

if(sortedChats.length > 1)
{
chats = sortedChats;
}
return {dbUser, chats};
}
}
Expand Down
35 changes: 28 additions & 7 deletions components/cards/ChatLogs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur
return lastIndex.timestamp
}


return (
<Link
href={`/chat/${receiverID}`}
Expand Down Expand Up @@ -162,16 +163,36 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur
)}

{isHome && (
<div className={`text-black ${!read && !isMe ? 'font-bold' : ''} `}>{getLastTime()}</div>
)
}
<div className={`ml-auto text-black ${!read && !isMe ? 'font-bold' : ''}`}>
<div className="text-left">
{/* Date */}
{getLastTime().split(' ')[0]}
</div>
<div className="text-left">
{/* Time */}
{getLastTime().split(' ')[1]}{' '}
{getLastTime().split(' ')[2]} {/* AM/PM */}
</div>
</div>
)}

</div>

{!isHome && (
<div className={`ml-auto text-black ${!read && !isMe ? 'font-bold' : ''} `}>{getLastTime()}</div>
)
}
<div className={`ml-auto text-black ${!read && !isMe ? 'font-bold' : ''}`}>
<div className="text-right">
{/* Date */}
{getLastTime().split(' ')[0]}
</div>
<div className="text-right">
{/* Time */}
{getLastTime().split(' ')[1]}{' '}
{getLastTime().split(' ')[2]} {/* AM/PM */}
</div>
</div>
)}



</div>
</Link>
Expand Down
8 changes: 3 additions & 5 deletions components/forms/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { markChatAsRead, revalData, sendMessage, updateChatForOther, updateOnlin
import { usePathname, useRouter } from "next/navigation";
import { getImageData } from "@/lib/s3";
import pusherClient from "@/lib/pusher";
import { getDateTime } from "@/lib/utils";

interface chat{
chatPicture: string;
Expand Down Expand Up @@ -60,7 +61,7 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:
// Use the data to update the online status in UI
console.log('Received updateOnlineStatus event:', data);

if(receiver === data.userID)
if(receiver === data.userId)
{
setActive(true);
}
Expand Down Expand Up @@ -182,10 +183,7 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:
setRead(false)
setLoading(true)

const date = new Date();
const options: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: 'numeric', hour12: true };

const timestamp = new Intl.DateTimeFormat('en-US', options).format(date);
const timestamp = getDateTime();

// Call the sendMessage function with the entered message and sender

Expand Down
3 changes: 3 additions & 0 deletions lib/actions/chat.actions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
"use server"

import { getDateTime } from "../utils";


import Pusher from "pusher";
import { connectDb } from "../sql";
import util from 'util';
Expand Down
16 changes: 1 addition & 15 deletions lib/actions/post.actions.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,10 @@
"use server"
import {connectDb} from '@/lib/sql'
import { revalidatePath } from 'next/cache';

import { getDateTime } from '../utils';
import util from 'util';

function getDateTime() {
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Months are zero-based
const day = String(currentDate.getDate()).padStart(2, '0');
let hours = currentDate.getHours();
const minutes = String(currentDate.getMinutes()).padStart(2, '0');
const period = hours >= 12 ? 'pm' : 'am';

// Convert hours to 12-hour format
hours = hours % 12 || 12;

// Combine the date and time components into a string with the desired format (e.g., "MM-DD-YYYY h:mm am/pm")
return `${month}-${day}-${year} ${hours}:${minutes} ${period}`;
}

export const createPost = async ({text,author,path, image, title} : {text: string, author: string, path: string, image:string , title: string}) => {
try{
Expand Down
2 changes: 0 additions & 2 deletions lib/s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export const getImageData = async (key: string) => {
const result = match ? match[0] : 'jpg';
console.log("RESULT IMAGE TYPE:", result)
let base64 = `data:image/${result};base64,` + getResponseData;
console.log('Success in Getting Image from server! Server response:', base64);
return base64;

} else {
Expand All @@ -34,7 +33,6 @@ export const getImageData = async (key: string) => {
if (response.ok) {
// Request was successful, handle the response
const responseData = await response.json();
console.log('Server response:', responseData);
return responseData.filename;
} else {
// Request failed, handle the error
Expand Down
17 changes: 17 additions & 0 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,21 @@ export function isBase64Image(imageData: string) {
return base64Regex.test(imageData);
}

export function getDateTime() {
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // Months are zero-based
const day = String(currentDate.getDate()).padStart(2, '0');
let hours = currentDate.getHours();
const minutes = String(currentDate.getMinutes()).padStart(2, '0');
const period = hours >= 12 ? 'pm' : 'am';

// Convert hours to 12-hour format
hours = hours % 12 || 12;

// Combine the date and time components into a string with the desired format (e.g., "MM-DD-YYYY h:mm am/pm")
const formattedTimestamp = `${month}-${day}-${year} ${hours}:${minutes} ${period}`;

return formattedTimestamp;
}

0 comments on commit 7762945

Please sign in to comment.