feat: frontend draft

This commit is contained in:
2026-09-15 17:55:48 +08:00
parent a13e4d2d99
commit 5329bb2ed9
28 changed files with 4865 additions and 67 deletions
-2
View File
@@ -1,2 +0,0 @@
onlyBuiltDependencies:
- esbuild
-42
View File
@@ -1,42 +0,0 @@
import { WhatsAppClient } from "./whatsapp";
const wa = new WhatsAppClient("wss://wa-bridge.rul.sh/ws");
await wa.connect();
const chats = await wa.listChats({
limit: 10,
groupsOnly: true,
// usersOnly: true,
});
console.log(
chats.map((i) => ({
id: typeof i.id === "object" ? i.id?._serialized : i.id,
lid: i.accountLid,
name: i.formattedTitle,
})),
);
const messages = await wa.getMessages({
chatId: "[email protected]",
count: 5,
});
console.log(
messages.map((i) => ({
id: i.id.id,
from: i.from,
text: i.body,
})),
);
// const result = await wa.searchMessages({
// query: "pasien",
// chatId: "[email protected]",
// limit: 20,
// });
// await wa.sendText({
// chatId: "[email protected]",
// text: "Hello from Node!",
// });
+25 -10
View File
@@ -1,5 +1,3 @@
import WebSocket from "ws";
import type { import type {
GetMessagesParams, GetMessagesParams,
ListChatsParams, ListChatsParams,
@@ -14,8 +12,9 @@ import type {
} from "../shared/dto"; } from "../shared/dto";
export class WhatsAppClient { export class WhatsAppClient {
isConnected: boolean = false;
private url: string = ""; private url: string = "";
private isConnected: boolean = false;
private socket: WebSocket | null = null; private socket: WebSocket | null = null;
private pending = new Map< private pending = new Map<
@@ -27,25 +26,28 @@ export class WhatsAppClient {
} }
>(); >();
private listeners: Map<string, (...args: any[]) => void> = new Map();
constructor(url = "ws://127.0.0.1:8787") { constructor(url = "ws://127.0.0.1:8787") {
this.url = url; this.url = url;
} }
async connect() { async connect() {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve) => {
if (this.socket) return; if (this.socket) return;
this.socket = new WebSocket(this.url); this.emit("connecting");
this.socket = new WebSocket(this.url + "?client=1");
this.socket.on("open", () => { this.socket.addEventListener("open", () => {
console.log("Connected to bridge"); console.log("Connected to bridge");
this.isConnected = true; this.isConnected = true;
this.emit("status", true);
resolve(); resolve();
}); });
this.socket.on("message", (data) => { this.socket.addEventListener("message", (data) => {
const message = JSON.parse(data.toString()); const message = JSON.parse(data.data);
if (message.type !== "response") { if (message.type !== "response") {
return; return;
} }
@@ -66,9 +68,10 @@ export class WhatsAppClient {
} }
}); });
this.socket.on("close", () => { this.socket.addEventListener("close", () => {
this.socket = null; this.socket = null;
this.isConnected = false; this.isConnected = false;
this.emit("status", false);
setTimeout(() => this.connect(), 3000); setTimeout(() => this.connect(), 3000);
}); });
}); });
@@ -105,7 +108,19 @@ export class WhatsAppClient {
}); });
} }
on(event: string, callback: (...args: any[]) => void) {
this.listeners.set(event, callback);
}
private emit(event: string, ...args: any[]) {
this.listeners.get(event)?.(...args);
}
status() { status() {
if (!this.isConnected) {
return null;
}
return this.request<{ return this.request<{
authenticated: boolean; authenticated: boolean;
ready: boolean; ready: boolean;
+5 -1
View File
@@ -36,9 +36,10 @@ export function initDb() {
} }
export function insertMessage(message: Message): void { export function insertMessage(message: Message): void {
try {
db.query( db.query(
`INSERT INTO messages (id, chat_id, sender, receiver, from_me, data) `INSERT INTO messages (id, chat_id, sender, receiver, from_me, data)
VALUES ($id, $chatId, $from, $to, $fromMe, $data)`, VALUES ($id, $chatId, $from, $to, $fromMe, $data) ON CONFLICT(id) DO UPDATE SET data = $data;`,
).run({ ).run({
$id: message.id, $id: message.id,
$chatId: message.chatId, $chatId: message.chatId,
@@ -47,4 +48,7 @@ export function insertMessage(message: Message): void {
$fromMe: message.fromMe ? 1 : 0, $fromMe: message.fromMe ? 1 : 0,
$data: JSON.stringify(message.data), $data: JSON.stringify(message.data),
}); });
} catch (err) {
console.error(err);
}
} }
+1 -1
View File
@@ -115,7 +115,7 @@ wss.on("connection", (ws) => {
* First connection from Tampermonkey is the * First connection from Tampermonkey is the
* WhatsApp bridge. * WhatsApp bridge.
*/ */
if (!whatsapp) { if (!whatsapp && !ws.url.includes("?client=1")) {
whatsapp = ws; whatsapp = ws;
console.log("[WS] WhatsApp bridge attached"); console.log("[WS] WhatsApp bridge attached");
+1 -1
View File
@@ -267,7 +267,7 @@ export function serializeMessage(message: any): MessageDTO {
from: serializeId(message.from), from: serializeId(message.from),
to: serializeId(message.to), to: serializeId(message.to),
author: serializeId(message.author), author: serializeId(message.author),
fromMe: message.fromMe ?? false, fromMe: message.id?.fromMe ?? message.fromMe ?? false,
body: message.body ?? null, body: message.body ?? null,
caption: message.caption ?? null, caption: message.caption ?? null,
type: message.type ?? null, type: message.type ?? null,
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
+32
View File
@@ -0,0 +1,32 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the Oxlint configuration
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
```json
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"options": {
"typeAware": true
},
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
```
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
+25
View File
@@ -0,0 +1,25 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-vega",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}
+16
View File
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ui</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+35
View File
@@ -0,0 +1,35 @@
{
"name": "ui",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"@base-ui/react": "^1.8.0",
"@fontsource-variable/inter": "^5.3.0",
"@tailwindcss/vite": "^4.3.3",
"@tanstack/react-query": "^5.102.8",
"class-variance-authority": "^0.7.1",
"cn": "^0.3.0",
"lucide-react": "^1.46.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"shadcn": "^4.21.0",
"tailwindcss": "^4.3.3",
"tw-animate-css": "^1.4.0"
},
"devDependencies": {
"@types/node": "^24.13.3",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.7",
"@vitejs/plugin-react": "^6.1.1",
"oxlint": "^1.81.0",
"typescript": "~6.0.2",
"vite": "^8.3.0"
}
}
+3718
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+20
View File
@@ -0,0 +1,20 @@
import { Button } from "./components/ui/button";
import { useQuery } from "@tanstack/react-query";
import { useWAClient } from "./lib/context";
export default function App() {
const { client, isReady } = useWAClient();
const { data: chats } = useQuery({
queryKey: ["chats"],
queryFn: () => client.listChats({ limit: 50 }),
enabled: isReady,
});
console.log(chats);
return (
<div>
<Button>Test</Button>
</div>
);
}
+146
View File
@@ -0,0 +1,146 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "@fontsource-variable/inter";
@custom-variant dark (&:is(.dark *));
@theme inline {
--font-heading: var(--font-sans);
--font-sans: "Inter Variable", sans-serif;
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
html {
@apply font-sans;
}
::selection {
background: var(--accent);
color: var(--accent-foreground);
}
}
.message-pattern {
background-color: var(--muted);
background-image: radial-gradient(color-mix(in oklch, var(--border) 70%, transparent) 0.7px, transparent 0.7px);
background-size: 18px 18px;
}
@media (max-width: 767px) {
textarea {
font-size: 16px;
}
}
+241
View File
@@ -0,0 +1,241 @@
import { useWAClient } from "@/lib/context";
import { getFormattedName, getId, getInitial } from "@/lib/utils";
import type { ChatDTO } from "@shared/dto";
import { useQuery } from "@tanstack/react-query";
import { cn } from "cn";
import {
ArrowLeftIcon,
CircleHelpIcon,
PaperclipIcon,
SendIcon,
} from "lucide-react";
import React, { useMemo, useState } from "react";
type Props = {
chat: ChatDTO;
mobileChat: boolean;
setMobileChat: React.Dispatch<React.SetStateAction<boolean>>;
};
export default function MessagesSection({
chat,
mobileChat,
setMobileChat,
}: Props) {
const { client, isReady } = useWAClient();
const [message, setMessage] = useState("");
const { data: contacts } = useQuery({
queryKey: ["contacts"],
queryFn: () => client.listContacts(),
refetchOnWindowFocus: false,
});
const chatId = getId(chat.id);
const { data: messages } = useQuery({
queryKey: ["messages", chatId],
queryFn: () =>
client.getMessages({ chatId, count: 50 }).then((res) =>
res.map((i) => ({
...i,
id: getId(i.id),
fromMe: i.id.fromMe || i.fromMe,
})),
),
enabled: Boolean(chatId && isReady),
});
const messageList = useMemo(() => {
return messages
?.filter((i) => !["call_log", "revoked"].includes(i.type as never))
.map((message) => {
const from = contacts?.find(
(c) => getId(c.id) === getId(message.author || message.from),
);
return {
...message,
from,
};
})
?.reverse();
}, [messages, contacts]);
function sendMessage() {
const text = message.trim();
if (!text) return;
setMessage("");
}
return (
<section
className={`flex min-w-0 flex-1 flex-col bg-muted ${mobileChat ? "flex" : "hidden md:flex"}`}
>
<header className="flex items-center justify-between border-b border-border bg-card px-4 py-3 sm:px-6">
<div className="flex min-w-0 items-center gap-3">
<button
aria-label="Back to conversations"
onClick={() => setMobileChat(false)}
className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-muted md:hidden"
>
<ArrowLeftIcon size={19} />
</button>
<div
className={cn(
"grid size-10 shrink-0 place-items-center rounded-full text-sm font-semibold",
)}
>
{getInitial(chat.formattedTitle)}
</div>
<div className="min-w-0">
<h2 className="truncate text-sm font-semibold">
{chat.formattedTitle || chat.name}
</h2>
{/* <p className="text-xs text-[#1ea66a]">
{selected.online ? "Online now" : "Active recently"}
</p> */}
</div>
</div>
{/* <div className="flex items-center gap-1 text-muted-foreground">
<button
aria-label="Start video call"
className="grid size-9 place-items-center rounded-full hover:bg-muted"
>
<VideoIcon size={18} />
</button>
<button
aria-label="Start voice call"
className="grid size-9 place-items-center rounded-full hover:bg-muted"
>
<Phone size={18} />
</button>
<button
aria-label="Chat details"
className="grid size-9 place-items-center rounded-full hover:bg-muted"
>
<EllipsisVertical size={18} />
</button>
</div> */}
</header>
<div className="message-pattern flex-1 px-4 py-6 sm:px-8 flex flex-col-reverse overflow-y-auto">
{/* <div className="mb-6 flex items-center justify-center gap-2 text-[11px] text-muted-foreground">
<span className="h-px flex-1 bg-border" />
<span>Today</span>
<span className="h-px flex-1 bg-border" />
</div> */}
{messageList?.map((item, index) => (
<div
key={`${item.timestamp}-${index}`}
className={`mb-3 flex ${item.fromMe ? "justify-end" : "justify-start"}`}
>
<div className="max-w-[82%] sm:max-w-[65%]">
<p className="mb-1 text-xs text-muted-foreground">
{getFormattedName(item.from) || item.notifyName}
</p>
<div
className={`rounded-2xl px-4 py-2.5 text-sm shadow-sm ${item.fromMe ? "rounded-br-md bg-[#d8f5e8] dark:bg-[#26855c] text-foreground" : "rounded-bl-md bg-card text-card-foreground"}`}
>
{item.isForwarded ? (
<p className="text-xs italic mb-1 text-primary/80">
Forwarded
</p>
) : null}
{item.quotedMsg && item.quotedMsg.type === "chat" ? (
<div
className={cn(
"bg-card/30 px-2 py-1.5 rounded-lg mb-2 mt-1",
!item.fromMe && "bg-[#d8f5e8]/30 dark:bg-[#26855c]/30",
)}
>
<p className="whitespace-pre-wrap">{item.quotedMsg.body}</p>
</div>
) : null}
{item.type === "image" && (
<img
src={"data:image/jpeg;base64," + item.body}
alt=""
className="w-full"
/>
)}
{item.type === "chat" || item.caption ? (
<p className="whitespace-pre-wrap">
{item.caption || item.body}
</p>
) : null}
{item.type === "sticker" && <p className="italic">Sticker</p>}
<div
className={`mt-1 flex items-center justify-end gap-1 text-[10px] ${item.fromMe ? "text-primary" : "text-muted-foreground"}`}
>
<span>{item.timestamp}</span>
{/* {item.fromMe &&
(item.read ? (
<CheckCheck size={14} />
) : (
<Check size={13} />
))} */}
</div>
</div>
</div>
</div>
))}
</div>
<div className="border-t border-border bg-card px-3 py-3 sm:px-6 sm:py-4">
<div className="mx-auto flex max-w-2xl items-end gap-2">
<button
aria-label="Add attachment"
className="grid size-10 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-muted hover:text-muted-foreground"
>
<PaperclipIcon size={19} />
</button>
<div className="flex min-h-10 flex-1 items-center gap-2 rounded-2xl bg-muted px-3">
{/* <button
aria-label="Add emoji"
className="shrink-0 text-muted-foreground hover:text-muted-foreground"
>
<SmileIcon size={19} />
</button> */}
<textarea
value={message}
onChange={(event) => setMessage(event.target.value)}
onKeyDown={(event) => {
if (
event.key === "Enter" &&
!event.shiftKey &&
!event.nativeEvent.isComposing &&
event.keyCode !== 229
) {
event.preventDefault();
sendMessage();
}
}}
placeholder="Write a message..."
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"
/>
</div>
<button
aria-label="Send message"
onClick={sendMessage}
className="grid size-10 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground shadow-sm transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
disabled={!message.trim()}
>
<SendIcon size={17} />
</button>
</div>
<div className="mx-auto mt-2 hidden max-w-2xl items-center justify-center gap-1 text-[10px] text-muted-foreground sm:flex">
<CircleHelpIcon size={12} /> Press Enter to send
</div>
</div>
</section>
);
}
+280
View File
@@ -0,0 +1,280 @@
import { useMemo, useState } from "react";
import {
ChevronDown,
Edit3,
EllipsisVertical,
Search,
Sparkles,
X,
} from "lucide-react";
import { useWAClient } from "@/lib/context";
import { useQuery } from "@tanstack/react-query";
import { cn, getId, getInitial } from "@/lib/utils";
import MessagesSection from "./messages";
// type Chat = {
// id: number;
// name: string;
// initials: string;
// color: string;
// preview: string;
// time: string;
// unread?: number;
// online?: boolean;
// messages: { text: string; time: string; fromMe?: boolean; read?: boolean }[];
// };
// const chats: Chat[] = [
// {
// id: 1,
// name: "Maya Chen",
// initials: "MC",
// color: "bg-rose-200 text-rose-800",
// preview: "That sounds perfect. See you then!",
// time: "10:42 AM",
// online: true,
// messages: [
// { text: "Hey! Are we still on for coffee tomorrow?", time: "10:38 AM" },
// {
// text: "Absolutely. I found a new spot near the park.",
// time: "10:40 AM",
// fromMe: true,
// read: true,
// },
// { text: "That sounds perfect. See you then!", time: "10:42 AM" },
// ],
// },
// {
// id: 2,
// name: "Design team",
// initials: "DT",
// color: "bg-violet-200 text-violet-800",
// preview: "Jon: The new explorations are ready",
// time: "9:16 AM",
// unread: 3,
// messages: [
// { text: "Jon: The new explorations are ready", time: "9:16 AM" },
// ],
// },
// {
// id: 3,
// name: "Alex Morgan",
// initials: "AM",
// color: "bg-amber-200 text-amber-800",
// preview: "You: Thanks for sending that over",
// time: "Yesterday",
// messages: [
// {
// text: "Thanks for sending that over",
// time: "Yesterday",
// fromMe: true,
// read: true,
// },
// ],
// },
// {
// id: 4,
// name: "Weekend plans",
// initials: "WP",
// color: "bg-emerald-200 text-emerald-800",
// preview: "Priya: I can bring the snacks",
// time: "Yesterday",
// unread: 8,
// messages: [{ text: "Priya: I can bring the snacks", time: "Yesterday" }],
// },
// {
// id: 5,
// name: "Noah Williams",
// initials: "NW",
// color: "bg-sky-200 text-sky-800",
// preview: "Voice message",
// time: "Tuesday",
// messages: [{ text: "Voice message", time: "Tuesday" }],
// },
// {
// id: 6,
// name: "Sofia Patel",
// initials: "SP",
// color: "bg-orange-200 text-orange-800",
// preview: "See you at the studio!",
// time: "Monday",
// messages: [{ text: "See you at the studio!", time: "Monday" }],
// },
// ];
export default function Page() {
const [selectedId, setSelectedId] = useState<string>();
const [query, setQuery] = useState("");
const [showSearch, setShowSearch] = useState(false);
const [mobileChat, setMobileChat] = useState(false);
const { client, isReady } = useWAClient();
const { data: chats } = useQuery({
queryKey: ["chats"],
queryFn: () =>
client
.listChats({ limit: 500 })
.then((res) => res.map((i) => ({ ...i, id: getId(i.id) }))),
enabled: isReady,
});
const filteredChats = useMemo(
() =>
chats?.filter(
(chat) =>
chat.formattedTitle?.toLowerCase().includes(query.toLowerCase()) ||
chat.lastMessage?.body?.toLowerCase().includes(query.toLowerCase()),
),
[chats, query],
);
function openChat(id: string) {
setSelectedId(id);
setMobileChat(true);
}
const selectedChat = chats?.find((chat) => chat.id === selectedId);
return (
<main className="min-h-dvh bg-background p-0 text-foreground sm:p-4 lg:p-6">
<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
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"}`}
>
<header className="flex items-center justify-between border-b border-border px-5 py-5">
<div className="flex items-center gap-3">
<div className="grid size-10 place-items-center rounded-xl bg-accent text-accent-foreground">
<Sparkles aria-hidden="true" />
</div>
<div>
<h1 className="text-lg font-semibold tracking-tight">
Messages
</h1>
<p className="text-xs text-muted-foreground">Stay connected</p>
</div>
</div>
<div className="flex items-center gap-1">
<button
aria-label="New message"
className="grid size-9 place-items-center rounded-full text-muted-foreground transition hover:bg-muted hover:text-foreground"
>
<Edit3 size={18} />
</button>
<button
aria-label="More options"
className="grid size-9 place-items-center rounded-full text-muted-foreground transition hover:bg-muted hover:text-foreground"
>
<EllipsisVertical size={19} />
</button>
</div>
</header>
<div className="px-4 py-3">
{showSearch ? (
<div className="flex items-center gap-2 rounded-xl bg-muted px-3 py-2">
<Search size={17} className="text-muted-foreground" />
<input
autoFocus
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search conversations"
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
<button
aria-label="Close search"
onClick={() => {
setShowSearch(false);
setQuery("");
}}
>
<X size={16} className="text-muted-foreground" />
</button>
</div>
) : (
<button
onClick={() => setShowSearch(true)}
className="flex w-full items-center gap-3 rounded-xl bg-muted px-3 py-2.5 text-left text-sm text-muted-foreground transition hover:bg-border"
>
<Search size={17} /> Search conversations
</button>
)}
</div>
<div className="flex items-center gap-2 px-5 pb-2 text-xs font-medium text-muted-foreground">
<span className="text-primary">All</span>
<span>·</span>
<span>Unread</span>
<span>·</span>
<span>Groups</span>
</div>
<div className="flex-1 overflow-y-auto px-2 pb-3">
{filteredChats?.map((chat) => (
<button
key={chat.id}
onClick={() => openChat(chat.id)}
className={`flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left transition ${selectedId === chat.id ? "bg-accent" : "hover:bg-muted/70"}`}
>
<div
className={cn(
"relative grid size-11 shrink-0 place-items-center rounded-full text-sm font-semibold bg-rose-200 text-rose-800",
)}
>
{getInitial(chat.formattedTitle)}
{/* {chat.initials}
{chat.online && (
<span className="absolute bottom-0 right-0 size-3 rounded-full border-2 border-card bg-primary" />
)} */}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2">
<p className="truncate text-sm font-semibold">
{chat.formattedTitle || chat.name}
</p>
{/* <span className="shrink-0 text-[11px] text-muted-foreground">
{chat.timestamp}
</span> */}
</div>
<div className="mt-1 flex items-center justify-between gap-2">
<p className="truncate text-xs text-muted-foreground">
{chat.lastMessage?.body?.substring(0, 50)}
</p>
{/* {chat.unread && (
<span className="grid size-5 shrink-0 place-items-center rounded-full bg-primary text-[10px] font-bold text-primary-foreground">
{chat.unread}
</span>
)} */}
</div>
</div>
</button>
))}
</div>
<div className="border-t border-border px-5 py-4">
<div className="flex items-center gap-3">
<div className="grid size-9 place-items-center rounded-full bg-border text-xs font-semibold text-muted-foreground">
JD
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium">Jordan Davis</p>
<p className="truncate text-xs text-muted-foreground">
jordan@example.com
</p>
</div>
<button
aria-label="Account menu"
className="text-muted-foreground"
>
<ChevronDown size={17} />
</button>
</div>
</div>
</aside>
{selectedChat ? (
<MessagesSection
chat={selectedChat}
mobileChat={mobileChat}
setMobileChat={setMobileChat}
/>
) : null}
</div>
</main>
);
}
+57
View File
@@ -0,0 +1,57 @@
import { Button as ButtonPrimitive } from "@base-ui/react/button";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "cn";
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-md border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/80",
outline:
"border-border bg-background shadow-xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default:
"h-9 gap-1.5 px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
xs: "h-6 gap-1 rounded-[min(var(--radius-md),8px)] px-2 text-xs in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1 rounded-[min(var(--radius-md),10px)] px-2.5 in-data-[slot=button-group]:rounded-md has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5",
lg: "h-10 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-9",
"icon-xs":
"size-6 rounded-[min(var(--radius-md),8px)] in-data-[slot=button-group]:rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-8 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-md",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant = "default",
size = "default",
...props
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
return (
<ButtonPrimitive
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
export { Button, buttonVariants };
+56
View File
@@ -0,0 +1,56 @@
import { createContext, useContext, useEffect, useRef, useState } from "react";
import type { WhatsAppClient } from "@client/whatsapp";
import { useQuery } from "@tanstack/react-query";
import wa from "./wa-client";
export const WAContext = createContext<{
client: WhatsAppClient;
isConnected: boolean;
isReady: boolean;
}>(null!);
export function useWAClient() {
const ctx = useContext(WAContext);
if (!ctx) throw new Error("useWAClient must be used within a WAProvider");
return ctx;
}
export function WAProvider({
children,
url,
}: {
children: React.ReactNode;
url?: string;
}) {
const isInitialized = useRef(false);
const [isConnected, setConnected] = useState(false);
const { data: status } = useQuery({
queryKey: ["status"],
queryFn: () => wa.status(),
enabled: isConnected,
});
useEffect(() => {
if (isInitialized.current) return;
wa.connect();
isInitialized.current = true;
wa.on("status", setConnected);
}, [url]);
console.log("status", status);
return (
<WAContext.Provider
value={{
client: wa,
isConnected,
isReady: status?.authenticated && status?.ready ? true : false,
}}
>
{children}
</WAContext.Provider>
);
}
+31
View File
@@ -0,0 +1,31 @@
import type { ContactDTO, MessageIdDTO, SerializedId } from "@shared/dto";
export { cn } from "cn";
export function getId(id?: string | SerializedId | MessageIdDTO | null) {
if (!id) return "";
return typeof id === "string" ? id : (id._serialized ?? "");
}
export function getInitial(name?: string | null) {
return (
name
?.split(" ")
.map((i) => i[0])
.slice(0, 2)
.join("") || ""
);
}
export function getFormattedName(
name: string | SerializedId | ContactDTO | null | undefined,
): string {
if (!name) return "";
return typeof name === "string"
? name
: typeof name.formattedName === "string"
? name.formattedName
: "user" in name
? name.user || ""
: "";
}
+5
View File
@@ -0,0 +1,5 @@
import { WhatsAppClient } from "@client/whatsapp";
const wa = new WhatsAppClient(import.meta.env.VITE_WHATSAPP_URL);
export default wa;
+18
View File
@@ -0,0 +1,18 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { WAProvider } from "./lib/context.tsx";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./app/page.tsx";
import "./app/globals.css";
const queryCLient = new QueryClient();
createRoot(document.getElementById("root")!).render(
<StrictMode>
<QueryClientProvider client={queryCLient}>
<WAProvider url={import.meta.env.VITE_WHATSAPP_URL}>
<App />
</WAProvider>
</QueryClientProvider>
</StrictMode>,
);
+32
View File
@@ -0,0 +1,32 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"paths": {
"@/*": ["./src/*"],
"@shared/*": ["../src/shared/*"],
"@client/*": ["../src/client/*"]
}
},
"include": ["src"]
}
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"],
"@shared/*": ["../src/shared/*"],
"@client/*": ["../src/client/*"]
}
},
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+16
View File
@@ -0,0 +1,16 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import path from "path";
import tailwindcss from "@tailwindcss/vite";
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(import.meta.dirname, "./src"),
"@shared": path.resolve(import.meta.dirname, "../src/shared"),
"@client": path.resolve(import.meta.dirname, "../src/client"),
},
},
});