feat: fetch media draft
This commit is contained in:
+35
-9
@@ -24,6 +24,7 @@ export default function MessagesSection({
|
||||
}: Props) {
|
||||
const { client, isReady } = useWAClient();
|
||||
const [message, setMessage] = useState("");
|
||||
const [isPending, setPending] = useState(false);
|
||||
|
||||
const { data: contacts } = useQuery({
|
||||
queryKey: ["contacts"],
|
||||
@@ -32,7 +33,7 @@ export default function MessagesSection({
|
||||
});
|
||||
|
||||
const chatId = getId(chat.id);
|
||||
const { data: messages } = useQuery({
|
||||
const { data: messages, refetch } = useQuery({
|
||||
queryKey: ["messages", chatId],
|
||||
queryFn: () =>
|
||||
client.getMessages({ chatId, count: 50 }).then((res) =>
|
||||
@@ -60,10 +61,33 @@ export default function MessagesSection({
|
||||
?.reverse();
|
||||
}, [messages, contacts]);
|
||||
|
||||
function sendMessage() {
|
||||
async function sendMessage() {
|
||||
const text = message.trim();
|
||||
if (!text) return;
|
||||
setMessage("");
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchMedia(msgId: string) {
|
||||
const data = await client.getMedia(msgId);
|
||||
// decode from base64
|
||||
const blob = await fetch(data).then((res) => res.blob());
|
||||
// download
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "media";
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -156,11 +180,13 @@ export default function MessagesSection({
|
||||
) : null}
|
||||
|
||||
{item.type === "image" && (
|
||||
<img
|
||||
src={"data:image/jpeg;base64," + item.body}
|
||||
alt=""
|
||||
className="w-full"
|
||||
/>
|
||||
<a href="#" onClick={() => fetchMedia(item.id)}>
|
||||
<img
|
||||
src={"data:image/jpeg;base64," + item.body}
|
||||
alt=""
|
||||
className="w-full"
|
||||
/>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{item.type === "chat" || item.caption ? (
|
||||
@@ -227,7 +253,7 @@ export default function MessagesSection({
|
||||
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()}
|
||||
disabled={!message.trim() || isPending}
|
||||
>
|
||||
<SendIcon size={17} />
|
||||
</button>
|
||||
|
||||
Reference in New Issue
Block a user