updated thread page

This commit is contained in:
Ren Amamiya 2023-03-22 14:32:09 +07:00
parent 23f85c7e4f
commit cd5aca9042
8 changed files with 251 additions and 28 deletions

View File

@ -0,0 +1,68 @@
import NoteMetadata from '@components/note/content/metadata';
import NotePreview from '@components/note/content/preview';
import { UserLarge } from '@components/user/large';
import { UserMention } from '@components/user/mention';
import destr from 'destr';
import { memo, useMemo } from 'react';
import reactStringReplace from 'react-string-replace';
export const ContentExtend = memo(function ContentExtend({ data }: { data: any }) {
const content = useMemo(() => {
let parsedContent;
// get data tags
const tags = destr(data.tags);
// remove all image urls
parsedContent = data.content.replace(/(https?:\/\/.*\.(jpg|jpeg|gif|png|webp|mp4|webm)((\?.*)$|$))/gim, '');
// handle urls
parsedContent = reactStringReplace(parsedContent, /(https?:\/\/\S+)/g, (match, i) => (
<a key={match + i} href={match} target="_blank" rel="noreferrer">
{match}
</a>
));
// handle hashtags
parsedContent = reactStringReplace(parsedContent, /#(\w+)/g, (match, i) => (
<span key={match + i} className="text-fuchsia-500">
#{match}
</span>
));
// handle mentions
if (tags.length > 0) {
parsedContent = reactStringReplace(parsedContent, /\#\[(\d+)\]/gm, (match, i) => {
if (tags[match][0] === 'p') {
return <UserMention key={match + i} pubkey={tags[match][1]} />;
} else {
// #TODO: handle mention other note
// console.log(tags[match]);
}
});
}
return parsedContent;
}, [data.content, data.tags]);
return (
<div className="relative z-10 flex flex-col">
<UserLarge pubkey={data.pubkey} time={data.created_at} />
<div className="mt-3">
<div className="flex flex-col gap-2">
<div className="prose prose-zinc max-w-none break-words text-[15px] leading-tight dark:prose-invert prose-headings:mt-3 prose-headings:mb-2 prose-p:m-0 prose-p:text-[15px] prose-p:leading-tight prose-a:font-normal prose-a:text-fuchsia-500 prose-a:no-underline prose-ul:mt-2 prose-li:my-1">
{content}
</div>
<NotePreview content={data.content} />
</div>
</div>
<div
onClick={(e) => e.stopPropagation()}
className="mt-5 flex items-center border-t border-b border-zinc-800 py-2"
>
<NoteMetadata
eventID={data.id}
eventPubkey={data.pubkey}
eventContent={data.content}
eventTime={data.created_at}
/>
</div>
</div>
);
});

View File

