feat: frontend draft
This commit is contained in:
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 || ""
|
||||
: "";
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { WhatsAppClient } from "@client/whatsapp";
|
||||
|
||||
const wa = new WhatsAppClient(import.meta.env.VITE_WHATSAPP_URL);
|
||||
|
||||
export default wa;
|
||||
Reference in New Issue
Block a user