added chats

This commit is contained in:
Ren Amamiya 2023-04-06 16:42:28 +07:00
parent 365ec3df88
commit 62ca74994d
13 changed files with 361 additions and 55 deletions

View File

@ -0,0 +1,44 @@
import { ImageWithFallback } from '@components/imageWithFallback';
import { activeAccountAtom } from '@stores/account';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useAtomValue } from 'jotai';
import { useRouter } from 'next/router';
export default function ChatList() {
const router = useRouter();
const activeAccount: any = useAtomValue(activeAccountAtom);
const accountProfile = JSON.parse(activeAccount.metadata);
const openChats = () => {
router.push({
pathname: '/chats/[pubkey]',
query: { pubkey: activeAccount.pubkey },
});
};
return (
<div className="flex flex-col gap-px">
<div
onClick={() => openChats()}
className="inline-flex items-center gap-2 rounded-md px-2.5 py-2 hover:bg-zinc-900"
>
<div className="relative h-5 w-5 shrink overflow-hidden rounded bg-white">
<ImageWithFallback
src={accountProfile.picture || DEFAULT_AVATAR}
alt={activeAccount.pubkey}
fill={true}
className="rounded object-cover"
/>
</div>
<div>
<h5 className="text-sm font-medium text-zinc-400">
{accountProfile.display_name || accountProfile.name} <span className="text-zinc-500">(you)</span>
</h5>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,49 @@
import { MessageUser } from '@components/chats/user';
import { nip04 } from 'nostr-tools';
import { useCallback, useEffect, useMemo, useState } from 'react';
export const Message = ({
data,
activeAccountPubkey,
activeAccountPrivkey,
}: {
data: any;
activeAccountPubkey: string;
activeAccountPrivkey: string;
}) => {
const [content, setContent] = useState('');
const sender = useMemo(() => {
const pTag = data.tags.find(([k, v]) => k === 'p' && v && v !== '')[1];
if (pTag === activeAccountPubkey) {
return data.pubkey;
} else {
return pTag;
}
}, [data.pubkey, data.tags, activeAccountPubkey]);
const decryptContent = useCallback(async () => {
const result = await nip04.decrypt(activeAccountPrivkey, sender, data.content);
setContent(result);
}, [data.content, activeAccountPrivkey, sender]);
useEffect(() => {
decryptContent().catch(console.error);
}, [decryptContent]);
return (
<div className="flex h-min min-h-min w-full select-text flex-col px-3 py-2.5 hover:bg-black/20">
<div className="flex flex-col">
<MessageUser pubkey={data.pubkey} time={data.created_at} />
<div className="-mt-4 pl-[44px]">
<div className="flex flex-col gap-2">
<div className="prose prose-zinc max-w-none break-words text-sm leading-tight dark:prose-invert prose-p:m-0 prose-p:text-sm prose-p:leading-tight prose-a:font-normal prose-a:text-fuchsia-500 prose-a:no-underline prose-img:m-0 prose-video:m-0">
{content}
</div>
</div>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,44 @@
import { Message } from '@components/chats/message';
import { useCallback, useRef } from 'react';
import { Virtuoso } from 'react-virtuoso';
export const MessageList = ({ data }: { data: any }) => {
const virtuosoRef = useRef(null);
const itemContent: any = useCallback(
(index: string | number) => {
const activeAccount = JSON.parse(localStorage.getItem('activeAccount'));
return (
<Message
data={data[index]}
activeAccountPubkey={activeAccount.pubkey}
activeAccountPrivkey={activeAccount.privkey}
/>
);
},
[data]
);
const computeItemKey = useCallback(
(index: string | number) => {
return data[index].id;
},
[data]
);
return (
<div className="h-full w-full">
<Virtuoso
ref={virtuosoRef}
data={data}
itemContent={itemContent}
computeItemKey={computeItemKey}
initialTopMostItemIndex={data.length - 1}
alignToBottom={true}
followOutput={true}
className="scrollbar-hide h-full w-full overflow-y-auto"
/>
</div>
);
};

View File

@ -0,0 +1,37 @@
import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { truncate } from '@utils/truncate';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
export const MessageUser = ({ pubkey, time }: { pubkey: string; time: number }) => {
const profile = useMetadata(pubkey);
return (
<div className="group flex items-start gap-2">
<div className="relative h-9 w-9 shrink overflow-hidden rounded-md bg-white">
<ImageWithFallback
src={profile?.picture || DEFAULT_AVATAR}
alt={pubkey}
fill={true}
className="rounded-md object-cover"
/>
</div>
<div className="flex w-full flex-1 items-start justify-between">
<div className="flex items-baseline gap-2 text-sm">
<span className="font-semibold leading-tight text-zinc-200 group-hover:underline">
{profile?.display_name || profile?.name || truncate(pubkey, 16, ' .... ')}
</span>
<span className="leading-tight text-zinc-500">·</span>
<span className="text-zinc-500">{dayjs().to(dayjs.unix(time))}</span>
</div>
</div>
</div>
);
};

View File

@ -0,0 +1,79 @@
import ImagePicker from '@components/form/imagePicker';
import { RelayContext } from '@components/relaysProvider';
import { dateToUnix } from '@utils/getDate';
import { getEventHash, nip04, signEvent } from 'nostr-tools';
import { useCallback, useContext, useState } from 'react';
export default function FormChat({ receiverPubkey }: { receiverPubkey: string }) {
const [pool, relays]: any = useContext(RelayContext);
const [value, setValue] = useState('');
const encryptMessage = useCallback(
async (privkey: string) => {
return await nip04.encrypt(privkey, receiverPubkey, value);
},
[receiverPubkey, value]
);
const submitEvent = useCallback(() => {
const activeAccount = JSON.parse(localStorage.getItem('activeAccount'));
encryptMessage(activeAccount.privkey)
.then((encryptedContent) => {
const event: any = {
content: encryptedContent,
created_at: dateToUnix(),
kind: 4,
pubkey: activeAccount.pubkey,
tags: [['p', receiverPubkey]],
};
event.id = getEventHash(event);
event.sig = signEvent(event, activeAccount.privkey);
// publish note
pool.publish(event, relays);
// reset state
setValue('');
})
.catch(console.error);
}, [encryptMessage, receiverPubkey, pool, relays]);
const handleEnterPress = (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
submitEvent();
}
};
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-sm shadow-input shadow-black/5 !outline-none placeholder:text-zinc-400 dark:bg-zinc-800 dark:text-zinc-200 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 />
<div className="flex items-center gap-2 pl-2"></div>
</div>
<div className="flex items-center gap-2">
<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-sm 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>
);
}

View File

@ -7,16 +7,16 @@ export default function Channels() {
return (
<Collapsible.Root open={open} onOpenChange={setOpen}>
<div className="flex flex-col gap-1 px-2">
<Collapsible.Trigger className="flex cursor-pointer items-center gap-2 px-2 py-1">
<div className="flex flex-col px-2">
<Collapsible.Trigger className="flex cursor-pointer items-center gap-1 px-1 py-1">
<div
className={`inline-flex h-6 w-6 transform items-center justify-center transition-transform duration-150 ease-in-out ${
className={`inline-flex h-5 w-5 transform items-center justify-center transition-transform duration-150 ease-in-out ${
open ? 'rotate-180' : ''
}`}
>
<TriangleUpIcon className="h-4 w-4 text-zinc-700" />
</div>
<h3 className="text-xs font-bold uppercase tracking-wide text-zinc-600">Channels</h3>
<h3 className="text-[11px] font-bold uppercase tracking-widest text-zinc-600">Channels</h3>
</Collapsible.Trigger>
<Collapsible.Content></Collapsible.Content>
</div>

View File

@ -1,3 +1,5 @@
import ChatList from '@components/chats/chatList';
import * as Collapsible from '@radix-ui/react-collapsible';
import { TriangleUpIcon } from '@radix-ui/react-icons';
import { useState } from 'react';
@ -7,18 +9,20 @@ export default function Chats() {
return (
<Collapsible.Root open={open} onOpenChange={setOpen}>
<div className="flex flex-col gap-1 px-2">
<Collapsible.Trigger className="flex cursor-pointer items-center gap-2 px-2 py-1">
<div className="flex flex-col px-2">
<Collapsible.Trigger className="flex cursor-pointer items-center gap-1 px-1 py-1">
<div
className={`inline-flex h-6 w-6 transform items-center justify-center transition-transform duration-150 ease-in-out ${
className={`inline-flex h-5 w-5 transform items-center justify-center transition-transform duration-150 ease-in-out ${
open ? 'rotate-180' : ''
}`}
>
<TriangleUpIcon className="h-4 w-4 text-zinc-700" />
</div>
<h3 className="text-xs font-bold uppercase tracking-wide text-zinc-600">Chats</h3>
<h3 className="text-[11px] font-bold uppercase tracking-widest text-zinc-600">Chats</h3>
</Collapsible.Trigger>
<Collapsible.Content></Collapsible.Content>
<Collapsible.Content>
<ChatList />
</Collapsible.Content>
</div>
</Collapsible.Root>
);

View File

@ -9,8 +9,8 @@ export default function Newsfeed() {
return (
<Collapsible.Root open={open} onOpenChange={setOpen}>
<div className="flex flex-col gap-1 px-2">
<Collapsible.Trigger className="flex cursor-pointer items-center gap-2 px-2 py-1">
<div className="flex flex-col px-2">
<Collapsible.Trigger className="flex cursor-pointer items-center gap-1 px-1 py-1">
<div
className={`inline-flex h-5 w-5 transform items-center justify-center transition-transform duration-150 ease-in-out ${
open ? 'rotate-180' : ''
@ -18,7 +18,7 @@ export default function Newsfeed() {
>
<TriangleUpIcon className="h-4 w-4 text-zinc-700" />
</div>
<h3 className="text-xs font-bold uppercase tracking-wide text-zinc-600">Newsfeed</h3>
<h3 className="text-[11px] font-bold uppercase tracking-widest text-zinc-600">Newsfeed</h3>
</Collapsible.Trigger>
<Collapsible.Content className="flex flex-col text-zinc-400">
<ActiveLink
@ -26,9 +26,6 @@ export default function Newsfeed() {
activeClassName="dark:bg-zinc-900 dark:text-zinc-100 hover:dark:bg-zinc-800"
className="flex h-8 items-center gap-2.5 rounded-md px-2.5 text-sm font-medium hover:text-zinc-200"
>
<div className="inline-flex h-5 w-5 items-center justify-center">
<span className="h-4 w-3 rounded-sm bg-gradient-to-br from-fuchsia-500 via-purple-300 to-pink-300"></span>
</div>
<span>Following</span>
</ActiveLink>
<ActiveLink
@ -36,9 +33,6 @@ export default function Newsfeed() {
activeClassName="dark:bg-zinc-900 dark:text-zinc-100 hover:dark:bg-zinc-800"
className="flex h-8 items-center gap-2.5 rounded-md px-2.5 text-sm font-medium hover:text-zinc-200"
>
<div className="inline-flex h-5 w-5 items-center justify-center">
<span className="h-4 w-3 rounded-sm bg-gradient-to-br from-amber-500 via-orange-200 to-yellow-300"></span>
</div>
<span>Circle</span>
</ActiveLink>
</Collapsible.Content>

View File

@ -16,12 +16,12 @@ export const UserExtend = ({ pubkey, time }: { pubkey: string; time: number }) =
return (
<div className="group flex items-start gap-2">
<div className="relative h-11 w-11 shrink overflow-hidden rounded-md bg-zinc-900 ring-fuchsia-500 ring-offset-1 ring-offset-zinc-900 group-hover:ring-1">
<div className="relative h-11 w-11 shrink overflow-hidden rounded-md bg-white">
<ImageWithFallback
src={profile?.picture || DEFAULT_AVATAR}
alt={pubkey}
fill={true}
className="rounded-md border border-white/10 object-cover"
className="rounded-md object-cover"
/>
</div>
<div className="flex w-full flex-1 items-start justify-between">

View File

@ -16,7 +16,7 @@ export const UserLarge = ({ pubkey, time }: { pubkey: string; time: number }) =>
return (
<div className="flex items-center gap-2">
<div className="relative h-11 w-11 shrink overflow-hidden rounded-md bg-zinc-900">
<div className="relative h-11 w-11 shrink overflow-hidden rounded-md bg-white">
<ImageWithFallback
src={profile?.picture || DEFAULT_AVATAR}
alt={pubkey}

View File

@ -1,10 +1,11 @@
import { useMetadata } from '@utils/metadata';
import { truncate } from '@utils/truncate';
import { memo } from 'react';
export const UserMention = memo(function UserMention({ pubkey }: { pubkey: string }) {
export const UserMention = ({ pubkey }: { pubkey: string }) => {
const profile = useMetadata(pubkey);
return <span className="cursor-pointer text-fuchsia-500">@{profile?.name || truncate(pubkey, 16, ' .... ')}</span>;
});
return (
<span className="cursor-pointer text-fuchsia-500">
@{profile?.name || profile?.username || truncate(pubkey, 16, ' .... ')}
</span>
);
};

View File

@ -1,28 +0,0 @@
import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { truncate } from '@utils/truncate';
export const UserMini = ({ pubkey }: { pubkey: string }) => {
const profile = useMetadata(pubkey);
return (
<div className="flex cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-1.5 text-sm font-medium hover:bg-zinc-900">
<div className="relative h-5 w-5 shrink-0 overflow-hidden rounded">
<ImageWithFallback
src={profile?.picture || DEFAULT_AVATAR}
alt={pubkey}
fill={true}
className="rounded object-cover"
/>
</div>
<div className="inline-flex w-full flex-1 flex-col overflow-hidden">
<p className="truncate leading-tight text-zinc-300">
{profile?.display_name || profile?.name || truncate(pubkey, 16, ' .... ')}
</p>
</div>
</div>
);
};

View File

@ -0,0 +1,82 @@
import BaseLayout from '@layouts/base';
import WithSidebarLayout from '@layouts/withSidebar';
import { MessageList } from '@components/chats/messageList';
import FormChat from '@components/form/chat';
import { RelayContext } from '@components/relaysProvider';
import { activeAccountAtom } from '@stores/account';
import { useAtomValue } from 'jotai';
import { useRouter } from 'next/router';
import {
JSXElementConstructor,
ReactElement,
ReactFragment,
ReactPortal,
useContext,
useEffect,
useState,
} from 'react';
export default function Page() {
const [pool, relays]: any = useContext(RelayContext);
const router = useRouter();
const pubkey: any = router.query.pubkey || null;
const activeAccount: any = useAtomValue(activeAccountAtom);
const [messages, setMessages] = useState([]);
useEffect(() => {
const unsubscribe = pool.subscribe(
[
{
kinds: [4],
authors: [pubkey],
'#p': [activeAccount.pubkey],
since: 0,
},
{
kinds: [4],
authors: [activeAccount.pubkey],
'#p': [pubkey],
since: 0,
},
],
relays,
(event: any) => {
setMessages((messages) => [event, ...messages]);
}
);
return () => {
unsubscribe;
};
}, [pool, relays, pubkey, activeAccount.pubkey]);
return (
<div className="flex h-full w-full flex-col justify-between">
<MessageList data={messages.sort((a, b) => a.created_at - b.created_at)} />
<div className="shrink-0 p-3">
<FormChat receiverPubkey={pubkey} />
</div>
</div>
);
}
Page.getLayout = function getLayout(
page:
| string
| number
| boolean
| ReactElement<unknown, string | JSXElementConstructor<unknown>>
| ReactFragment
| ReactPortal
) {
return (
<BaseLayout>
<WithSidebarLayout>{page}</WithSidebarLayout>
</BaseLayout>
);
};