Skip to content

Commit

Permalink
timestamp tracking
Browse files Browse the repository at this point in the history
  • Loading branch information
Wolfiej-k committed Dec 18, 2023
1 parent 4abdc46 commit 763bf91
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 30 deletions.
4 changes: 2 additions & 2 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
"editor.formatOnSave": false,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.formatDocument": true,
"source.fixAll.eslint": true
"source.formatDocument": "explicit",
"source.fixAll.eslint": "explicit"
},
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
Expand Down
10 changes: 5 additions & 5 deletions app/messages/chat-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,25 @@ function trim_text(text: string, length: number, with_ellipsis = false) {
const max_preview_length = 40;

interface ChatCardProps {
senderId: string;
senderName: string;
otherId: string;
otherName: string;
preview: string;
focused: boolean;
setFocus: (target: Target) => void;
}

export default function ChatCard({ senderId, senderName, preview, focused, setFocus }: ChatCardProps) {
export default function ChatCard({ otherId, otherName, preview, focused, setFocus }: ChatCardProps) {
const border = focused ? "border-slate-900" : "border-slate-500";
const style = "flex flex-row gap-4 rounded-lg border-2 p-4";

return (
<button onClick={() => setFocus({ targetId: senderId, targetName: senderName })}>
<button onClick={() => setFocus({ targetId: otherId, targetName: otherName })}>
<div className={style + " " + border}>
<div className="shrink">
<div className="h-24 w-24 rounded-3xl border-2 border-slate-500"></div>
</div>
<div className="flex flex-auto flex-col text-left">
<div className="mb-2 text-xl">{trim_text(senderName, max_preview_length / 3, true)}</div>
<div className="mb-2 text-xl">{trim_text(otherName, max_preview_length / 3, true)}</div>
<div className="text-sm text-slate-700">{trim_text(preview, max_preview_length, true)}</div>
</div>
</div>
Expand Down
81 changes: 63 additions & 18 deletions app/messages/chat-display.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,32 @@ export default function ChatDisplay({ userId, previews, messages }: ChatDisplayP

useEffect(() => {
const getData = async () => {
const { data, error } = await supabase.from("latest_messages").select().or(`sender.eq.${userId}, receiver.eq.${userId}`);
const { data, error } = await supabase
.from("latest_messages")
.select()
.or(`sender.eq.${userId}, receiver.eq.${userId}`);
if (!error && data) {
setPrevs(data);
const filteredPrevs: typeof data = [];
for (let i = 0; i < data.length; i++) {
const other = data[i]?.sender == userId ? data[i]?.receiver : data[i]?.sender;
if (filteredPrevs.some((cmp) => cmp.sender == other || cmp.receiver == other)) {
continue;
}

let min = i;
for (let j = i + 1; j < data.length; j++) {
const minTime = Date.parse(data[min]?.time_sent ?? "");
const cmpTime = Date.parse(data[j]?.time_sent ?? "");

if ((data[j]?.sender == other || data[j]?.receiver == other) && cmpTime > minTime) {
min = j;
}
}

filteredPrevs.push(data[min]!);
}

setPrevs(filteredPrevs);
}
};

Expand Down Expand Up @@ -66,6 +89,7 @@ export default function ChatDisplay({ userId, previews, messages }: ChatDisplayP
},
(payload) => {
setMsgs([...msgs, payload.new as Message]);
void getData();
},
)
.subscribe();
Expand All @@ -81,16 +105,37 @@ export default function ChatDisplay({ userId, previews, messages }: ChatDisplayP
<div className="col-span-3 p-6">
<ScrollArea.Root>
<ScrollArea.Viewport>
{prevs.map((prev, idx) => (
<ChatCard
key={idx}
senderId={prev.sender ?? ""}
senderName={prev.sender_display_name ?? ""}
preview={prev.message ?? ""}
focused={prev.sender == focus?.targetId}
setFocus={setFocus}
/>
))}
{prevs
.sort((a, b) => Date.parse(b.time_sent ?? "") - Date.parse(a.time_sent ?? ""))
.map((prev, idx) => {
const otherId = prev.sender == userId ? prev.receiver : prev.sender;
const otherName = prev.sender == userId ? prev.receiver_display_name : prev.sender_display_name;
let previewMsg = prev.sender;

if (prev.sender == userId) {
const diff = Date.now() - Date.parse(prev.time_sent!);
const time = Math.floor(diff / (1000 * 60));

if (time < 60) {
previewMsg = `Sent ${time}m ago`;
} else if (60 <= time && time < 1440) {
previewMsg = `Sent ${Math.floor(time / 60)}h ago`;
} else if (time >= 1440) {
previewMsg = `Sent ${Math.floor(time / (60 * 24))}d ago`;
}
}

return (
<ChatCard
key={idx}
otherId={otherId ?? ""}
otherName={otherName ?? ""}
preview={previewMsg ?? ""}
focused={otherId == focus?.targetId}
setFocus={setFocus}
/>
);
})}
</ScrollArea.Viewport>
<ScrollArea.Scrollbar orientation="horizontal">
<ScrollArea.Thumb />
Expand All @@ -105,12 +150,12 @@ export default function ChatDisplay({ userId, previews, messages }: ChatDisplayP
{focus && (
<div className="h-full rounded-md border-2 border-slate-900 px-4 py-6">
<div className="h-[80%] overflow-auto">
{msgs.map(
(msg, idx) =>
(msg.sender == focus.targetId || msg.receiver == focus.targetId) && (
<ChatText key={idx} userId={userId} message={msg} targetName={focus.targetName} />
),
)}
{msgs.map(
(msg, idx) =>
(msg.sender == focus.targetId || msg.receiver == focus.targetId) && (
<ChatText key={idx} userId={userId} message={msg} targetName={focus.targetName} />
),
)}
</div>
<ChatInput userId={userId} targetId={focus.targetId} />
</div>
Expand Down
26 changes: 21 additions & 5 deletions app/messages/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { createServerSupabaseClient } from "@/lib/server-utils";
import { redirect } from "next/navigation";
import ChatDisplay from "./chat-display";
import { type Database } from "@/lib/schema";

type Views<T extends keyof Database["public"]["Views"]> = Database["public"]["Views"][T]["Row"];
type Preview = Views<"latest_messages">;

export default async function Page() {
const supabase = createServerSupabaseClient();
Expand All @@ -24,5 +20,25 @@ export default async function Page() {
return;
}

return <ChatDisplay userId={userId} previews={previews.data} messages={messages.data} />;
const filteredPrevs: typeof previews.data = [];
for (let i = 0; i < previews.data.length; i++) {
const other = previews.data[i]?.sender == userId ? previews.data[i]?.receiver : previews.data[i]?.sender;
if (filteredPrevs.some((cmp) => cmp.sender == other || cmp.receiver == other)) {
continue;
}

let min = i;
for (let j = i + 1; j < previews.data.length; j++) {
const minTime = Date.parse(previews.data[min]?.time_sent ?? "");
const cmpTime = Date.parse(previews.data[j]?.time_sent ?? "");

if ((previews.data[j]?.sender == other || previews.data[j]?.receiver == other) && cmpTime > minTime) {
min = j;
}
}

filteredPrevs.push(previews.data[min]!);
}

return <ChatDisplay userId={userId} previews={filteredPrevs} messages={messages.data} />;
}

0 comments on commit 763bf91

Please sign in to comment.