feat: update ui

This commit is contained in:
2026-09-17 13:47:37 +08:00
parent e9c1d5f3c7
commit 65a2e534d7
18 changed files with 284 additions and 58 deletions
+6
View File
@@ -47,6 +47,12 @@ export class WhatsAppClient {
this.socket.addEventListener("message", (data) => { this.socket.addEventListener("message", (data) => {
const message = JSON.parse(data.data); const message = JSON.parse(data.data);
if (message.type === "event") {
this.emit(message.event, message.data);
return;
}
if (message.type !== "response") { if (message.type !== "response") {
return; return;
} }
+5 -2
View File
@@ -3,9 +3,12 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WhatsApp Bridge UI</title> <title>WhatsApp Bridge</title>
</head> </head>
<body> <body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+1
View File
@@ -0,0 +1 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}
+95 -25
View File
@@ -1,9 +1,19 @@
import { useWAClient } from "./context"; import { useWAClient } from "./context";
import Avatar from "@/components/ui/avatar"; import Avatar from "@/components/ui/avatar";
import { getId } from "@/lib/utils"; import { useContacts } from "@/hooks/useContact";
import type { ChatDTO } from "@shared/dto"; import { getFormattedName, getId } from "@/lib/utils";
import type { ChatDTO, ContactDTO } from "@shared/dto";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { SearchIcon, XIcon } from "lucide-react"; import dayjs from "dayjs";
import {
FaceGrinningIcon,
ImageIcon,
PaperclipIcon,
PhoneIcon,
SearchIcon,
UsersIcon,
XIcon,
} from "lucide-react";
import { useMemo, useState } from "react"; import { useMemo, useState } from "react";
type Props = { type Props = {
@@ -14,6 +24,7 @@ export default function ChatsSection({ selected, onSelect }: Props) {
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const { client, isReady } = useWAClient(); const { client, isReady } = useWAClient();
const contacts = useContacts();
const { data: chats } = useQuery({ const { data: chats } = useQuery({
queryKey: ["chats"], queryKey: ["chats"],
queryFn: () => queryFn: () =>
@@ -25,17 +36,22 @@ export default function ChatsSection({ selected, onSelect }: Props) {
}); });
const filteredChats = useMemo(() => { const filteredChats = useMemo(() => {
if (!query.trim()) { let items = chats || [];
return chats?.slice(0, 100);
}
return chats if (query.trim().length > 0) {
?.filter( items = items.filter(
(chat) => (chat) =>
chat.formattedTitle?.toLowerCase().includes(query.toLowerCase()) || chat.formattedTitle?.toLowerCase().includes(query.toLowerCase()) ||
chat.lastMessage?.body?.toLowerCase().includes(query.toLowerCase()), chat.lastMessage?.body?.toLowerCase().includes(query.toLowerCase()),
) );
?.slice(0, 100); }
return items.slice(0, 100).map((i) => ({
...i,
from: i.isGroup
? contacts.findById(i.previewMessage?.author || null)
: null,
}));
}, [chats, query]); }, [chats, query]);
return ( return (
@@ -75,28 +91,32 @@ export default function ChatsSection({ selected, onSelect }: Props) {
onClick={() => onSelect(chat)} onClick={() => onSelect(chat)}
className={`flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition cursor-pointer ${selected?.id === chat.id ? "bg-accent" : "hover:bg-muted/70"}`} className={`flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition cursor-pointer ${selected?.id === chat.id ? "bg-accent" : "hover:bg-muted/70"}`}
> >
<Avatar name={chat.formattedTitle} /> <Avatar
name={chat.formattedTitle || chat.name}
icon={chat.isGroup ? <UsersIcon size={16} /> : null}
/>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2"> <div className="flex items-center justify-between gap-2">
<p className="truncate text-sm font-semibold"> <p className="truncate text-sm font-semibold">
{chat.formattedTitle || chat.name} {chat.formattedTitle || chat.name}
</p> </p>
{/* <span className="shrink-0 text-[11px] text-muted-foreground"> <span className="shrink-0 text-[11px] text-muted-foreground">
{chat.timestamp} {dayjs((chat.timestamp || 0) * 1000).fromNow()}
</span> */} </span>
</div> </div>
<div className="mt-1 flex items-center justify-between gap-2"> <div className="mt-1 flex items-center gap-0.5 text-xs text-muted-foreground">
<p className="truncate text-xs text-muted-foreground"> <ChatPreviewMessage
{chat.previewMessage?.type === "chat" data={chat.previewMessage}
? chat.previewMessage?.body?.substring(0, 50) from={chat.isGroup ? chat.from : null}
: null} />
</p>
{/* {chat.unread && ( {/* <div className="flex-1" />
<span className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-[10px] font-bold text-primary-foreground"> {chat.unreadCount ? (
{chat.unread} <span className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-[10px] font-bold text-primary-foreground">
</span> {chat.unreadCount}
)} */} </span>
) : null} */}
</div> </div>
</div> </div>
</button> </button>
@@ -105,3 +125,53 @@ export default function ChatsSection({ selected, onSelect }: Props) {
</> </>
); );
} }
function ChatPreviewMessage({
data,
from,
}: {
data: ChatDTO["previewMessage"];
from?: ContactDTO | null;
}) {
if (!data) {
return null;
}
let caption = useMemo(() => {
if (data.type === "image") {
return data.caption || "Picture";
}
if (data.type === "document") {
return data.caption || "Document";
}
if (data.type === "call_log") {
return "Call log";
}
if (data.type === "sticker") {
return "Sticker";
}
return data.type === "chat" || data.caption
? data.caption || data.body
: null;
}, [data]);
return (
<>
{from ? (
<span className="whitespace-nowrap" title={getFormattedName(from)}>
{getFormattedName(from) + ": "}
</span>
) : null}
{data.type === "image" && <ImageIcon size={16} />}
{data.type === "document" && <PaperclipIcon size={16} />}
{data.type === "call_log" && <PhoneIcon size={16} />}
{data.type === "sticker" && <FaceGrinningIcon size={16} />}
<p className="truncate" title={caption || undefined}>
{caption?.substring(0, 50)}
</p>
</>
);
}
+20
View File
@@ -7,6 +7,7 @@ export const WAContext = createContext<{
client: WhatsAppClient; client: WhatsAppClient;
isConnected: boolean; isConnected: boolean;
isReady: boolean; isReady: boolean;
addListener: (event: string, callback: (...args: any[]) => any) => () => void;
}>(null!); }>(null!);
export function useWAClient() { export function useWAClient() {
@@ -15,8 +16,11 @@ export function useWAClient() {
return ctx; return ctx;
} }
type ListenerMap = Record<string, ((...args: any[]) => any)[]>;
export function WAProvider({ children }: { children: React.ReactNode }) { export function WAProvider({ children }: { children: React.ReactNode }) {
const isInitialized = useRef(false); const isInitialized = useRef(false);
const eventListeners = useRef<ListenerMap>({});
const [isConnected, setConnected] = useState(false); const [isConnected, setConnected] = useState(false);
const { data: status } = useQuery({ const { data: status } = useQuery({
@@ -25,6 +29,20 @@ export function WAProvider({ children }: { children: React.ReactNode }) {
enabled: isConnected, enabled: isConnected,
}); });
function addListener(event: string, callback: (...args: any[]) => any) {
eventListeners.current[event] = eventListeners.current[event] || [];
eventListeners.current[event].push(callback);
return () => {
eventListeners.current[event] = eventListeners.current[event].filter(
(i) => i !== callback,
);
};
}
function emit(event: string, ...args: any[]) {
eventListeners.current[event]?.forEach((i) => i(...args));
}
useEffect(() => { useEffect(() => {
if (isInitialized.current) return; if (isInitialized.current) return;
@@ -32,6 +50,7 @@ export function WAProvider({ children }: { children: React.ReactNode }) {
isInitialized.current = true; isInitialized.current = true;
wa.on("status", setConnected); wa.on("status", setConnected);
wa.on("message", (data) => emit("message", data));
}, []); }, []);
return ( return (
@@ -40,6 +59,7 @@ export function WAProvider({ children }: { children: React.ReactNode }) {
client: wa, client: wa,
isConnected, isConnected,
isReady: status?.authenticated && status?.ready ? true : false, isReady: status?.authenticated && status?.ready ? true : false,
addListener,
}} }}
> >
{children} {children}
+75 -24
View File
@@ -5,6 +5,8 @@ import { useQuery } from "@tanstack/react-query";
import { cn } from "cn"; import { cn } from "cn";
import { import {
ArrowLeftIcon, ArrowLeftIcon,
CheckCheckIcon,
CheckIcon,
PaperclipIcon, PaperclipIcon,
PhoneCallIcon, PhoneCallIcon,
SendIcon, SendIcon,
@@ -14,6 +16,8 @@ import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime"; import relativeTime from "dayjs/plugin/relativeTime";
import MessageMedia from "@/components/message-media"; import MessageMedia from "@/components/message-media";
import Avatar from "@/components/ui/avatar"; import Avatar from "@/components/ui/avatar";
import { useContacts } from "@/hooks/useContact";
import { useMessageEvent } from "@/hooks/useMessageEvent";
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@@ -32,11 +36,7 @@ export default function MessagesSection({
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const [isPending, setPending] = useState(false); const [isPending, setPending] = useState(false);
const { data: contacts } = useQuery({ const { data: contacts } = useContacts();
queryKey: ["contacts"],
queryFn: () => client.listContacts(),
refetchOnWindowFocus: false,
});
const chatId = getId(chat.id); const chatId = getId(chat.id);
const { data: messages, refetch } = useQuery({ const { data: messages, refetch } = useQuery({
@@ -46,17 +46,35 @@ export default function MessagesSection({
refetchInterval: 10_1000, refetchInterval: 10_1000,
}); });
useMessageEvent((data) => {
if (data.chatId === chatId) refetch();
});
const messageList = useMemo(() => { const messageList = useMemo(() => {
return messages return messages
?.filter((i) => !["revoked"].includes(i.type as never)) ?.filter((i) => !["revoked"].includes(i.type as never))
?.map((message) => { ?.map((i) => {
const from = contacts?.find( const from = contacts?.find(
(c) => getId(c.id) === getId(message.author || message.from), (c) => getId(c.id) === getId(i.author || i.from),
); );
const quotedMsg = i.quotedMsg
? {
...i.quotedMsg,
from: contacts?.find((c) => {
return (
getId(c.id) ===
getId(i.quotedMsg?.author || i.quotedMsg?.from)
);
}),
}
: null;
return { return {
...message, ...i,
id: getId(message.id), id: getId(i.id),
from, from,
quotedMsg,
}; };
}) })
?.reverse(); ?.reverse();
@@ -135,6 +153,7 @@ export default function MessagesSection({
{messageList?.map((item, index) => ( {messageList?.map((item, index) => (
<div <div
id={item.id}
key={`${item.timestamp}-${index}`} key={`${item.timestamp}-${index}`}
className={`mb-3 flex ${item.fromMe ? "justify-end" : "justify-start"}`} className={`mb-3 flex ${item.fromMe ? "justify-end" : "justify-start"}`}
> >
@@ -151,23 +170,48 @@ export default function MessagesSection({
</p> </p>
) : null} ) : null}
{item.quotedMsg && item.quotedMsg.type === "chat" ? ( {/* <pre className="overflow-y-auto max-h-80">
<div {JSON.stringify(item, null, 2)}
</pre> */}
{item.quotedMsg &&
["chat", "image", "document"].includes(
item.quotedMsg.type as string,
) ? (
<a
href="#"
onClick={(e) => {
e.preventDefault();
const el = document.getElementById(
getId(item.quotedMsgId),
);
if (el) {
el.scrollIntoView({ behavior: "smooth" });
}
}}
className={cn( className={cn(
"bg-card/30 px-2 py-1.5 rounded-lg mb-2 mt-1", "bg-card/30 px-2 py-1.5 rounded-lg mb-2 mt-1 cursor-pointer block",
!item.fromMe && "bg-[#d8f5e8]/30 dark:bg-[#26855c]/30", !item.fromMe && "bg-[#d8f5e8]/30 dark:bg-[#26855c]/30",
)} )}
> >
<p className="whitespace-pre-wrap wrap-break-word"> <p className="text-xs text-muted-foreground">
{item.quotedMsg.body} {getFormattedName(item.quotedMsg.from)}
</p> </p>
</div> <p className="whitespace-pre-wrap wrap-break-word">
{item.quotedMsg.filename ||
item.quotedMsg.caption ||
(item.quotedMsg.type === "chat"
? item.quotedMsg.body
: "Quoted")}
</p>
</a>
) : null} ) : null}
{item.type === "image" || {item.type === "image" ||
item.type === "sticker" || item.type === "sticker" ||
item.type === "document" ? ( item.type === "document" ||
<MessageMedia data={item} /> item.type === "ptt" ? (
<MessageMedia data={item as never} />
) : null} ) : null}
{item.type === "chat" || item.caption ? ( {item.type === "chat" || item.caption ? (
@@ -187,12 +231,19 @@ export default function MessagesSection({
className={`mt-1 flex items-center justify-end gap-1 text-[10px] ${item.fromMe ? "text-primary" : "text-muted-foreground"}`} className={`mt-1 flex items-center justify-end gap-1 text-[10px] ${item.fromMe ? "text-primary" : "text-muted-foreground"}`}
> >
<span>{dayjs((item.timestamp ?? 0) * 1000).fromNow()}</span> <span>{dayjs((item.timestamp ?? 0) * 1000).fromNow()}</span>
{/* {item.fromMe &&
(item.read ? ( {item.fromMe && (
<CheckCheck size={14} /> <>
) : ( {item.ack && item.ack >= 2 ? (
<Check size={13} /> <CheckCheckIcon
))} */} size={14}
className={item.ack === 3 ? "text-blue-300" : ""}
/>
) : (
<CheckIcon size={13} />
)}
</>
)}
</div> </div>
</div> </div>
</div> </div>
@@ -232,7 +283,7 @@ export default function MessagesSection({
}} }}
placeholder="Write a message..." placeholder="Write a message..."
rows={1} rows={1}
className="max-h-24 min-h-10 flex-1 resize-none bg-transparent py-2.5 text-sm outline-none placeholder:text-muted-foreground" className="max-h-24 min-h-10 flex-1 resize-none field-sizing-content bg-transparent py-2.5 text-sm outline-none placeholder:text-muted-foreground"
/> />
</div> </div>
<button <button
+1 -1
View File
@@ -19,7 +19,7 @@ export default function Page() {
<main className="bg-background text-foreground flex overflow-hidden h-screen max-h-dvh"> <main className="bg-background text-foreground flex overflow-hidden h-screen max-h-dvh">
{/* <div className="mx-auto flex h-dvh max-w-360 overflow-hidden bg-card shadow-xl sm:h-[calc(100dvh-2rem)] sm:rounded-2xl lg:h-[calc(100dvh-3rem)]"> */} {/* <div className="mx-auto flex h-dvh max-w-360 overflow-hidden bg-card shadow-xl sm:h-[calc(100dvh-2rem)] sm:rounded-2xl lg:h-[calc(100dvh-3rem)]"> */}
<aside <aside
className={`flex w-full shrink-0 flex-col border-r border-border bg-card md:w-85 lg:w-95 ${mobileChat ? "hidden md:flex" : "flex"}`} className={`flex w-full shrink-0 flex-col border-r border-border bg-card md:w-85 lg:w-1/3 max-w-md ${mobileChat ? "hidden md:flex" : "flex"}`}
> >
{/* <header className="flex items-center justify-between border-b border-border px-5 py-5"> {/* <header className="flex items-center justify-between border-b border-border px-5 py-5">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
+14 -4
View File
@@ -1,6 +1,7 @@
import { useWAClient } from "@/app/context"; import { useWAClient } from "@/app/context";
import { storage } from "@/lib/storage"; import { storage } from "@/lib/storage";
import type { MessageDTO } from "@shared/dto"; import type { MessageDTO } from "@shared/dto";
import { cn } from "cn";
import { DownloadIcon, Loader2Icon, PaperclipIcon } from "lucide-react"; import { DownloadIcon, Loader2Icon, PaperclipIcon } from "lucide-react";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
@@ -85,9 +86,16 @@ export default function MessageMedia({ data }: Props) {
<a <a
href="#" href="#"
onClick={() => openMedia()} onClick={() => openMedia()}
className="w-full max-w-40 block relative overflow-hidden" className="w-full h-32 aspect-video block relative overflow-hidden"
> >
<img src={body || ""} alt="" className="w-full" /> <img
src={body || ""}
alt=""
className={cn(
"w-full h-full object-cover",
!isDownloaded && "blur-sm",
)}
/>
{isLoading && ( {isLoading && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center"> <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
@@ -108,7 +116,7 @@ export default function MessageMedia({ data }: Props) {
); );
} }
if (type === "document") { if (type === "document" || type === "ptt") {
return ( return (
<button <button
onClick={() => openMedia()} onClick={() => openMedia()}
@@ -122,7 +130,9 @@ export default function MessageMedia({ data }: Props) {
) : ( ) : (
<DownloadIcon className="size-4" /> <DownloadIcon className="size-4" />
)} )}
<span className="text-xs truncate">{data.filename}</span> <span className="text-xs truncate">
{type === "ptt" ? `Voice note (${data.duration}s)` : data.filename}
</span>
<span className="text-xs">{readableBytes(data.size || 0)}</span> <span className="text-xs">{readableBytes(data.size || 0)}</span>
</button> </button>
); );
+10 -2
View File
@@ -4,6 +4,7 @@ import { UserIcon } from "lucide-react";
type Props = { type Props = {
name?: string | null; name?: string | null;
icon?: React.ReactNode;
className?: string; className?: string;
iconClassName?: string; iconClassName?: string;
}; };
@@ -33,7 +34,12 @@ function getColorBasedOnName(name?: string | null) {
return colorSchemes[getInitial(name).charCodeAt(0) % colorSchemes.length]; return colorSchemes[getInitial(name).charCodeAt(0) % colorSchemes.length];
} }
export default function Avatar({ name, className, iconClassName }: Props) { export default function Avatar({
name,
icon,
className,
iconClassName,
}: Props) {
const color = getColorBasedOnName(name); const color = getColorBasedOnName(name);
return ( return (
@@ -44,7 +50,9 @@ export default function Avatar({ name, className, iconClassName }: Props) {
className, className,
)} )}
> >
{name ? ( {icon ? (
icon
) : name ? (
getInitial(name) getInitial(name)
) : ( ) : (
<UserIcon className={cn("size-4", iconClassName)} /> <UserIcon className={cn("size-4", iconClassName)} />
+24
View File
@@ -144,3 +144,27 @@
font-size: 16px; font-size: 16px;
} }
} }
@layer utilities {
.dark * {
scrollbar-width: thin;
scrollbar-color: #4b5563 transparent;
}
.dark *::-webkit-scrollbar {
width: 6px;
}
.dark *::-webkit-scrollbar-track {
background: transparent;
}
.dark *::-webkit-scrollbar-thumb {
background: #4b5563;
border-radius: 9999px;
}
.dark *::-webkit-scrollbar-thumb:hover {
background: #6b7280;
}
}
+23
View File
@@ -0,0 +1,23 @@
import { useWAClient } from "@/app/context";
import { getId } from "@/lib/utils";
import type { ContactDTO } from "@shared/dto";
import { useQuery } from "@tanstack/react-query";
export function useContacts() {
const { client, isReady } = useWAClient();
const res = useQuery({
queryKey: ["contacts"],
queryFn: () => client.listContacts(),
refetchOnWindowFocus: false,
enabled: isReady,
});
return {
...res,
findById(id: ContactDTO["id"]) {
if (!id) return null;
return res.data?.find((i) => getId(i.id) === getId(id));
},
};
}
+10
View File
@@ -0,0 +1,10 @@
import { useWAClient } from "@/app/context";
import type { MessageDTO } from "@shared/dto";
import { useEffect } from "react";
export function useMessageEvent(callback: (msg: MessageDTO) => any) {
const { addListener } = useWAClient();
useEffect(() => {
return addListener("message", callback);
}, [callback]);
}