Compare commits
2
Commits
65a2e534d7
...
9792e49123
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9792e49123 | ||
|
|
6e852ab224 |
Vendored
+11
-8
@@ -2,7 +2,7 @@
|
|||||||
// ==UserScript==
|
// ==UserScript==
|
||||||
// @name WhatsApp Web Bridge
|
// @name WhatsApp Web Bridge
|
||||||
// @namespace https://rul.sh/
|
// @namespace https://rul.sh/
|
||||||
// @version 0.0.7
|
// @version 0.0.8
|
||||||
// @description WhatsApp Web WebSocket bridge
|
// @description WhatsApp Web WebSocket bridge
|
||||||
// @match https://web.whatsapp.com/*
|
// @match https://web.whatsapp.com/*
|
||||||
// @updateURL https://git.rul.sh/khairul169/whatsapp-bridge/raw/branch/main/dist/whatsapp-bridge.user.js
|
// @updateURL https://git.rul.sh/khairul169/whatsapp-bridge/raw/branch/main/dist/whatsapp-bridge.user.js
|
||||||
@@ -267,7 +267,7 @@
|
|||||||
ok: false,
|
ok: false,
|
||||||
error: {
|
error: {
|
||||||
code: "ERROR",
|
code: "ERROR",
|
||||||
message: err instanceof Error ? err.message : String(err)
|
message: typeof err === "object" && "message" in err ? err.message : String(err)
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -309,12 +309,15 @@
|
|||||||
const result = await WPP.chat.sendTextMessage(
|
const result = await WPP.chat.sendTextMessage(
|
||||||
request.params.chatId,
|
request.params.chatId,
|
||||||
request.params.text,
|
request.params.text,
|
||||||
{
|
request.params.options
|
||||||
delay: request.params.options?.delay,
|
);
|
||||||
quotedMsg: request.params.options?.quotedMsg,
|
return serialize(result);
|
||||||
mentionedList: request.params.options?.mentionedList,
|
}
|
||||||
waitForAck: request.params.options?.waitForAck
|
case "sendFile": {
|
||||||
}
|
const result = await WPP.chat.sendFileMessage(
|
||||||
|
request.params.chatId,
|
||||||
|
request.params.data,
|
||||||
|
request.params.options
|
||||||
);
|
);
|
||||||
return serialize(result);
|
return serialize(result);
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+2
-2
File diff suppressed because one or more lines are too long
+2
-1
@@ -1,6 +1,7 @@
|
|||||||
import * as esbuild from "esbuild";
|
import * as esbuild from "esbuild";
|
||||||
|
import pkgInfo from "./package.json";
|
||||||
|
|
||||||
const VERSION = "0.0.7";
|
const VERSION = pkgInfo.version;
|
||||||
const IS_DIST =
|
const IS_DIST =
|
||||||
process.argv.indexOf("--prod") !== -1 || process.argv.indexOf("-p") !== -1;
|
process.argv.indexOf("--prod") !== -1 || process.argv.indexOf("-p") !== -1;
|
||||||
const WS_URL = IS_DIST ? process.env.WS_URL : "ws://127.0.0.1:8787";
|
const WS_URL = IS_DIST ? process.env.WS_URL : "ws://127.0.0.1:8787";
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "whatsapp-bridge",
|
"name": "whatsapp-bridge",
|
||||||
"module": "index.ts",
|
"module": "index.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
"version": "0.0.8",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "bun run esbuild.mjs",
|
"build": "bun run esbuild.mjs",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type {
|
import type {
|
||||||
GetMessagesParams,
|
GetMessagesParams,
|
||||||
ListChatsParams,
|
ListChatsParams,
|
||||||
|
SendFileParams,
|
||||||
SendTextParams,
|
SendTextParams,
|
||||||
} from "../shared/protocol";
|
} from "../shared/protocol";
|
||||||
import type {
|
import type {
|
||||||
@@ -158,6 +159,10 @@ export class WhatsAppClient {
|
|||||||
return this.request<any>("sendText", params);
|
return this.request<any>("sendText", params);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sendFile(params: SendFileParams) {
|
||||||
|
return this.request<any>("sendFile", params);
|
||||||
|
}
|
||||||
|
|
||||||
getMedia(msgId: string) {
|
getMedia(msgId: string) {
|
||||||
return this.request<string>("getMedia", msgId);
|
return this.request<string>("getMedia", msgId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -214,6 +214,7 @@ wss.on("connection", (ws) => {
|
|||||||
case "listGroups":
|
case "listGroups":
|
||||||
case "getMessages":
|
case "getMessages":
|
||||||
case "sendText":
|
case "sendText":
|
||||||
|
case "sendFile":
|
||||||
case "getMedia":
|
case "getMedia":
|
||||||
case "exec":
|
case "exec":
|
||||||
result = await call(wa, request.method, request.params);
|
result = await call(wa, request.method, request.params);
|
||||||
|
|||||||
+17
-6
@@ -40,16 +40,26 @@ export interface GetMessagesParams {
|
|||||||
id?: string;
|
id?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SendTextOptions {
|
||||||
|
delay?: number;
|
||||||
|
quotedMsg?: string;
|
||||||
|
mentionedList?: string[];
|
||||||
|
waitForAck?: boolean;
|
||||||
|
caption?: string;
|
||||||
|
filename?: string;
|
||||||
|
mimetype?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface SendTextParams {
|
export interface SendTextParams {
|
||||||
chatId: string;
|
chatId: string;
|
||||||
text: string;
|
text: string;
|
||||||
|
options?: SendTextOptions;
|
||||||
|
}
|
||||||
|
|
||||||
options?: {
|
export interface SendFileParams {
|
||||||
delay?: number;
|
chatId: string;
|
||||||
quotedMsg?: string;
|
data: string;
|
||||||
mentionedList?: string[];
|
options?: SendTextOptions;
|
||||||
waitForAck?: boolean;
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GetContactsParams {
|
export interface GetContactsParams {
|
||||||
@@ -64,5 +74,6 @@ export type BridgeRequest =
|
|||||||
| RpcRequest<"listGroups">
|
| RpcRequest<"listGroups">
|
||||||
| RpcRequest<"getMessages", GetMessagesParams>
|
| RpcRequest<"getMessages", GetMessagesParams>
|
||||||
| RpcRequest<"sendText", SendTextParams>
|
| RpcRequest<"sendText", SendTextParams>
|
||||||
|
| RpcRequest<"sendFile", SendFileParams>
|
||||||
| RpcRequest<"getMedia", string>
|
| RpcRequest<"getMedia", string>
|
||||||
| RpcRequest<"exec", string>;
|
| RpcRequest<"exec", string>;
|
||||||
|
|||||||
+15
-7
@@ -48,7 +48,10 @@ function error(id: string, err: unknown) {
|
|||||||
ok: false,
|
ok: false,
|
||||||
error: {
|
error: {
|
||||||
code: "ERROR",
|
code: "ERROR",
|
||||||
message: err instanceof Error ? err.message : String(err),
|
message:
|
||||||
|
typeof err === "object" && "message" in err!
|
||||||
|
? err.message
|
||||||
|
: String(err),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -107,12 +110,17 @@ async function handleRequest(request: BridgeRequest) {
|
|||||||
const result = await WPP.chat.sendTextMessage(
|
const result = await WPP.chat.sendTextMessage(
|
||||||
request.params.chatId,
|
request.params.chatId,
|
||||||
request.params.text,
|
request.params.text,
|
||||||
{
|
request.params.options,
|
||||||
delay: request.params.options?.delay,
|
);
|
||||||
quotedMsg: request.params.options?.quotedMsg,
|
|
||||||
mentionedList: request.params.options?.mentionedList,
|
return serialize(result);
|
||||||
waitForAck: request.params.options?.waitForAck,
|
}
|
||||||
},
|
|
||||||
|
case "sendFile": {
|
||||||
|
const result = await WPP.chat.sendFileMessage(
|
||||||
|
request.params.chatId,
|
||||||
|
request.params.data,
|
||||||
|
request.params.options,
|
||||||
);
|
);
|
||||||
|
|
||||||
return serialize(result);
|
return serialize(result);
|
||||||
|
|||||||
Vendored
+22
-10
@@ -1,5 +1,20 @@
|
|||||||
declare const __WS_URL__: string;
|
declare const __WS_URL__: string;
|
||||||
|
|
||||||
|
type SendMessageOptions = {
|
||||||
|
delay?: number;
|
||||||
|
detectMentioned?: boolean;
|
||||||
|
markIsRead?: boolean;
|
||||||
|
mentionedList?: string[];
|
||||||
|
messageId?: string;
|
||||||
|
quotedMsg?: string;
|
||||||
|
quotedMsgPayload?: string;
|
||||||
|
waitForAck?: boolean;
|
||||||
|
isViewOnce?: boolean;
|
||||||
|
filename?: string;
|
||||||
|
mimetype?: string;
|
||||||
|
type?: string;
|
||||||
|
};
|
||||||
|
|
||||||
declare const WPP: {
|
declare const WPP: {
|
||||||
isReady: boolean;
|
isReady: boolean;
|
||||||
|
|
||||||
@@ -38,16 +53,13 @@ declare const WPP: {
|
|||||||
sendTextMessage(
|
sendTextMessage(
|
||||||
chatId: string,
|
chatId: string,
|
||||||
text: string,
|
text: string,
|
||||||
options?: {
|
options?: SendMessageOptions,
|
||||||
delay?: number;
|
): Promise<any>;
|
||||||
detectMentioned?: boolean;
|
|
||||||
markIsRead?: boolean;
|
sendFileMessage(
|
||||||
mentionedList?: string[];
|
chatId: string,
|
||||||
messageId?: string;
|
data: string,
|
||||||
quotedMsg?: string;
|
options?: SendMessageOptions,
|
||||||
quotedMsgPayload?: string;
|
|
||||||
waitForAck?: boolean;
|
|
||||||
},
|
|
||||||
): Promise<any>;
|
): Promise<any>;
|
||||||
|
|
||||||
downloadMedia(msgId: string): Promise<Blob>;
|
downloadMedia(msgId: string): Promise<Blob>;
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
"cn": "^0.3.0",
|
"cn": "^0.3.0",
|
||||||
"dayjs": "^1.11.23",
|
"dayjs": "^1.11.23",
|
||||||
"lucide-react": "^1.46.0",
|
"lucide-react": "^1.46.0",
|
||||||
|
"nanoid": "^6.0.1",
|
||||||
"react": "^19.2.8",
|
"react": "^19.2.8",
|
||||||
"react-dom": "^19.2.8",
|
"react-dom": "^19.2.8",
|
||||||
"shadcn": "^4.21.0",
|
"shadcn": "^4.21.0",
|
||||||
|
|||||||
Generated
+10
@@ -32,6 +32,9 @@ importers:
|
|||||||
lucide-react:
|
lucide-react:
|
||||||
specifier: ^1.46.0
|
specifier: ^1.46.0
|
||||||
version: 1.46.0([email protected])
|
version: 1.46.0([email protected])
|
||||||
|
nanoid:
|
||||||
|
specifier: ^6.0.1
|
||||||
|
version: 6.0.1
|
||||||
react:
|
react:
|
||||||
specifier: ^19.2.8
|
specifier: ^19.2.8
|
||||||
version: 19.3.0
|
version: 19.3.0
|
||||||
@@ -1488,6 +1491,11 @@ packages:
|
|||||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
|
[email protected]:
|
||||||
|
resolution: {integrity: sha512-3wVS3i51pE2pi1k5FFL/95BGfVS0kSsvDVuGXHOtxox/TywUmtgq+3qiTOTbs9J7KfHaXPiN171k/A6dBnaXFw==}
|
||||||
|
engines: {node: ^22 || ^24 || >=26}
|
||||||
|
hasBin: true
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==}
|
resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==}
|
||||||
engines: {node: '>=18'}
|
engines: {node: '>=18'}
|
||||||
@@ -3216,6 +3224,8 @@ snapshots:
|
|||||||
|
|
||||||
[email protected]: {}
|
[email protected]: {}
|
||||||
|
|
||||||
|
[email protected]: {}
|
||||||
|
|
||||||
[email protected]:
|
[email protected]:
|
||||||
dependencies:
|
dependencies:
|
||||||
content-type: 2.1.0
|
content-type: 2.1.0
|
||||||
|
|||||||
+7
-15
@@ -1,9 +1,8 @@
|
|||||||
import { useWAClient } from "./context";
|
|
||||||
import Avatar from "@/components/ui/avatar";
|
import Avatar from "@/components/ui/avatar";
|
||||||
|
import { useChats } from "@/hooks/useChats";
|
||||||
import { useContacts } from "@/hooks/useContact";
|
import { useContacts } from "@/hooks/useContact";
|
||||||
import { getFormattedName, getId } from "@/lib/utils";
|
import { getFormattedName } from "@/lib/utils";
|
||||||
import type { ChatDTO, ContactDTO } from "@shared/dto";
|
import type { ChatDTO, ContactDTO } from "@shared/dto";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
import dayjs from "dayjs";
|
import dayjs from "dayjs";
|
||||||
import {
|
import {
|
||||||
FaceGrinningIcon,
|
FaceGrinningIcon,
|
||||||
@@ -17,21 +16,14 @@ import {
|
|||||||
import { useMemo, useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
selected: ChatDTO | null;
|
selected: string | null;
|
||||||
onSelect: (chat: ChatDTO) => void;
|
onSelect: (chat: string) => void;
|
||||||
};
|
};
|
||||||
export default function ChatsSection({ selected, onSelect }: Props) {
|
export default function ChatsSection({ selected, onSelect }: Props) {
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
|
|
||||||
const { client, isReady } = useWAClient();
|
|
||||||
const contacts = useContacts();
|
const contacts = useContacts();
|
||||||
const { data: chats } = useQuery({
|
const { data: chats } = useChats({
|
||||||
queryKey: ["chats"],
|
|
||||||
queryFn: () =>
|
|
||||||
client
|
|
||||||
.listChats({ limit: 500 })
|
|
||||||
.then((res) => res.map((i) => ({ ...i, id: getId(i.id) }))),
|
|
||||||
enabled: isReady,
|
|
||||||
refetchInterval: 10_000,
|
refetchInterval: 10_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -88,8 +80,8 @@ export default function ChatsSection({ selected, onSelect }: Props) {
|
|||||||
{filteredChats?.map((chat) => (
|
{filteredChats?.map((chat) => (
|
||||||
<button
|
<button
|
||||||
key={chat.id}
|
key={chat.id}
|
||||||
onClick={() => onSelect(chat)}
|
onClick={() => onSelect(chat.id)}
|
||||||
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 === chat.id ? "bg-accent" : "hover:bg-muted/70"}`}
|
||||||
>
|
>
|
||||||
<Avatar
|
<Avatar
|
||||||
name={chat.formattedTitle || chat.name}
|
name={chat.formattedTitle || chat.name}
|
||||||
|
|||||||
+295
-100
@@ -1,55 +1,97 @@
|
|||||||
import { useWAClient } from "./context";
|
import { useWAClient } from "./context";
|
||||||
import { getFormattedName, getId } from "@/lib/utils";
|
import { getFilesAsBase64, getFormattedName, getId } from "@/lib/utils";
|
||||||
import type { ChatDTO } from "@shared/dto";
|
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
|
||||||
import { cn } from "cn";
|
import { cn } from "cn";
|
||||||
import {
|
import {
|
||||||
ArrowLeftIcon,
|
ArrowLeftIcon,
|
||||||
CheckCheckIcon,
|
CheckCheckIcon,
|
||||||
CheckIcon,
|
CheckIcon,
|
||||||
|
Loader2Icon,
|
||||||
PaperclipIcon,
|
PaperclipIcon,
|
||||||
PhoneCallIcon,
|
PhoneCallIcon,
|
||||||
SendIcon,
|
SendIcon,
|
||||||
|
XIcon,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import React, { useMemo, useState } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import dayjs from "dayjs";
|
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 { useContacts } from "@/hooks/useContact";
|
import { useContacts } from "@/hooks/useContact";
|
||||||
import { useMessageEvent } from "@/hooks/useMessageEvent";
|
import { useMessageEvent } from "@/hooks/useMessageEvent";
|
||||||
|
import { useHashRouter } from "@/hooks/useHashRouter";
|
||||||
|
import { useChats } from "@/hooks/useChats";
|
||||||
|
import Avatar from "@/components/ui/avatar";
|
||||||
|
import { useIntersection } from "@/hooks/useIntersection";
|
||||||
|
import Paragraph from "@/components/paragraph";
|
||||||
|
import { nanoid } from "nanoid";
|
||||||
|
|
||||||
dayjs.extend(relativeTime);
|
dayjs.extend(relativeTime);
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
chat: ChatDTO;
|
chatId: string | null;
|
||||||
mobileChat: boolean;
|
maxCount?: number;
|
||||||
setMobileChat: React.Dispatch<React.SetStateAction<boolean>>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function MessagesSection({
|
export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
|
||||||
chat,
|
|
||||||
mobileChat,
|
|
||||||
setMobileChat,
|
|
||||||
}: Props) {
|
|
||||||
const { client, isReady } = useWAClient();
|
const { client, isReady } = useWAClient();
|
||||||
const [message, setMessage] = useState("");
|
const router = useHashRouter();
|
||||||
const [isPending, setPending] = useState(false);
|
|
||||||
|
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const { data: chats } = useChats();
|
||||||
const { data: contacts } = useContacts();
|
const { data: contacts } = useContacts();
|
||||||
|
|
||||||
const chatId = getId(chat.id);
|
const {
|
||||||
const { data: messages, refetch } = useQuery({
|
data: messages,
|
||||||
|
isLoading,
|
||||||
|
refetch,
|
||||||
|
fetchNextPage,
|
||||||
|
hasNextPage,
|
||||||
|
isFetchingNextPage,
|
||||||
|
} = useInfiniteQuery({
|
||||||
queryKey: ["messages", chatId],
|
queryKey: ["messages", chatId],
|
||||||
queryFn: () => client.getMessages({ chatId, count: 50 }),
|
queryFn: ({ pageParam }) =>
|
||||||
|
client
|
||||||
|
.getMessages({
|
||||||
|
chatId: chatId!,
|
||||||
|
count: maxCount,
|
||||||
|
direction: "before",
|
||||||
|
id: pageParam,
|
||||||
|
})
|
||||||
|
.then((i) => i.reverse()),
|
||||||
|
initialPageParam: undefined as string | undefined,
|
||||||
enabled: Boolean(chatId && isReady),
|
enabled: Boolean(chatId && isReady),
|
||||||
refetchInterval: 10_1000,
|
|
||||||
|
getNextPageParam: (lastPage) => {
|
||||||
|
if (lastPage.length < maxCount) return undefined;
|
||||||
|
return getId(lastPage[lastPage.length - 1]?.id);
|
||||||
|
},
|
||||||
|
select: (data) => data.pages.flat(),
|
||||||
});
|
});
|
||||||
|
|
||||||
useMessageEvent((data) => {
|
useMessageEvent((data) => {
|
||||||
if (data.chatId === chatId) refetch();
|
if (data.chatId !== chatId) return;
|
||||||
|
|
||||||
|
queryClient.setQueryData(["messages", chatId], (old: any) => {
|
||||||
|
if (!old) return old;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...old,
|
||||||
|
pages: [[data, ...old.pages[0]], ...old.pages.slice(1)],
|
||||||
|
};
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const endScrollRef = useIntersection(() => {
|
||||||
|
if (hasNextPage && !isFetchingNextPage && !isLoading) {
|
||||||
|
fetchNextPage();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const chat = useMemo(
|
||||||
|
() => chats?.find((c) => c.id === chatId),
|
||||||
|
[chats, chatId],
|
||||||
|
);
|
||||||
|
|
||||||
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))
|
||||||
@@ -76,45 +118,31 @@ export default function MessagesSection({
|
|||||||
from,
|
from,
|
||||||
quotedMsg,
|
quotedMsg,
|
||||||
};
|
};
|
||||||
})
|
});
|
||||||
?.reverse();
|
|
||||||
}, [messages, contacts]);
|
}, [messages, contacts]);
|
||||||
|
|
||||||
async function sendMessage() {
|
|
||||||
const text = message.trim();
|
|
||||||
if (!text) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
setPending(true);
|
|
||||||
await client.sendText({ chatId, text, options: { waitForAck: true } });
|
|
||||||
setTimeout(refetch, 100);
|
|
||||||
setMessage("");
|
|
||||||
} catch (err) {
|
|
||||||
alert((err as Error).message);
|
|
||||||
} finally {
|
|
||||||
setPending(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className={`flex min-w-0 flex-1 flex-col bg-muted ${mobileChat ? "flex" : "hidden md:flex"}`}
|
className={`flex min-w-0 flex-1 flex-col bg-muted ${chatId ? "flex" : "hidden md:flex"}`}
|
||||||
>
|
>
|
||||||
<header className="flex items-center justify-between border-b border-border bg-card px-4 py-3 sm:px-6">
|
<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">
|
<div className="flex min-w-0 items-center gap-3">
|
||||||
<button
|
<button
|
||||||
aria-label="Back to conversations"
|
aria-label="Back to conversations"
|
||||||
onClick={() => setMobileChat(false)}
|
onClick={() => router.goBack()}
|
||||||
className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-muted md:hidden cursor-pointer"
|
className="grid size-9 place-items-center rounded-full text-muted-foreground hover:bg-muted md:hidden cursor-pointer -ml-2"
|
||||||
>
|
>
|
||||||
<ArrowLeftIcon size={19} />
|
<ArrowLeftIcon size={19} />
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<Avatar name={chat.formattedTitle || chat.name} className="size-10" />
|
<Avatar
|
||||||
|
name={chat?.formattedTitle || chat?.name}
|
||||||
|
className="size-10"
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<h2 className="truncate text-sm font-semibold">
|
<h2 className="truncate text-sm font-semibold">
|
||||||
{chat.formattedTitle || chat.name}
|
{chat?.formattedTitle || chat?.name}
|
||||||
</h2>
|
</h2>
|
||||||
|
|
||||||
{/* <p className="text-xs text-[#1ea66a]">
|
{/* <p className="text-xs text-[#1ea66a]">
|
||||||
@@ -153,7 +181,7 @@ export default function MessagesSection({
|
|||||||
|
|
||||||
{messageList?.map((item, index) => (
|
{messageList?.map((item, index) => (
|
||||||
<div
|
<div
|
||||||
id={item.id}
|
id={item.id.replace(/^(?:false_|true_)/, "")}
|
||||||
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"}`}
|
||||||
>
|
>
|
||||||
@@ -178,33 +206,37 @@ export default function MessagesSection({
|
|||||||
["chat", "image", "document"].includes(
|
["chat", "image", "document"].includes(
|
||||||
item.quotedMsg.type as string,
|
item.quotedMsg.type as string,
|
||||||
) ? (
|
) ? (
|
||||||
<a
|
<button
|
||||||
href="#"
|
type="button"
|
||||||
onClick={(e) => {
|
onClick={() => {
|
||||||
e.preventDefault();
|
const id = getId(item.quotedMsgId).replace(
|
||||||
const el = document.getElementById(
|
/^(?:false_|true_)/,
|
||||||
getId(item.quotedMsgId),
|
"",
|
||||||
);
|
);
|
||||||
|
const el = document.getElementById(id);
|
||||||
if (el) {
|
if (el) {
|
||||||
el.scrollIntoView({ behavior: "smooth" });
|
el.scrollIntoView({ behavior: "smooth" });
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
className={cn(
|
className={cn(
|
||||||
"bg-card/30 px-2 py-1.5 rounded-lg mb-2 mt-1 cursor-pointer block",
|
"bg-card/30 px-2 py-1.5 rounded-lg mb-2 mt-1 cursor-pointer block text-left",
|
||||||
!item.fromMe && "bg-[#d8f5e8]/30 dark:bg-[#26855c]/30",
|
!item.fromMe && "bg-[#d8f5e8]/30 dark:bg-[#26855c]/30",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
{getFormattedName(item.quotedMsg.from)}
|
{getFormattedName(item.quotedMsg.from)}
|
||||||
</p>
|
</p>
|
||||||
<p className="whitespace-pre-wrap wrap-break-word">
|
|
||||||
{item.quotedMsg.filename ||
|
<Paragraph
|
||||||
|
text={
|
||||||
|
item.quotedMsg.filename ||
|
||||||
item.quotedMsg.caption ||
|
item.quotedMsg.caption ||
|
||||||
(item.quotedMsg.type === "chat"
|
(item.quotedMsg.type === "chat"
|
||||||
? item.quotedMsg.body
|
? item.quotedMsg.body
|
||||||
: "Quoted")}
|
: "Quoted")
|
||||||
</p>
|
}
|
||||||
</a>
|
/>
|
||||||
|
</button>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{item.type === "image" ||
|
{item.type === "image" ||
|
||||||
@@ -215,9 +247,7 @@ export default function MessagesSection({
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{item.type === "chat" || item.caption ? (
|
{item.type === "chat" || item.caption ? (
|
||||||
<p className="whitespace-pre-wrap wrap-break-word">
|
<Paragraph text={item.caption || item.body} />
|
||||||
{item.caption || item.body}
|
|
||||||
</p>
|
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{item.type === "call_log" && (
|
{item.type === "call_log" && (
|
||||||
@@ -249,56 +279,221 @@ export default function MessagesSection({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
|
<div ref={endScrollRef} className="h-1" />
|
||||||
|
|
||||||
|
<div className="mb-6 flex items-center justify-center gap-2 text-[11px] text-muted-foreground">
|
||||||
|
<span className="h-px flex-1 bg-border" />
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{isLoading ||
|
||||||
|
(isFetchingNextPage && (
|
||||||
|
<Loader2Icon className="animate-spin size-4" />
|
||||||
|
))}
|
||||||
|
<span>
|
||||||
|
{isLoading || isFetchingNextPage
|
||||||
|
? "Loading..."
|
||||||
|
: "End of messages"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className="h-px flex-1 bg-border" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="border-t border-border bg-card px-3 py-3 sm:px-6 sm:py-4">
|
<MessageInputSection chatId={chatId} refetch={refetch} />
|
||||||
<div className="mx-auto flex max-w-2xl items-end gap-2">
|
</section>
|
||||||
<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"
|
|
||||||
>
|
function MessageInputSection({
|
||||||
<PaperclipIcon size={19} />
|
chatId,
|
||||||
</button>
|
refetch,
|
||||||
<div className="flex min-h-10 flex-1 items-center gap-2 rounded-2xl bg-muted px-3">
|
}: {
|
||||||
{/* <button
|
chatId?: string | null;
|
||||||
|
refetch: () => void;
|
||||||
|
}) {
|
||||||
|
const { client, isReady } = useWAClient();
|
||||||
|
const [message, setMessage] = useState("");
|
||||||
|
const [files, setFiles] = useState<{ id: string; file: File }[]>([]);
|
||||||
|
const [isPending, setPending] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
function onDragOver(e: DragEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
function onDrop(e: DragEvent) {
|
||||||
|
const fileList = e.dataTransfer?.files || [];
|
||||||
|
if (fileList) {
|
||||||
|
e.preventDefault();
|
||||||
|
onFileAttached([...fileList]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("dragover", onDragOver);
|
||||||
|
document.addEventListener("drop", onDrop);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("dragover", onDragOver);
|
||||||
|
document.removeEventListener("drop", onDrop);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
function onFileAttached(files: File[]) {
|
||||||
|
setFiles((f) => [...f, ...files.map((file) => ({ id: nanoid(), file }))]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPaste(e: React.ClipboardEvent<HTMLTextAreaElement>) {
|
||||||
|
const fileList = e.clipboardData?.files || [];
|
||||||
|
if (fileList.length > 0) {
|
||||||
|
e.preventDefault();
|
||||||
|
onFileAttached([...fileList]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendMessage() {
|
||||||
|
const text = message.trim();
|
||||||
|
if ((!text && !files.length) || !chatId || !isReady) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setPending(true);
|
||||||
|
const options = { waitForAck: true };
|
||||||
|
|
||||||
|
if (files.length > 0) {
|
||||||
|
const fileList = await getFilesAsBase64(files.map((f) => f.file));
|
||||||
|
for (let i = 0; i < fileList.length; i++) {
|
||||||
|
const file = fileList[i];
|
||||||
|
await client.sendFile({
|
||||||
|
chatId,
|
||||||
|
data: file,
|
||||||
|
options: {
|
||||||
|
...options,
|
||||||
|
caption: i === 0 ? text : undefined,
|
||||||
|
filename: files[i].file.name,
|
||||||
|
mimetype: files[i].file.type,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await client.sendText({ chatId, text, options });
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(refetch, 1000);
|
||||||
|
setFiles([]);
|
||||||
|
setMessage("");
|
||||||
|
} catch (err) {
|
||||||
|
alert((err as Error).message);
|
||||||
|
} finally {
|
||||||
|
setPending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onRemoveAttachment(id: string) {
|
||||||
|
setFiles((f) => f.filter((file) => file.id !== id));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border-t border-border bg-card px-3 py-3 sm:py-4">
|
||||||
|
{files.length > 0 && (
|
||||||
|
<div className="flex items-center gap-2 mb-3 overflow-x-auto">
|
||||||
|
{files.map((i) => (
|
||||||
|
<AttachmentPreview
|
||||||
|
key={i.id}
|
||||||
|
file={i.file}
|
||||||
|
onRemove={() => onRemoveAttachment(i.id)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex 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"
|
aria-label="Add emoji"
|
||||||
className="shrink-0 text-muted-foreground hover:text-muted-foreground"
|
className="shrink-0 text-muted-foreground hover:text-muted-foreground"
|
||||||
>
|
>
|
||||||
<SmileIcon size={19} />
|
<SmileIcon size={19} />
|
||||||
</button> */}
|
</button> */}
|
||||||
|
|
||||||
<textarea
|
<textarea
|
||||||
value={message}
|
value={message}
|
||||||
onChange={(event) => setMessage(event.target.value)}
|
onChange={(event) => setMessage(event.target.value)}
|
||||||
onKeyDown={(event) => {
|
onPaste={onPaste}
|
||||||
if (
|
onKeyDown={(event) => {
|
||||||
event.key === "Enter" &&
|
if (
|
||||||
!event.shiftKey &&
|
event.key === "Enter" &&
|
||||||
!event.nativeEvent.isComposing &&
|
!event.shiftKey &&
|
||||||
event.keyCode !== 229
|
!event.nativeEvent.isComposing &&
|
||||||
) {
|
event.keyCode !== 229
|
||||||
event.preventDefault();
|
) {
|
||||||
sendMessage();
|
event.preventDefault();
|
||||||
}
|
sendMessage();
|
||||||
}}
|
}
|
||||||
placeholder="Write a message..."
|
}}
|
||||||
rows={1}
|
placeholder="Write a message..."
|
||||||
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"
|
rows={1}
|
||||||
/>
|
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>
|
/>
|
||||||
<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() || isPending}
|
|
||||||
>
|
|
||||||
<SendIcon size={17} />
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
{/* <div className="mx-auto mt-2 hidden max-w-2xl items-center justify-center gap-1 text-[10px] text-muted-foreground sm:flex">
|
<button
|
||||||
<CircleHelpIcon size={12} /> Press Enter to send
|
aria-label="Send message"
|
||||||
</div> */}
|
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={!isReady || (!message.trim() && !files.length) || isPending}
|
||||||
|
>
|
||||||
|
<SendIcon size={17} />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AttachmentPreview({
|
||||||
|
file,
|
||||||
|
onRemove,
|
||||||
|
}: {
|
||||||
|
file: File;
|
||||||
|
onRemove?: () => void;
|
||||||
|
}) {
|
||||||
|
const [img, setImg] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!file.type.startsWith("image/")) return;
|
||||||
|
const blob = URL.createObjectURL(file);
|
||||||
|
setImg(blob);
|
||||||
|
return () => URL.revokeObjectURL(blob);
|
||||||
|
}, [file]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 rounded-2xl bg-muted px-3 py-2 shrink-0",
|
||||||
|
img != null && "rounded-sm",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{img ? (
|
||||||
|
<a href={img} target="_blank" rel="noopener noreferrer">
|
||||||
|
<img
|
||||||
|
src={img}
|
||||||
|
alt={file.name}
|
||||||
|
className="h-10 aspect-video object-cover"
|
||||||
|
/>
|
||||||
|
</a>
|
||||||
|
) : (
|
||||||
|
<p className="text-xs">{file.name}</p>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
aria-label="Remove attachment"
|
||||||
|
className="shrink-0 text-muted-foreground cursor-pointer hover:bg-muted hover:text-white"
|
||||||
|
onClick={onRemove}
|
||||||
|
>
|
||||||
|
<XIcon size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-23
@@ -1,25 +1,19 @@
|
|||||||
import ChatsSection from "./chats";
|
import ChatsSection from "./chats";
|
||||||
import type { ChatDTO } from "@shared/dto";
|
|
||||||
import MessagesSection from "./messages";
|
|
||||||
import DevicesSection from "./devices";
|
import DevicesSection from "./devices";
|
||||||
import { useLocalStorage } from "@/hooks/useLocalStorage";
|
import { useLocalStorage } from "@/hooks/useLocalStorage";
|
||||||
|
import { useHashRouter } from "@/hooks/useHashRouter";
|
||||||
|
import MessagesSection from "./messages";
|
||||||
|
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
const [chat, setChat] = useLocalStorage<ChatDTO | null>(
|
const router = useHashRouter();
|
||||||
"app/current-chat",
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
const [mobileChat, setMobileChat] = useLocalStorage<boolean>(
|
|
||||||
"app/mobile-chat",
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
const [curDeviceId, setDeviceId] = useLocalStorage<string>("app/device", "");
|
const [curDeviceId, setDeviceId] = useLocalStorage<string>("app/device", "");
|
||||||
|
const chatId = router.query.get("chatId");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<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-1/3 max-w-md ${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 ${chatId ? "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">
|
||||||
@@ -50,11 +44,8 @@ export default function Page() {
|
|||||||
</header> */}
|
</header> */}
|
||||||
|
|
||||||
<ChatsSection
|
<ChatsSection
|
||||||
selected={chat}
|
selected={chatId}
|
||||||
onSelect={(c) => {
|
onSelect={(id) => router.push(`/?chatId=${id}`)}
|
||||||
setChat(c);
|
|
||||||
setMobileChat(true);
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* <div className="border-t border-border px-5 py-4">
|
{/* <div className="border-t border-border px-5 py-4">
|
||||||
@@ -80,13 +71,7 @@ export default function Page() {
|
|||||||
<DevicesSection curDeviceId={curDeviceId} setDeviceId={setDeviceId} />
|
<DevicesSection curDeviceId={curDeviceId} setDeviceId={setDeviceId} />
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
{chat ? (
|
{chatId ? <MessagesSection chatId={chatId} /> : null}
|
||||||
<MessagesSection
|
|
||||||
chat={chat}
|
|
||||||
mobileChat={mobileChat}
|
|
||||||
setMobileChat={setMobileChat}
|
|
||||||
/>
|
|
||||||
) : null}
|
|
||||||
{/* </div> */}
|
{/* </div> */}
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,7 +2,12 @@ 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 { cn } from "cn";
|
||||||
import { DownloadIcon, Loader2Icon, PaperclipIcon } from "lucide-react";
|
import {
|
||||||
|
DownloadIcon,
|
||||||
|
ImageIcon,
|
||||||
|
Loader2Icon,
|
||||||
|
PaperclipIcon,
|
||||||
|
} from "lucide-react";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
@@ -17,7 +22,9 @@ export default function MessageMedia({ data }: Props) {
|
|||||||
const [isLoading, setLoading] = useState(false);
|
const [isLoading, setLoading] = useState(false);
|
||||||
const [isDownloaded, setDownloaded] = useState(false);
|
const [isDownloaded, setDownloaded] = useState(false);
|
||||||
const [body, setBody] = useState(
|
const [body, setBody] = useState(
|
||||||
type === "image" ? "data:image/webp;base64," + data.body : data.body,
|
type === "image" && data.body
|
||||||
|
? "data:image/webp;base64," + data.body
|
||||||
|
: data.body,
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -85,17 +92,28 @@ export default function MessageMedia({ data }: Props) {
|
|||||||
return (
|
return (
|
||||||
<a
|
<a
|
||||||
href="#"
|
href="#"
|
||||||
onClick={() => openMedia()}
|
onClick={(e) => {
|
||||||
className="w-full h-32 aspect-video block relative overflow-hidden"
|
e.preventDefault();
|
||||||
|
openMedia();
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"w-full min-h-32 max-h-40 aspect-video block relative overflow-hidden rounded",
|
||||||
|
)}
|
||||||
>
|
>
|
||||||
<img
|
{body ? (
|
||||||
src={body || ""}
|
<img
|
||||||
alt=""
|
src={body}
|
||||||
className={cn(
|
alt=""
|
||||||
"w-full h-full object-cover",
|
className={cn(
|
||||||
!isDownloaded && "blur-sm",
|
"w-full h-full object-cover",
|
||||||
)}
|
!isDownloaded && "blur-[2px]",
|
||||||
/>
|
)}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="absolute inset-0 bg-black/30 flex items-center justify-center">
|
||||||
|
<ImageIcon className="size-8 opacity-80" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{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">
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import { cn } from "cn";
|
||||||
|
import React from "react";
|
||||||
|
|
||||||
|
type Token =
|
||||||
|
| { type: "text"; value: string }
|
||||||
|
| { type: "bold"; value: string }
|
||||||
|
| { type: "italic"; value: string }
|
||||||
|
| { type: "strike"; value: string }
|
||||||
|
| { type: "code"; value: string }
|
||||||
|
| { type: "url"; value: string };
|
||||||
|
|
||||||
|
function renderWhatsAppMessage(message: string): React.ReactNode {
|
||||||
|
const regex =
|
||||||
|
/(\*[^*\n]+\*|_[^_\n]+_|~[^~\n]+~|`[^`\n]+`|https?:\/\/[^\s<]+|www\.[^\s<]+)/g;
|
||||||
|
|
||||||
|
const tokens: Token[] = [];
|
||||||
|
let lastIndex = 0;
|
||||||
|
|
||||||
|
for (const match of message.matchAll(regex)) {
|
||||||
|
const index = match.index ?? 0;
|
||||||
|
const value = match[0];
|
||||||
|
|
||||||
|
if (index > lastIndex) {
|
||||||
|
tokens.push({
|
||||||
|
type: "text",
|
||||||
|
value: message.slice(lastIndex, index),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.startsWith("*")) {
|
||||||
|
tokens.push({ type: "bold", value: value.slice(1, -1) });
|
||||||
|
} else if (value.startsWith("_")) {
|
||||||
|
tokens.push({ type: "italic", value: value.slice(1, -1) });
|
||||||
|
} else if (value.startsWith("~")) {
|
||||||
|
tokens.push({ type: "strike", value: value.slice(1, -1) });
|
||||||
|
} else if (value.startsWith("`")) {
|
||||||
|
tokens.push({ type: "code", value: value.slice(1, -1) });
|
||||||
|
} else {
|
||||||
|
// Remove punctuation that commonly follows a URL.
|
||||||
|
const url = value.replace(/[.,!?;:)]+$/, "");
|
||||||
|
|
||||||
|
tokens.push({ type: "url", value: url });
|
||||||
|
|
||||||
|
// Preserve trailing punctuation.
|
||||||
|
if (url.length < value.length) {
|
||||||
|
tokens.push({
|
||||||
|
type: "text",
|
||||||
|
value: value.slice(url.length),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lastIndex = index + value.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lastIndex < message.length) {
|
||||||
|
tokens.push({
|
||||||
|
type: "text",
|
||||||
|
value: message.slice(lastIndex),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return tokens.map((token, i) => {
|
||||||
|
switch (token.type) {
|
||||||
|
case "bold":
|
||||||
|
return (
|
||||||
|
<strong key={i} className="font-bold">
|
||||||
|
{token.value}
|
||||||
|
</strong>
|
||||||
|
);
|
||||||
|
|
||||||
|
case "italic":
|
||||||
|
return (
|
||||||
|
<em key={i} className="italic">
|
||||||
|
{token.value}
|
||||||
|
</em>
|
||||||
|
);
|
||||||
|
|
||||||
|
case "strike":
|
||||||
|
return (
|
||||||
|
<del key={i} className="line-through">
|
||||||
|
{token.value}
|
||||||
|
</del>
|
||||||
|
);
|
||||||
|
|
||||||
|
case "code":
|
||||||
|
return (
|
||||||
|
<code
|
||||||
|
key={i}
|
||||||
|
className="rounded bg-black/10 px-1 py-0.5 font-mono text-sm"
|
||||||
|
>
|
||||||
|
{token.value}
|
||||||
|
</code>
|
||||||
|
);
|
||||||
|
|
||||||
|
case "url":
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
key={i}
|
||||||
|
href={
|
||||||
|
token.value.startsWith("www.")
|
||||||
|
? `https://${token.value}`
|
||||||
|
: token.value
|
||||||
|
}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="break-all text-blue-200 underline hover:text-blue-300"
|
||||||
|
>
|
||||||
|
{token.value}
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
|
||||||
|
case "text":
|
||||||
|
return <React.Fragment key={i}>{token.value}</React.Fragment>;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
text?: string | null;
|
||||||
|
className?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function Paragraph({ text, className }: Props) {
|
||||||
|
if (!text) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("whitespace-pre-wrap wrap-break-word", className)}>
|
||||||
|
{renderWhatsAppMessage(text)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { useWAClient } from "@/app/context";
|
||||||
|
import { getId } from "@/lib/utils";
|
||||||
|
import type { WhatsAppClient } from "@client/whatsapp";
|
||||||
|
import { useQuery, type UseQueryOptions } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
async function getChats(client: WhatsAppClient) {
|
||||||
|
return client
|
||||||
|
.listChats({ limit: 500 })
|
||||||
|
.then((res) => res.map((i) => ({ ...i, id: getId(i.id) })));
|
||||||
|
}
|
||||||
|
|
||||||
|
type Response = Awaited<ReturnType<typeof getChats>>;
|
||||||
|
|
||||||
|
export function useChats(opt?: Partial<UseQueryOptions>) {
|
||||||
|
const { client, isReady } = useWAClient();
|
||||||
|
return useQuery<Response, Error>({
|
||||||
|
queryKey: ["chats"],
|
||||||
|
queryFn: () => getChats(client),
|
||||||
|
enabled: isReady,
|
||||||
|
...((opt || {}) as any),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
|
||||||
|
type HashLocation = {
|
||||||
|
path: string;
|
||||||
|
query: URLSearchParams;
|
||||||
|
search: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type HashRouter = HashLocation & {
|
||||||
|
navigate: (path: string, options?: NavigateOptions) => void;
|
||||||
|
push: (path: string) => void;
|
||||||
|
reset: (path?: string) => void;
|
||||||
|
canGoback: () => boolean;
|
||||||
|
goBack: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
type NavigateOptions = {
|
||||||
|
replace?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
function getHashLocation(): HashLocation {
|
||||||
|
const hash = window.location.hash.slice(1);
|
||||||
|
|
||||||
|
const [pathname, search = ""] = hash.split("?");
|
||||||
|
|
||||||
|
const path = pathname
|
||||||
|
? pathname.startsWith("/")
|
||||||
|
? pathname
|
||||||
|
: `/${pathname}`
|
||||||
|
: "/";
|
||||||
|
|
||||||
|
return {
|
||||||
|
path,
|
||||||
|
search: search ? `?${search}` : "",
|
||||||
|
query: new URLSearchParams(search),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePath(path: string) {
|
||||||
|
return path.startsWith("/") ? path : `/${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setHashPath(path: string, replace = false) {
|
||||||
|
const normalized = normalizePath(path);
|
||||||
|
const hash = `#${normalized}`;
|
||||||
|
|
||||||
|
if (replace) {
|
||||||
|
window.history.replaceState(null, "", hash);
|
||||||
|
|
||||||
|
// replaceState doesn't emit hashchange
|
||||||
|
window.dispatchEvent(new HashChangeEvent("hashchange"));
|
||||||
|
} else {
|
||||||
|
window.location.hash = normalized;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useHashRouter(): HashRouter {
|
||||||
|
const [location, setLocation] = useState<HashLocation>(getHashLocation);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleChange = () => {
|
||||||
|
setLocation(getHashLocation());
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener("hashchange", handleChange);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener("hashchange", handleChange);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const navigate = useCallback(
|
||||||
|
(path: string, options: NavigateOptions = {}) => {
|
||||||
|
setHashPath(path, options.replace);
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const push = useCallback(
|
||||||
|
(path: string) => {
|
||||||
|
navigate(path);
|
||||||
|
},
|
||||||
|
[navigate],
|
||||||
|
);
|
||||||
|
|
||||||
|
const reset = useCallback(
|
||||||
|
(path = "/") => {
|
||||||
|
navigate(path, { replace: true });
|
||||||
|
},
|
||||||
|
[navigate],
|
||||||
|
);
|
||||||
|
|
||||||
|
const canGoback = useCallback(() => window.history.length > 1, []);
|
||||||
|
|
||||||
|
const goBack = useCallback(() => {
|
||||||
|
if (canGoback()) {
|
||||||
|
window.history.back();
|
||||||
|
} else {
|
||||||
|
reset();
|
||||||
|
}
|
||||||
|
}, [canGoback, reset]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...location,
|
||||||
|
navigate,
|
||||||
|
push,
|
||||||
|
reset,
|
||||||
|
canGoback,
|
||||||
|
goBack,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
|
||||||
|
export function useIntersection(
|
||||||
|
callback: (entry: IntersectionObserverEntry) => void,
|
||||||
|
options: any = {},
|
||||||
|
) {
|
||||||
|
const ref = useRef(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const element = ref.current;
|
||||||
|
if (!element) return;
|
||||||
|
|
||||||
|
const observer = new IntersectionObserver(([entry]) => {
|
||||||
|
if (entry.isIntersecting) {
|
||||||
|
callback(entry);
|
||||||
|
}
|
||||||
|
}, options);
|
||||||
|
|
||||||
|
observer.observe(element);
|
||||||
|
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [callback, options]);
|
||||||
|
|
||||||
|
return ref;
|
||||||
|
}
|
||||||
@@ -33,3 +33,15 @@ export function getFormattedName(
|
|||||||
? name.user || ""
|
? name.user || ""
|
||||||
: "";
|
: "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getFilesAsBase64(files: File[]) {
|
||||||
|
return Promise.all(
|
||||||
|
files.map((file) => {
|
||||||
|
return new Promise<string>((resolve) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => resolve((reader.result as string) || "");
|
||||||
|
reader.readAsDataURL(file);
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user