feat: add send file function
This commit is contained in:
+193
-62
@@ -1,5 +1,5 @@
|
||||
import { useWAClient } from "./context";
|
||||
import { getFormattedName, getId } from "@/lib/utils";
|
||||
import { getFilesAsBase64, getFormattedName, getId } from "@/lib/utils";
|
||||
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { cn } from "cn";
|
||||
import {
|
||||
@@ -10,8 +10,9 @@ import {
|
||||
PaperclipIcon,
|
||||
PhoneCallIcon,
|
||||
SendIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import dayjs from "dayjs";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import MessageMedia from "@/components/message-media";
|
||||
@@ -22,6 +23,7 @@ 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);
|
||||
|
||||
@@ -33,8 +35,6 @@ type Props = {
|
||||
export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
|
||||
const { client, isReady } = useWAClient();
|
||||
const router = useHashRouter();
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setPending] = useState(false);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { data: chats } = useChats();
|
||||
@@ -121,22 +121,6 @@ export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
|
||||
});
|
||||
}, [messages, contacts]);
|
||||
|
||||
async function sendMessage() {
|
||||
const text = message.trim();
|
||||
if (!text || !chatId) 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 (
|
||||
<section
|
||||
className={`flex min-w-0 flex-1 flex-col bg-muted ${chatId ? "flex" : "hidden md:flex"}`}
|
||||
@@ -235,7 +219,7 @@ export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
|
||||
}
|
||||
}}
|
||||
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",
|
||||
)}
|
||||
>
|
||||
@@ -315,54 +299,201 @@ export default function MessagesSection({ chatId, maxCount = 50 }: Props) {
|
||||
</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
|
||||
<MessageInputSection chatId={chatId} refetch={refetch} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageInputSection({
|
||||
chatId,
|
||||
refetch,
|
||||
}: {
|
||||
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"
|
||||
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 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>
|
||||
<textarea
|
||||
value={message}
|
||||
onChange={(event) => setMessage(event.target.value)}
|
||||
onPaste={onPaste}
|
||||
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 field-sizing-content bg-transparent py-2.5 text-sm outline-none placeholder:text-muted-foreground"
|
||||
/>
|
||||
</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> */}
|
||||
<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={!isReady || (!message.trim() && !files.length) || isPending}
|
||||
>
|
||||
<SendIcon size={17} />
|
||||
</button>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,3 +33,15 @@ export function getFormattedName(
|
||||
? 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