added kind 6 to newsfeed and changed useMetadata to useProfileMetadata

This commit is contained in:
Ren Amamiya 2023-04-16 16:43:17 +07:00
parent a7e95fd18a
commit 3aeb70f234
19 changed files with 297 additions and 83 deletions

View File

@ -3,6 +3,7 @@
import FormBase from '@components/form/base';
import { NoteBase } from '@components/note/base';
import { Placeholder } from '@components/note/placeholder';
import { NoteQuoteRepost } from '@components/note/quoteRepost';
import { filteredNotesAtom, hasNewerNoteAtom, notesAtom } from '@stores/note';
@ -25,7 +26,14 @@ export default function Page() {
const itemContent: any = useCallback(
(index: string | number) => {
return <NoteBase event={data[index]} />;
switch (data[index].kind) {
case 1:
return <NoteBase event={data[index]} />;
case 6:
return <NoteQuoteRepost event={data[index]} />;
default:
break;
}
},
[data]
);

View File

@ -66,7 +66,7 @@ export default function Page() {
since = dateToUnix(new Date(lastLogin));
}
query.push({
kinds: [1],
kinds: [1, 6],
authors: follows,
since: since,
until: dateToUnix(now.current),
@ -93,32 +93,52 @@ export default function Page() {
query,
relays,
(event) => {
if (event.kind === 1) {
const parentID = getParentID(event.tags, event.id);
// insert event to local database
createNote({
event_id: event.id,
pubkey: event.pubkey,
kind: event.kind,
tags: JSON.stringify(event.tags),
content: event.content,
parent_id: parentID,
parent_comment_id: '',
created_at: event.created_at,
account_id: account.id,
}).catch(console.error);
} else if (event.kind === 4) {
if (event.pubkey !== account.pubkey) {
createChat({
switch (event.kind) {
// short text note
case 1:
const parentID = getParentID(event.tags, event.id);
// insert event to local database
createNote({
event_id: event.id,
pubkey: event.pubkey,
kind: event.kind,
tags: JSON.stringify(event.tags),
content: event.content,
parent_id: parentID,
parent_comment_id: '',
created_at: event.created_at,
account_id: account.id,
}).catch(console.error);
}
} else if (event.kind === 40) {
createChannel({ event_id: event.id, content: event.content, account_id: account.id }).catch(console.error);
} else {
console.error;
break;
// chat
case 4:
if (event.pubkey !== account.pubkey) {
createChat({
pubkey: event.pubkey,
created_at: event.created_at,
account_id: account.id,
}).catch(console.error);
}
// repost
case 6:
createNote({
event_id: event.id,
pubkey: event.pubkey,
kind: event.kind,
tags: JSON.stringify(event.tags),
content: event.content,
parent_id: '',
parent_comment_id: '',
created_at: event.created_at,
account_id: account.id,
}).catch(console.error);
// channel
case 40:
createChannel({ event_id: event.id, content: event.content, account_id: account.id }).catch(
console.error
);
default:
break;
}
},
undefined,

View File

@ -2,14 +2,14 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { useProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { truncate } from '@utils/truncate';
import { useRouter } from 'next/navigation';
export const ChatListItem = ({ pubkey }: { pubkey: string }) => {
const router = useRouter();
const profile = useMetadata(pubkey);
const profile = useProfileMetadata(pubkey);
const openChat = () => {
router.push(`/chats/${pubkey}`);

View File

@ -2,7 +2,7 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { useProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { truncate } from '@utils/truncate';
import dayjs from 'dayjs';
@ -11,7 +11,7 @@ import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
export const MessageUser = ({ pubkey, time }: { pubkey: string; time: number }) => {
const profile = useMetadata(pubkey);
const profile = useProfileMetadata(pubkey);
return (
<div className="group flex items-start gap-3">

View File

@ -6,7 +6,7 @@ import { RelayContext } from '@components/relaysProvider';
import { hasNewerNoteAtom } from '@stores/note';
import { dateToUnix } from '@utils/getDate';
import { fetchMetadata } from '@utils/metadata';
import { fetchProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { getParentID, pubkeyArray } from '@utils/transform';
import useLocalStorage, { writeStorage } from '@rehooks/local-storage';
@ -31,7 +31,7 @@ export default function EventCollector() {
const { createPleb } = await import('@utils/bindings');
for (const tag of tags) {
const pubkey = tag[1];
fetchMetadata(pubkey)
fetchProfileMetadata(pubkey)
.then((res: { content: string }) => {
createPleb({
pleb_id: pubkey + '-lume' + activeAccount.id.toString(),
@ -55,7 +55,7 @@ export default function EventCollector() {
unsubscribe.current = pool.subscribe(
[
{
kinds: [1],
kinds: [1, 6],
authors: pubkeyArray(follows),
since: dateToUnix(now.current),
},
@ -75,39 +75,65 @@ export default function EventCollector() {
],
relays,
(event) => {
if (event.kind === 1) {
const parentID = getParentID(event.tags, event.id);
// insert event to local database
createNote({
event_id: event.id,
pubkey: event.pubkey,
kind: event.kind,
tags: JSON.stringify(event.tags),
content: event.content,
parent_id: parentID,
parent_comment_id: '',
created_at: event.created_at,
account_id: activeAccount.id,
})
.then(() =>
// notify user reload to get newer note
setHasNewerNote(true)
)
.catch(console.error);
} else if (event.kind === 3) {
createFollowingPlebs(event.tags);
} else if (event.kind === 4) {
if (event.pubkey !== activeAccount.pubkey) {
createChat({ pubkey: event.pubkey, created_at: event.created_at, account_id: activeAccount.id }).catch(
switch (event.kind) {
// short text note
case 1:
const parentID = getParentID(event.tags, event.id);
createNote({
event_id: event.id,
pubkey: event.pubkey,
kind: event.kind,
tags: JSON.stringify(event.tags),
content: event.content,
parent_id: parentID,
parent_comment_id: '',
created_at: event.created_at,
account_id: activeAccount.id,
})
.then(() =>
// notify user reload to get newer note
setHasNewerNote(true)
)
.catch(console.error);
break;
// contacts
case 3:
createFollowingPlebs(event.tags);
break;
// chat
case 4:
if (event.pubkey !== activeAccount.pubkey) {
createChat({
pubkey: event.pubkey,
created_at: event.created_at,
account_id: activeAccount.id,
}).catch(console.error);
}
// repost
case 6:
createNote({
event_id: event.id,
pubkey: event.pubkey,
kind: event.kind,
tags: JSON.stringify(event.tags),
content: event.content,
parent_id: '',
parent_comment_id: '',
created_at: event.created_at,
account_id: activeAccount.id,
})
.then(() =>
// notify user reload to get newer note
setHasNewerNote(true)
)
.catch(console.error);
// channel
case 40:
createChannel({ event_id: event.id, content: event.content, account_id: activeAccount.id }).catch(
console.error
);
}
} else if (event.kind === 40) {
createChannel({ event_id: event.id, content: event.content, account_id: activeAccount.id }).catch(
console.error
);
} else {
console.error;
default:
break;
}
}
);

View File

@ -1,7 +1,7 @@
import { useNavigatorOnLine } from '@utils/network';
import { useNetworkStatus } from '@utils/hooks/useNetworkStatus';
export const NetworkStatusIndicator = () => {
const isOnline = useNavigatorOnLine();
const isOnline = useNetworkStatus();
return (
<div className="inline-flex items-center gap-1 rounded-md px-1.5 py-1 hover:bg-zinc-900">

View File

@ -45,7 +45,7 @@ export const NoteBase = memo(function NoteBase({ event }: { event: any }) {
));
// handle mentions
if (tags.length > 0) {
parsedContent = reactStringReplace(parsedContent, /\#\[(\d+)\]/gm, (match, i) => {
parsedContent = reactStringReplace(parsedContent, /\#\[(\d+)\]/gm, (match) => {
if (tags[match][0] === 'p') {
// @-mentions
return <UserMention key={tags[match][1]} pubkey={tags[match][1]} />;
@ -90,7 +90,7 @@ export const NoteBase = memo(function NoteBase({ event }: { event: any }) {
onClick={(e) => openThread(e)}
className="relative z-10 m-0 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"
>
<>{parentNote}</>
{parentNote}
<div className="relative z-10 flex flex-col">
<div onClick={(e) => openUserPage(e)}>
<UserExtend pubkey={event.pubkey} time={event.createdAt || event.created_at} />

View File

@ -9,7 +9,7 @@ import destr from 'destr';
import { memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import reactStringReplace from 'react-string-replace';
export const NoteQuote = memo(function NoteRepost({ id }: { id: string }) {
export const NoteQuote = memo(function NoteQuote({ id }: { id: string }) {
const [pool, relays]: any = useContext(RelayContext);
const [activeAccount]: any = useLocalStorage('activeAccount', {});

View File

@ -0,0 +1,26 @@
import { RootNote } from '@components/note/rootNote';
import { UserQuoteRepost } from '@components/user/quoteRepost';
import { memo } from 'react';
export const NoteQuoteRepost = memo(function NoteQuoteRepost({ event }: { event: any }) {
const rootNote = () => {
let note = null;
if (event.content.length > 0) {
note = <RootNote event={JSON.parse(event.content)} />;
}
return note;
};
return (
<div className="relative z-10 m-0 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">
<div className="relative z-10 flex flex-col pb-8">
<div className="absolute left-[21px] top-0 h-full w-0.5 bg-gradient-to-t from-zinc-800 to-zinc-600"></div>
<UserQuoteRepost pubkey={event.pubkey} time={event.createdAt || event.created_at} />
</div>
{rootNote()}
</div>
);
});

View File

@ -0,0 +1,99 @@
import NoteMetadata from '@components/note/metadata';
import { ImagePreview } from '@components/note/preview/image';
import { VideoPreview } from '@components/note/preview/video';
import { NoteQuote } from '@components/note/quote';
import { UserExtend } from '@components/user/extend';
import { UserMention } from '@components/user/mention';
import destr from 'destr';
import { useRouter } from 'next/navigation';
import { memo, useMemo } from 'react';
import reactStringReplace from 'react-string-replace';
export const RootNote = memo(function RootNote({ event }: { event: any }) {
const router = useRouter();
const content = useMemo(() => {
let parsedContent = event.content;
// get data tags
const tags = destr(event.tags);
// handle urls
parsedContent = reactStringReplace(parsedContent, /(https?:\/\/\S+)/g, (match, i) => {
if (match.match(/\.(jpg|jpeg|gif|png|webp)$/i)) {
// image url
return <ImagePreview key={match + i} url={match} />;
} else if (match.match(/(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]{11})/i)) {
// youtube
return <VideoPreview key={match + i} url={match} />;
} else if (match.match(/\.(mp4|webm)$/i)) {
// video
return <VideoPreview key={match + i} url={match} />;
} else {
return (
<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="cursor-pointer text-fuchsia-500">
#{match}
</span>
));
// handle mentions
if (tags.length > 0) {
parsedContent = reactStringReplace(parsedContent, /\#\[(\d+)\]/gm, (match) => {
if (tags[match][0] === 'p') {
// @-mentions
return <UserMention key={tags[match][1]} pubkey={tags[match][1]} />;
} else if (tags[match][0] === 'e') {
// note-quotes
return <NoteQuote key={tags[match][1]} id={tags[match][1]} />;
} else {
return;
}
});
}
return parsedContent;
}, [event.content, event.tags]);
const openUserPage = (e) => {
e.stopPropagation();
router.push(`/users/${event.pubkey}`);
};
const openThread = (e) => {
const selection = window.getSelection();
if (selection.toString().length === 0) {
router.push(`/newsfeed/${event.parent_id}`);
} else {
e.stopPropagation();
}
};
return (
<div onClick={(e) => openThread(e)} className="relative z-10 flex flex-col">
<div onClick={(e) => openUserPage(e)}>
<UserExtend pubkey={event.pubkey} time={event.createdAt || event.created_at} />
</div>
<div className="-mt-5 pl-[52px]">
<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-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-img:m-0 prose-video:m-0">
{content}
</div>
</div>
</div>
<div onClick={(e) => e.stopPropagation()} className="mt-5 pl-[52px]">
<NoteMetadata
eventID={event.eventId}
eventPubkey={event.pubkey}
eventContent={event.content}
eventTime={event.createdAt || event.created_at}
/>
</div>
</div>
);
});

View File

@ -2,13 +2,13 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { useProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { truncate } from '@utils/truncate';
import { memo } from 'react';
export const UserBase = memo(function UserBase({ pubkey }: { pubkey: string }) {
const profile = useMetadata(pubkey);
const profile = useProfileMetadata(pubkey);
return (
<div className="flex items-center gap-2">

View File

@ -2,7 +2,7 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { useProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { truncate } from '@utils/truncate';
import dayjs from 'dayjs';
@ -12,7 +12,7 @@ import { MoreHoriz } from 'iconoir-react';
dayjs.extend(relativeTime);
export const UserExtend = ({ pubkey, time }: { pubkey: string; time: number }) => {
const profile = useMetadata(pubkey);
const profile = useProfileMetadata(pubkey);
return (
<div className="group flex items-start gap-2">

View File

@ -2,11 +2,11 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { useProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { truncate } from '@utils/truncate';
export const UserFollow = ({ pubkey }: { pubkey: string }) => {
const profile = useMetadata(pubkey);
const profile = useProfileMetadata(pubkey);
return (
<div className="flex items-center gap-2">

View File

@ -2,7 +2,7 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { useProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { truncate } from '@utils/truncate';
import dayjs from 'dayjs';
@ -12,7 +12,7 @@ import { MoreHoriz } from 'iconoir-react';
dayjs.extend(relativeTime);
export const UserLarge = ({ pubkey, time }: { pubkey: string; time: number }) => {
const profile = useMetadata(pubkey);
const profile = useProfileMetadata(pubkey);
return (
<div className="flex items-center gap-2">

View File

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

View File

@ -2,11 +2,11 @@ import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useMetadata } from '@utils/metadata';
import { useProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { truncate } from '@utils/truncate';
export const UserMini = ({ pubkey }: { pubkey: string }) => {
const profile = useMetadata(pubkey);
const profile = useProfileMetadata(pubkey);
return (
<div className="group flex items-start gap-1">

View File

@ -0,0 +1,35 @@
import { ImageWithFallback } from '@components/imageWithFallback';
import { DEFAULT_AVATAR } from '@stores/constants';
import { useProfileMetadata } from '@utils/hooks/useProfileMetadata';
import { truncate } from '@utils/truncate';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
export const UserQuoteRepost = ({ pubkey, time }: { pubkey: string; time: number }) => {
const profile = useProfileMetadata(pubkey);
return (
<div className="group flex items-center gap-2">
<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 object-cover"
/>
</div>
<div className="flex items-baseline gap-2 text-sm">
<h5 className="font-bold leading-tight group-hover:underline">
{profile?.display_name || profile?.name || truncate(pubkey, 16, ' .... ')} reposted
</h5>
<span className="leading-tight text-zinc-500">·</span>
<span className="text-zinc-500">{dayjs().to(dayjs.unix(time))}</span>
</div>
</div>
);
};

View File

@ -3,7 +3,7 @@ import { useEffect, useState } from 'react';
const getOnLineStatus = () =>
typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean' ? navigator.onLine : true;
export const useNavigatorOnLine = () => {
export const useNetworkStatus = () => {
const [status, setStatus] = useState(getOnLineStatus());
const setOnline = () => setStatus(true);

View File

@ -2,7 +2,7 @@ import useLocalStorage from '@rehooks/local-storage';
import { fetch } from '@tauri-apps/api/http';
import { useCallback, useEffect, useMemo, useState } from 'react';
export const fetchMetadata = async (pubkey: string) => {
export const fetchProfileMetadata = async (pubkey: string) => {
const result = await fetch(`https://rbr.bio/${pubkey}/metadata.json`, {
method: 'GET',
timeout: 5,
@ -10,7 +10,7 @@ export const fetchMetadata = async (pubkey: string) => {
return await result.data;
};
export const useMetadata = (pubkey) => {
export const useProfileMetadata = (pubkey) => {
const [activeAccount]: any = useLocalStorage('activeAccount', {});
const [plebs] = useLocalStorage('activeAccountFollows', []);
const [profile, setProfile] = useState(null);
@ -47,7 +47,7 @@ export const useMetadata = (pubkey) => {
useEffect(() => {
if (!cacheProfile) {
fetchMetadata(pubkey)
fetchProfileMetadata(pubkey)
.then((res: any) => {
// update state
setProfile(JSON.parse(res.content));