@ -38,10 +38,7 @@ export const CommentsCounter = memo(function CommentsCounter({
const profile = JSON.parse(currentUser.metadata);
const openThread = () => {
router.push({
pathname: '/newsfeed/thread',
query: { id: eventID },
});
router.push(`/newsfeed/${eventID}`);
};
const submitEvent = () => {

View File

@ -3,47 +3,59 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { dateToUnix } from '@utils/getDate';
import { SizeIcon } from '@radix-ui/react-icons';
import { useLocalStorage } from '@rehooks/local-storage';
import { getEventHash, signEvent } from 'nostr-tools';
import { useContext, useState } from 'react';
export default function FormComment() {
export default function FormComment({ eventID }: { eventID: any }) {
const relayPool: any = useContext(RelayContext);
const [relays]: any = useLocalStorage('relays');
const [currentUser]: any = useLocalStorage('current-user');
const [value, setValue] = useState('');
const pubkey = currentUser.id;
const privkey = currentUser.privkey;
const profile = JSON.parse(currentUser.metadata);
const submitEvent = () => {
const event: any = {
content: value,
created_at: dateToUnix(),
kind: 1,
pubkey: currentUser.id,
tags: [['e', eventID]],
};
event.id = getEventHash(event);
event.sig = signEvent(event, currentUser.privkey);
relayPool.publish(event, relays);
};
return (
<div className="p-3">
<div className="flex gap-1">
<div>
<div className="relative h-11 w-11 shrink-0 overflow-hidden rounded-md border border-white/10">
<ImageWithFallback src={profile.picture} alt={pubkey} fill={true} className="rounded-md object-cover" />
<ImageWithFallback
src={profile.picture}
alt={currentUser.id}
fill={true}
className="rounded-md object-cover"
/>
</div>
</div>
<div className="relative h-36 w-full flex-1 overflow-hidden before:pointer-events-none before:absolute before:-inset-1 before:rounded-[11px] before:border before:border-blue-500 before:opacity-0 before:ring-2 before:ring-blue-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-blue-500/100 dark:focus-within:after:shadow-blue-500/20">
<div className="relative h-24 w-full flex-1 overflow-hidden before:pointer-events-none before:absolute before:-inset-1 before:rounded-[11px] before:border before:border-blue-500 before:opacity-0 before:ring-2 before:ring-blue-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-blue-500/100 dark:focus-within:after:shadow-blue-500/20">
<div>
<textarea
name="content"
onChange={(e) => setValue(e.target.value)}
placeholder="Send your comment"
className="relative h-36 w-full resize-none rounded-md 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"
className="relative h-24 w-full resize-none rounded-md 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"
spellCheck={false}
/>
</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">
<span className="inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-zinc-700">
<SizeIcon className="h-4 w-4 text-zinc-400" />
</span>
<div className="flex items-center gap-2 pl-2">
<span className="inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md hover:bg-zinc-700">
<svg
@ -80,7 +92,10 @@ export default function FormComment() {
</div>
</div>
<div className="flex items-center gap-2">
<button className="inline-flex h-8 w-16 items-center justify-center rounded-md bg-fuchsia-500 px-4 text-sm font-medium shadow-md shadow-fuchsia-900/50 hover:bg-fuchsia-600">
<button
onClick={() => submitEvent()}
className="inline-flex h-8 w-16 items-center justify-center rounded-md bg-fuchsia-500 px-4 text-sm font-medium shadow-md shadow-fuchsia-900/50 hover:bg-fuchsia-600"
>
<span className="text-white drop-shadow">Send</span>
</button>
</div>

View File

@ -44,9 +44,7 @@ export const RootNote = memo(function RootNote({ id }: { id: string }) {
insertDB(event);
},
undefined,
(events, relayURL) => {
console.log(events, relayURL);
},
undefined,
{
unsubscribeOnEose: true,
}

View File

@ -1,6 +1,8 @@
import { DatabaseContext } from '@components/contexts/database';
import { ImageWithFallback } from '@components/imageWithFallback';
import { truncate } from '@utils/truncate';
import { DotsHorizontalIcon } from '@radix-ui/react-icons';
import { fetch } from '@tauri-apps/api/http';
import Avatar from 'boring-avatars';
@ -74,7 +76,9 @@ export const UserExtend = memo(function UserExtend({ pubkey, time }: { pubkey: s
<div className="flex w-full flex-1 items-start justify-between">
<div className="flex w-full justify-between">
<div className="flex items-baseline gap-2 text-sm">
<span className="font-bold leading-tight">{profile?.name}</span>
<span className="font-bold leading-tight">
{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>

View File

@ -0,0 +1,97 @@
import { DatabaseContext } from '@components/contexts/database';
import { ImageWithFallback } from '@components/imageWithFallback';
import { truncate } from '@utils/truncate';
import { DotsHorizontalIcon } from '@radix-ui/react-icons';
import { fetch } from '@tauri-apps/api/http';
import Avatar from 'boring-avatars';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { memo, useCallback, useContext, useEffect, useState } from 'react';
truncate;
dayjs.extend(relativeTime);
export const UserLarge = memo(function UserLarge({ pubkey, time }: { pubkey: string; time: any }) {
const { db }: any = useContext(DatabaseContext);
const [profile, setProfile] = useState(null);
const fetchProfile = useCallback(async (id: string) => {
const res = await fetch(`https://rbr.bio/${id}/metadata.json`, {
method: 'GET',
timeout: 30,
});
return res.data;
}, []);
const getCacheProfile = useCallback(async () => {
const result: any = await db.select(`SELECT metadata FROM cache_profiles WHERE id = "${pubkey}"`);
return result[0];
}, [db, pubkey]);
const insertCacheProfile = useCallback(
async (event) => {
// update state
setProfile(JSON.parse(event.content));
// insert to database
await db.execute('INSERT OR IGNORE INTO cache_profiles (id, metadata) VALUES (?, ?);', [pubkey, event.content]);
},
[db, pubkey]
);
useEffect(() => {
getCacheProfile()
.then((res) => {
if (res !== undefined) {
setProfile(JSON.parse(res.metadata));
} else {
fetchProfile(pubkey)
.then((res) => insertCacheProfile(res))
.catch(console.error);
}
})
.catch(console.error);
}, [fetchProfile, getCacheProfile, insertCacheProfile, pubkey]);
return (
<div className="flex items-center gap-2">
<div className="relative h-11 w-11 shrink overflow-hidden rounded-md bg-zinc-900">
{profile?.picture ? (
<ImageWithFallback
src={profile.picture}
alt={pubkey}
fill={true}
className="rounded-md border border-white/10 object-cover"
/>
) : (
<Avatar
size={44}
name={pubkey}
variant="beam"
square={true}
colors={['#FEE2E2', '#FEF3C7', '#F59E0B', '#EC4899', '#D946EF', '#8B5CF6']}
/>
)}
</div>
<div className="w-full flex-1">
<div className="flex w-full justify-between">
<div className="flex flex-col gap-1 text-sm">
<span className="font-bold leading-tight text-zinc-100">
{profile?.display_name || profile?.name || truncate(pubkey, 16, ' .... ')}
</span>
<span className="leading-tight text-zinc-400">
{profile?.username || truncate(pubkey, 16, ' .... ')} · {dayjs().to(dayjs.unix(time))}
</span>
</div>
<div>
<button className="inline-flex h-5 w-5 items-center justify-center rounded hover:bg-zinc-800">
<DotsHorizontalIcon className="h-3 w-3 text-zinc-500" />
</button>
</div>
</div>
</div>
</div>
);
});

View File

@ -64,7 +64,9 @@ export const UserMini = memo(function UserMini({ pubkey }: { pubkey: string }) {
)}
</div>
<div className="inline-flex w-full flex-1 flex-col overflow-hidden">
<p className="truncate leading-tight text-zinc-300">{profile?.name || truncate(pubkey, 16, ' .... ')}</p>
<p className="truncate leading-tight text-zinc-300">
{profile?.display_name || profile?.name || truncate(pubkey, 16, ' .... ')}
</p>
</div>
</div>
);

View File

@ -2,9 +2,12 @@ import BaseLayout from '@layouts/base';
import WithSidebarLayout from '@layouts/withSidebar';
import { DatabaseContext } from '@components/contexts/database';
import { RelayContext } from '@components/contexts/relay';
import { Content } from '@components/note/content';
import { ContentExtend } from '@components/note/content/extend';
import FormComment from '@components/note/form/comment';
import useLocalStorage from '@rehooks/local-storage';
import { useRouter } from 'next/router';
import {
JSXElementConstructor,
@ -18,26 +21,65 @@ import {
} from 'react';
export default function Page() {
const router = useRouter();
const { db }: any = useContext(DatabaseContext);
const relayPool: any = useContext(RelayContext);
const router = useRouter();
const id = router.query.id;
const [root, setRoot] = useState(null);
const [relays]: any = useLocalStorage('relays');
const [rootEvent, setRootEvent] = useState(null);
const [comments, setComments] = useState([]);
const fetchRoot = useCallback(async () => {
const result = await db.select(`SELECT * FROM cache_notes WHERE id = "${id}"`);
setRoot(result[0]);
setRootEvent(result[0]);
}, [db, id]);
useEffect(() => {
fetchRoot().catch(console.error);
}, [fetchRoot]);
let unsubscribe: () => void;
fetchRoot()
.then(() => {
unsubscribe = relayPool.subscribe(
[
{
'#e': [id],
kinds: [1],
},
],
relays,
(event: any) => {
setComments((comments) => [...comments, event]);
}
);
})
.catch(console.error);
return () => {
unsubscribe();
};
}, [fetchRoot, id, relayPool, relays]);
return (
<div className="scrollbar-hide flex h-full flex-col gap-2 overflow-y-auto py-5">
<div className="flex h-min min-h-min w-full select-text flex-col px-3">{root && <Content data={root} />}</div>
<div className="flex h-min min-h-min w-full select-text flex-col px-3">
{rootEvent && <ContentExtend data={rootEvent} />}
</div>
<div>
<FormComment />
<FormComment eventID={id} />
</div>
<div className="flex flex-col">
{comments.length > 0 &&
comments.map((comment) => (
<div
key={comment.id}
className="flex h-min min-h-min w-full select-text flex-col border-b border-zinc-800 px-3 py-5 hover:bg-black/20"
>
<Content data={comment} />
</div>
))}
</div>
</div>
);