wip: refactor chats to use zustand

This commit is contained in:
Ren Amamiya
2023-05-27 12:14:30 +07:00
parent 671b857077
commit 79e948ac05
21 changed files with 229 additions and 278 deletions

View File

@@ -1,19 +1,18 @@
import { Image } from "@shared/image";
import { useActiveAccount } from "@stores/accounts";
import { DEFAULT_AVATAR } from "@stores/constants";
import { usePageContext } from "@utils/hooks/usePageContext";
import { useProfile } from "@utils/hooks/useProfile";
import { shortenKey } from "@utils/shortenKey";
import { twMerge } from "tailwind-merge";
export default function ChatsListItem({ pubkey }: { pubkey: string }) {
export function ChatsListItem({ pubkey }: { pubkey: string }) {
const pageContext = usePageContext();
const searchParams: any = pageContext.urlParsed.search;
const pagePubkey = searchParams.pubkey;
const account = useActiveAccount((state: any) => state.account);
const { user, isError, isLoading } = useProfile(pubkey);
return (
@@ -43,10 +42,13 @@ export default function ChatsListItem({ pubkey }: { pubkey: string }) {
className="h-5 w-5 rounded bg-white object-cover"
/>
</div>
<div>
<div className="inline-flex items-baseline gap-1">
<h5 className="max-w-[9rem] truncate font-medium text-zinc-200 group-hover:text-white">
{user?.nip05 || user.name || shortenKey(pubkey)}
</h5>
{account?.pubkey === pubkey && (
<span className="text-zinc-500">(you)</span>
)}
</div>
</a>
)}

View File

@@ -1,5 +1,4 @@
import ChatsListItem from "@app/chat/components/item";
import ChatsListSelfItem from "@app/chat/components/self";
import { ChatsListItem } from "@app/chat/components/item";
import { useActiveAccount } from "@stores/accounts";
import { useChats } from "@stores/chats";
import { useEffect } from "react";
@@ -16,7 +15,6 @@ export default function ChatsList() {
return (
<div className="flex flex-col gap-1">
<ChatsListSelfItem />
{!chats ? (
<>
<div className="inline-flex h-8 items-center gap-2 rounded-md px-2.5">
@@ -29,7 +27,7 @@ export default function ChatsList() {
</div>
</>
) : (
chats.map((item) => (
chats.map((item: { sender_pubkey: string }) => (
<ChatsListItem key={item.sender_pubkey} pubkey={item.sender_pubkey} />
))
)}

View File

@@ -1,44 +1,39 @@
import { ChatMessageItem } from "@app/chat/components/messages/item";
import { useActiveAccount } from "@stores/accounts";
import { sortedChatMessagesAtom } from "@stores/chat";
import { useAtomValue } from "jotai";
import { useChatMessages } from "@stores/chats";
import { useCallback, useRef } from "react";
import { Virtuoso } from "react-virtuoso";
export default function ChatMessageList() {
export function ChatMessageList() {
const account = useActiveAccount((state: any) => state.account);
const messages = useChatMessages((state: any) => state.messages);
const virtuosoRef = useRef(null);
const data = useAtomValue(sortedChatMessagesAtom);
const itemContent: any = useCallback(
(index: string | number) => {
return (
<ChatMessageItem
data={data[index]}
userPubkey={account.pubkey}
userPrivkey={account.privkey}
/>
<ChatMessageItem data={messages[index]} userPrivkey={account.privkey} />
);
},
[account.privkey, account.pubkey, data],
[account.privkey, account.pubkey, messages],
);
const computeItemKey = useCallback(
(index: string | number) => {
return data[index].id;
return messages[index].id;
},
[data],
[messages],
);
return (
<div className="h-full w-full">
<Virtuoso
ref={virtuosoRef}
data={data}
data={messages}
itemContent={itemContent}
computeItemKey={computeItemKey}
initialTopMostItemIndex={data.length - 1}
initialTopMostItemIndex={messages.length - 1}
alignToBottom={true}
followOutput={true}
overscan={50}

View File

@@ -1,87 +1,74 @@
import { ImagePicker } from "@shared/form/imagePicker";
import { RelayContext } from "@shared/relayProvider";
import { useActiveAccount } from "@stores/accounts";
import { chatContentAtom } from "@stores/chat";
import { useChatMessages } from "@stores/chats";
import { WRITEONLY_RELAYS } from "@stores/constants";
import { dateToUnix } from "@utils/date";
import { useAtom } from "jotai";
import { useResetAtom } from "jotai/utils";
import { getEventHash, getSignature, nip04 } from "nostr-tools";
import { useCallback, useContext } from "react";
import { useCallback, useContext, useState } from "react";
export default function ChatMessageForm({
export function ChatMessageForm({
receiverPubkey,
}: { receiverPubkey: string }) {
userPubkey,
userPrivkey,
}: { receiverPubkey: string; userPubkey: string; userPrivkey: string }) {
const pool: any = useContext(RelayContext);
const account = useActiveAccount((state: any) => state.account);
const addMessage = useChatMessages((state: any) => state.add);
const [value, setValue] = useState("");
const [value, setValue] = useAtom(chatContentAtom);
const resetValue = useResetAtom(chatContentAtom);
const encryptMessage = useCallback(async () => {
return await nip04.encrypt(userPrivkey, receiverPubkey, value);
}, [receiverPubkey, value]);
const encryptMessage = useCallback(
async (privkey: string) => {
return await nip04.encrypt(privkey, receiverPubkey, value);
},
[receiverPubkey, value],
);
const submit = async () => {
const message = await encryptMessage();
const submitEvent = () => {
encryptMessage(account.privkey)
.then((encryptedContent) => {
const event: any = {
content: encryptedContent,
created_at: dateToUnix(),
kind: 4,
pubkey: account.pubkey,
tags: [["p", receiverPubkey]],
};
event.id = getEventHash(event);
event.sig = getSignature(event, account.privkey);
// publish note
pool.publish(event, WRITEONLY_RELAYS);
// reset state
resetValue();
})
.catch(console.error);
const event: any = {
content: message,
created_at: dateToUnix(),
kind: 4,
pubkey: userPubkey,
tags: [["p", receiverPubkey]],
};
event.id = getEventHash(event);
event.sig = getSignature(event, userPrivkey);
// publish message
pool.publish(event, WRITEONLY_RELAYS);
// add message to store
addMessage({
receiver_pubkey: receiverPubkey,
sender_pubkey: event.pubkey,
content: event.content,
tags: event.tags,
created_at: event.created_at,
});
// reset state
setValue("");
};
const handleEnterPress = (e) => {
const handleEnterPress = (e: {
key: string;
shiftKey: any;
preventDefault: () => void;
}) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
submitEvent();
submit();
}
};
return (
<div className="relative h-24 w-full shrink-0 overflow-hidden before:pointer-events-none before:absolute before:-inset-1 before:rounded-[11px] before:border before:border-fuchsia-500 before:opacity-0 before:ring-2 before:ring-fuchsia-500/20 before:transition after:pointer-events-none after:absolute after:inset-px after:rounded-[7px] after:shadow-highlight after:shadow-white/5 after:transition focus-within:before:opacity-100 focus-within:after:shadow-fuchsia-500/100 dark:focus-within:after:shadow-fuchsia-500/20">
<div>
<textarea
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={handleEnterPress}
spellCheck={false}
placeholder="Message"
className="relative h-24 w-full resize-none rounded-lg border border-black/5 px-3.5 py-3 text-base shadow-input shadow-black/5 !outline-none placeholder:text-zinc-400 dark:bg-zinc-800 dark:text-white dark:shadow-black/10 dark:placeholder:text-zinc-500"
/>
</div>
<div className="absolute bottom-2 w-full px-2">
<div className="flex w-full items-center justify-between bg-zinc-800">
<div className="flex items-center gap-2 divide-x divide-zinc-700">
<ImagePicker type="chat" />
<div className="flex items-center gap-2 pl-2" />
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => submitEvent()}
disabled={value.length === 0 ? true : false}
className="inline-flex h-8 w-16 items-center justify-center rounded-md bg-fuchsia-500 px-4 text-base font-medium shadow-button hover:bg-fuchsia-600 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
Send
</button>
</div>
</div>
</div>
<div className="relative h-11 w-full overflow-hidden">
<input
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={handleEnterPress}
spellCheck={false}
placeholder="Message"
className="relative h-11 w-full resize-none rounded-md px-5 !outline-none bg-zinc-800 placeholder:text-zinc-500"
/>
</div>
);
}

View File

@@ -1,22 +1,19 @@
import ChatMessageUser from "@app/chat/components/messages/user";
import { ChatMessageUser } from "@app/chat/components/messages/user";
import { useDecryptMessage } from "@app/chat/hooks/useDecryptMessage";
import ImagePreview from "@app/note/components/preview/image";
import VideoPreview from "@app/note/components/preview/video";
import { noteParser } from "@utils/parser";
import { memo } from "react";
export const ChatMessageItem = memo(function MessageListItem({
export const ChatMessageItem = memo(function ChatMessageItem({
data,
userPubkey,
userPrivkey,
}: {
data: any;
userPubkey: string;
userPrivkey: string;
}) {
const decryptedContent = useDecryptMessage(userPubkey, userPrivkey, data);
const decryptedContent = useDecryptMessage(data, userPrivkey);
console.log(decryptedContent);
// if we have decrypted content, use it instead of the encrypted content
if (decryptedContent) {
data["content"] = decryptedContent;
@@ -25,12 +22,12 @@ export const ChatMessageItem = memo(function MessageListItem({
const content = noteParser(data);
return (
<div className="flex h-min min-h-min w-full select-text flex-col px-5 py-2 hover:bg-black/20">
<div className="flex h-min min-h-min w-full select-text flex-col px-5 py-3 hover:bg-black/20">
<div className="flex flex-col">
<ChatMessageUser pubkey={data.pubkey} time={data.created_at} />
<div className="-mt-[17px] pl-[48px]">
<ChatMessageUser pubkey={data.sender_pubkey} time={data.created_at} />
<div className="-mt-[20px] pl-[49px]">
<div className="whitespace-pre-line break-words text-base leading-tight">
{content.parsed}
{content.parsed || ""}
</div>
{Array.isArray(content.images) && content.images.length ? (
<ImagePreview urls={content.images} />

View File

@@ -7,7 +7,7 @@ import relativeTime from "dayjs/plugin/relativeTime";
dayjs.extend(relativeTime);
export default function ChatMessageUser({
export function ChatMessageUser({
pubkey,
time,
}: { pubkey: string; time: number }) {
@@ -17,7 +17,7 @@ export default function ChatMessageUser({
<div className="group flex items-start gap-3">
{isError || isLoading ? (
<>
<div className="relative h-9 w-9 shrink animate-pulse rounded-md bg-zinc-800" />
<div className="relative h-11 w-11 shrink animate-pulse rounded-md bg-zinc-800" />
<div className="flex w-full flex-1 items-start justify-between">
<div className="flex items-baseline gap-2 text-base">
<div className="h-4 w-20 animate-pulse rounded bg-zinc-800" />
@@ -26,17 +26,17 @@ export default function ChatMessageUser({
</>
) : (
<>
<div className="relative h-9 w-9 shrink rounded-md">
<div className="relative h-11 w-11 shrink rounded-md">
<Image
src={user?.picture || DEFAULT_AVATAR}
alt={pubkey}
className="h-9 w-9 rounded-md object-cover"
className="h-11 w-11 rounded-md object-cover"
/>
</div>
<div className="flex w-full flex-1 items-start justify-between">
<div className="flex items-baseline gap-2 text-base">
<span className="font-semibold leading-none text-white group-hover:underline">
{user?.display_name || user?.name || shortenKey(pubkey)}
{user?.nip05 || user?.name || shortenKey(pubkey)}
</span>
<span className="leading-none text-zinc-500">·</span>
<span className="leading-none text-zinc-500">

View File

@@ -1,52 +0,0 @@
import { Image } from "@shared/image";
import { useActiveAccount } from "@stores/accounts";
import { DEFAULT_AVATAR } from "@stores/constants";
import { usePageContext } from "@utils/hooks/usePageContext";
import { shortenKey } from "@utils/shortenKey";
import { twMerge } from "tailwind-merge";
export default function ChatsListSelfItem() {
const pageContext = usePageContext();
const searchParams: any = pageContext.urlParsed.search;
const pagePubkey = searchParams.pubkey;
const account = useActiveAccount((state: any) => state.account);
return (
<>
{!account ? (
<div className="inline-flex h-8 items-center gap-2.5 rounded-md px-2.5">
<div className="relative h-5 w-5 shrink-0 animate-pulse rounded bg-zinc-800" />
<div>
<div className="h-2.5 w-full animate-pulse truncate rounded bg-zinc-800 text-base font-medium" />
</div>
</div>
) : (
<a
href={`/app/chat?pubkey=${account.pubkey}`}
className={twMerge(
"inline-flex h-8 items-center gap-2.5 rounded-md px-2.5 hover:bg-zinc-900",
pagePubkey === account.pubkey
? "dark:bg-zinc-900 dark:text-white hover:dark:bg-zinc-800"
: "",
)}
>
<div className="relative h-5 w-5 shrink-0 rounded">
<Image
src={account?.picture || DEFAULT_AVATAR}
alt={account.pubkey}
className="h-5 w-5 rounded bg-white object-cover"
/>
</div>
<div className="inline-flex items-baseline">
<h5 className="max-w-[9rem] truncate font-medium text-zinc-200">
{account?.nip05 || account?.name || shortenKey(account.pubkey)}
</h5>
<span className="text-zinc-600">(you)</span>
</div>
</a>
)}
</>
);
}

View File

@@ -0,0 +1,30 @@
import { Image } from "@shared/image";
import { DEFAULT_AVATAR } from "@stores/constants";
import { useProfile } from "@utils/hooks/useProfile";
import { shortenKey } from "@utils/shortenKey";
export function ChatSidebar({ pubkey }: { pubkey: string }) {
const { user, isError, isLoading } = useProfile(pubkey);
return (
<div className="px-3 py-2">
<div className="flex flex-col gap-3">
<div className="relative h-11 w-11 shrink rounded-md">
<Image
src={user?.picture || DEFAULT_AVATAR}
alt={pubkey}
className="h-11 w-11 rounded-md object-cover"
/>
</div>
<div className="flex flex-col gap-1">
<h3 className="leading-none text-lg font-semibold">
{user?.display_name || user?.name}
</h3>
<p className="leading-none text-zinc-400">
{user?.nip05 || user?.username || shortenKey(pubkey)}
</p>
</div>
</div>
</div>
);
}

View File

@@ -1,32 +1,21 @@
import { nip04 } from "nostr-tools";
import { useCallback, useEffect, useState } from "react";
import { useEffect, useState } from "react";
export function useDecryptMessage(
userKey: string,
userPriv: string,
data: any,
) {
const [content, setContent] = useState(null);
const extractSenderKey = useCallback(() => {
const keyInTags = data.tags.find(([k, v]) => k === "p" && v && v !== "")[1];
if (keyInTags === userKey) {
return data.pubkey;
} else {
return keyInTags;
}
}, [data.pubkey, data.tags, userKey]);
const decrypt = useCallback(async () => {
const senderKey = extractSenderKey();
const result = await nip04.decrypt(userPriv, senderKey, data.content);
// update state with decrypt content
setContent(result);
}, [extractSenderKey, userPriv, data.content]);
export function useDecryptMessage(data: any, userPriv: string) {
const [content, setContent] = useState(data.content);
useEffect(() => {
decrypt().catch(console.error);
}, [decrypt]);
async function decrypt() {
const result = await nip04.decrypt(
userPriv,
data.sender_pubkey,
data.content,
);
setContent(result);
}
return content ? content : null;
decrypt().catch(console.error);
}, []);
return content;
}

View File

@@ -1,4 +1,3 @@
import AppHeader from "@shared/appHeader";
import MultiAccounts from "@shared/multiAccounts";
import Navigation from "@shared/navigation";

View File

@@ -1,16 +1,15 @@
import ChatMessageForm from "@app/chat/components/messages/form";
import { ChatSidebar } from "../components/sidebar";
import { ChatMessageList } from "@app/chat/components/messageList";
import { ChatMessageForm } from "@app/chat/components/messages/form";
import { RelayContext } from "@shared/relayProvider";
import { useActiveAccount } from "@stores/accounts";
import { chatMessagesAtom } from "@stores/chat";
import { useChatMessages } from "@stores/chats";
import { READONLY_RELAYS } from "@stores/constants";
import { dateToUnix } from "@utils/date";
import { usePageContext } from "@utils/hooks/usePageContext";
import { useSetAtom } from "jotai";
import { useResetAtom } from "jotai/utils";
import { Suspense, lazy, useContext, useEffect } from "react";
import { useContext, useEffect } from "react";
import useSWRSubscription from "swr/subscription";
const ChatMessageList = lazy(() => import("@app/chat/components/messageList"));
export function Page() {
const pool: any = useContext(RelayContext);
const account = useActiveAccount((state: any) => state.account);
@@ -19,8 +18,10 @@ export function Page() {
const searchParams: any = pageContext.urlParsed.search;
const pubkey = searchParams.pubkey;
const setChatMessages = useSetAtom(chatMessagesAtom);
const resetChatMessages = useResetAtom(chatMessagesAtom);
const [fetchMessages, addMessage] = useChatMessages((state: any) => [
state.fetch,
state.add,
]);
useSWRSubscription(account ? ["chat", pubkey] : null, ([, key]) => {
const unsubscribe = pool.subscribe(
@@ -29,18 +30,18 @@ export function Page() {
kinds: [4],
authors: [key],
"#p": [account.pubkey],
limit: 20,
},
{
kinds: [4],
authors: [account.pubkey],
"#p": [key],
limit: 20,
since: dateToUnix(),
},
],
READONLY_RELAYS,
(event: any) => {
setChatMessages((prev) => [...prev, event]);
addMessage({
receiver_pubkey: account.pubkey,
sender_pubkey: event.pubkey,
content: event.content,
tags: event.tags,
created_at: event.created_at,
});
},
);
@@ -50,25 +51,37 @@ export function Page() {
});
useEffect(() => {
let ignore = false;
if (!ignore) {
// reset chat messages
resetChatMessages();
}
return () => {
ignore = true;
};
});
fetchMessages(account.pubkey, pubkey);
}, [pubkey]);
return (
<div className="relative flex h-full w-full flex-col justify-between rounded-lg border border-zinc-800 bg-zinc-900 shadow-input shadow-black/20">
<Suspense fallback={<p>Loading...</p>}>
<ChatMessageList />
</Suspense>
<div className="shrink-0 p-3">
<ChatMessageForm receiverPubkey={pubkey} />
<div className="h-full w-full grid grid-cols-3">
<div className="col-span-2 flex flex-col justify-between border-r border-zinc-900">
<div
data-tauri-drag-region
className="h-11 w-full shrink-0 inline-flex items-center justify-center border-b border-zinc-900"
>
<h3 className="font-semibold text-zinc-100">Encrypted Chat</h3>
</div>
<div className="w-full flex-1 p-3">
<div className="flex h-full flex-col justify-between rounded-md bg-zinc-900 shadow-input shadow-black/20">
<ChatMessageList />
<div className="shrink-0 px-5 p-3 border-t border-zinc-800">
<ChatMessageForm
receiverPubkey={pubkey}
userPubkey={account.pubkey}
userPrivkey={account.privkey}
/>
</div>
</div>
</div>
</div>
<div className="col-span-1">
<div
data-tauri-drag-region
className="h-11 w-full shrink-0 inline-flex items-center justify-center border-b border-zinc-900"
/>
<ChatSidebar pubkey={pubkey} />
</div>
</div>
);