update thread

This commit is contained in:
Ren Amamiya
2023-06-27 11:42:12 +07:00
parent 2f553d8039
commit 6abff45678
25 changed files with 396 additions and 295 deletions

View File

@@ -77,7 +77,11 @@ export function OnboardingScreen() {
className="inline-flex h-12 w-full items-center justify-between gap-2 rounded-lg px-6 font-medium text-zinc-100 bg-fuchsia-500 hover:bg-fuchsia-600" className="inline-flex h-12 w-full items-center justify-between gap-2 rounded-lg px-6 font-medium text-zinc-100 bg-fuchsia-500 hover:bg-fuchsia-600"
> >
{loading ? ( {loading ? (
<LoaderIcon className="h-4 w-4 animate-spin text-black dark:text-zinc-100" /> <>
<span className="w-5" />
<LoaderIcon className="h-4 w-4 animate-spin text-black dark:text-zinc-100" />
<span className="w-5" />
</>
) : ( ) : (
<> <>
<span className="w-5" /> <span className="w-5" />

View File

@@ -6,54 +6,52 @@ import { NavLink } from "react-router-dom";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
export function ChatsListItem({ data }: { data: any }) { export function ChatsListItem({ data }: { data: any }) {
const { status, user, isFetching } = useProfile(data.sender_pubkey); const { status, user } = useProfile(data.sender_pubkey);
if (status === "loading") {
return (
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5">
<div className="relative h-6 w-6 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>
);
}
return ( return (
<> <NavLink
{status === "loading" && isFetching ? ( to={`/app/chat/${data.sender_pubkey}`}
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5"> preventScrollReset={true}
<div className="relative h-6 w-6 shrink-0 animate-pulse rounded bg-zinc-800" /> className={({ isActive }) =>
<div> twMerge(
<div className="h-2.5 w-full animate-pulse truncate rounded bg-zinc-800 text-base font-medium" /> "inline-flex h-9 items-center gap-2.5 rounded-md px-2.5",
</div> isActive ? "bg-zinc-900/50 text-zinc-100" : "",
)
}
>
<div className="inline-flex shrink-0 h-6 w-6 items-center justify-center rounded border-t border-zinc-800/50 bg-zinc-900">
<Image
src={user?.image}
fallback={DEFAULT_AVATAR}
alt={data.sender_pubkey}
className="h-6 w-6 rounded object-cover"
/>
</div>
<div className="w-full inline-flex items-center justify-between">
<div className="inline-flex items-baseline gap-1">
<h5 className="max-w-[9rem] truncate font-medium text-zinc-200">
{user?.nip05 || user?.displayName || shortenKey(data.sender_pubkey)}
</h5>
</div> </div>
) : ( <div className="flex items-center">
<NavLink {data.new_messages > 0 && (
to={`/app/chat/${data.sender_pubkey}`} <span className="inline-flex items-center justify-center rounded bg-fuchsia-400/10 w-8 px-1 py-1 text-xs font-medium text-fuchsia-500 ring-1 ring-inset ring-fuchsia-400/20">
preventScrollReset={true} {data.new_messages}
className={({ isActive }) => </span>
twMerge( )}
"inline-flex h-9 items-center gap-2.5 rounded-md px-2.5", </div>
isActive ? "bg-zinc-900/50 text-zinc-100" : "", </div>
) </NavLink>
}
>
<div className="inline-flex shrink-0 h-6 w-6 items-center justify-center rounded border-t border-zinc-800/50 bg-zinc-900">
<Image
src={user?.image}
fallback={DEFAULT_AVATAR}
alt={data.sender_pubkey}
className="h-6 w-6 rounded object-cover"
/>
</div>
<div className="w-full inline-flex items-center justify-between">
<div className="inline-flex items-baseline gap-1">
<h5 className="max-w-[9rem] truncate font-medium text-zinc-200">
{user?.nip05 ||
user?.displayName ||
shortenKey(data.sender_pubkey)}
</h5>
</div>
<div className="flex items-center">
{data.new_messages > 0 && (
<span className="inline-flex items-center justify-center rounded bg-fuchsia-400/10 w-8 px-1 py-1 text-xs font-medium text-fuchsia-500 ring-1 ring-inset ring-fuchsia-400/20">
{data.new_messages}
</span>
)}
</div>
</div>
</NavLink>
)}
</>
); );
} }

View File

@@ -26,6 +26,21 @@ export function ChatsList() {
}, },
); );
if (status === "loading") {
return (
<div className="flex flex-col">
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5">
<div className="relative h-6 w-6 shrink-0 animate-pulse rounded bg-zinc-800" />
<div className="h-3 w-full rounded-sm animate-pulse bg-zinc-800" />
</div>
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5">
<div className="relative h-6 w-6 shrink-0 animate-pulse rounded bg-zinc-800" />
<div className="h-3 w-full rounded-sm animate-pulse bg-zinc-800" />
</div>
</div>
);
}
return ( return (
<div className="flex flex-col"> <div className="flex flex-col">
<NewMessageModal /> <NewMessageModal />
@@ -37,24 +52,11 @@ export function ChatsList() {
<div className="h-3 w-full rounded-sm animate-pulse bg-zinc-800" /> <div className="h-3 w-full rounded-sm animate-pulse bg-zinc-800" />
</div> </div>
)} )}
{status === "loading" ? ( {chats.map((item) => {
<> if (account.pubkey !== item.sender_pubkey) {
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5"> return <ChatsListItem key={item.sender_pubkey} data={item} />;
<div className="relative h-6 w-6 shrink-0 animate-pulse rounded bg-zinc-800" /> }
<div className="h-3 w-full rounded-sm animate-pulse bg-zinc-800" /> })}
</div>
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5">
<div className="relative h-6 w-6 shrink-0 animate-pulse rounded bg-zinc-800" />
<div className="h-3 w-full rounded-sm animate-pulse bg-zinc-800" />
</div>
</>
) : (
chats.map((item) => {
if (account.pubkey !== item.sender_pubkey) {
return <ChatsListItem key={item.sender_pubkey} data={item} />;
}
})
)}
{isFetching && ( {isFetching && (
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5"> <div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5">
<div className="relative h-6 w-6 shrink-0 animate-pulse rounded bg-zinc-800" /> <div className="relative h-6 w-6 shrink-0 animate-pulse rounded bg-zinc-800" />

View File

@@ -6,44 +6,44 @@ import { NavLink } from "react-router-dom";
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge";
export function ChatsListSelfItem({ data }: { data: any }) { export function ChatsListSelfItem({ data }: { data: any }) {
const { status, user, isFetching } = useProfile(data.pubkey); const { status, user } = useProfile(data.pubkey);
if (status === "loading") {
return (
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5">
<div className="relative h-6 w-6 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>
);
}
return ( return (
<> <NavLink
{status === "loading" && isFetching ? ( to={`/app/chat/${data.pubkey}`}
<div className="inline-flex h-9 items-center gap-2.5 rounded-md px-2.5"> preventScrollReset={true}
<div className="relative h-6 w-6 shrink-0 animate-pulse rounded bg-zinc-800" /> className={({ isActive }) =>
<div> twMerge(
<div className="h-2.5 w-full animate-pulse truncate rounded bg-zinc-800 text-base font-medium" /> "inline-flex h-9 items-center gap-2.5 rounded-md px-2.5",
</div> isActive ? "bg-zinc-900/50 text-zinc-100" : "",
</div> )
) : ( }
<NavLink >
to={`/app/chat/${data.pubkey}`} <div className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded border-t border-zinc-800/50 bg-zinc-900">
preventScrollReset={true} <Image
className={({ isActive }) => src={user?.image}
twMerge( fallback={DEFAULT_AVATAR}
"inline-flex h-9 items-center gap-2.5 rounded-md px-2.5", alt={data.pubkey}
isActive ? "bg-zinc-900/50 text-zinc-100" : "", className="h-6 w-6 rounded bg-white object-cover"
) />
} </div>
> <div className="inline-flex items-baseline gap-1">
<div className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded border-t border-zinc-800/50 bg-zinc-900"> <h5 className="max-w-[9rem] truncate font-medium text-zinc-200">
<Image {user?.nip05 || user?.name || shortenKey(data.pubkey)}
src={user?.image} </h5>
fallback={DEFAULT_AVATAR} <span className="text-zinc-500">(you)</span>
alt={data.pubkey} </div>
className="h-6 w-6 rounded bg-white object-cover" </NavLink>
/>
</div>
<div className="inline-flex items-baseline gap-1">
<h5 className="max-w-[9rem] truncate font-medium text-zinc-200">
{user?.nip05 || user?.name || shortenKey(data.pubkey)}
</h5>
<span className="text-zinc-500">(you)</span>
</div>
</NavLink>
)}
</>
); );
} }

View File

@@ -28,22 +28,18 @@ export function Root() {
async function fetchNotes() { async function fetchNotes() {
try { try {
const follows = JSON.parse(account.follows); const follows = JSON.parse(account.follows);
let queryNoteSince: number; let since: number;
if (totalNotes === 0) { if (totalNotes === 0 || lastLogin === 0) {
queryNoteSince = dateToUnix(getHourAgo(48, now.current)); since = dateToUnix(getHourAgo(48, now.current));
} else { } else {
if (lastLogin > 0) { since = lastLogin;
queryNoteSince = lastLogin;
} else {
queryNoteSince = dateToUnix(getHourAgo(48, now.current));
}
} }
const filter: NDKFilter = { const filter: NDKFilter = {
kinds: [1, 6], kinds: [1, 6],
authors: follows, authors: follows,
since: queryNoteSince, since: since,
}; };
const events = await prefetchEvents(ndk, filter); const events = await prefetchEvents(ndk, filter);

View File

@@ -15,25 +15,19 @@ const TIME = Math.floor(Date.now() / 1000);
export function FeedBlock({ params }: { params: any }) { export function FeedBlock({ params }: { params: any }) {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { const { status, data, fetchNextPage, hasNextPage, isFetchingNextPage }: any =
status, useInfiniteQuery({
data, queryKey: ["newsfeed", params.content],
fetchNextPage, queryFn: async ({ pageParam = 0 }) => {
hasNextPage, return await getNotesByAuthors(
isFetching, params.content,
isFetchingNextPage, TIME,
}: any = useInfiniteQuery({ ITEM_PER_PAGE,
queryKey: ["newsfeed", params.content], pageParam,
queryFn: async ({ pageParam = 0 }) => { );
return await getNotesByAuthors( },
params.content, getNextPageParam: (lastPage) => lastPage.nextCursor,
TIME, });
ITEM_PER_PAGE,
pageParam,
);
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
const notes = data ? data.pages.flatMap((d: { data: any }) => d.data) : []; const notes = data ? data.pages.flatMap((d: { data: any }) => d.data) : [];
const parentRef = useRef(); const parentRef = useRef();
@@ -119,7 +113,7 @@ export function FeedBlock({ params }: { params: any }) {
</div> </div>
</div> </div>
)} )}
{isFetching && !isFetchingNextPage && ( {isFetchingNextPage && (
<div className="px-3 py-1.5"> <div className="px-3 py-1.5">
<div className="rounded-xl border-t border-zinc-800/50 bg-zinc-900 px-3 py-3"> <div className="rounded-xl border-t border-zinc-800/50 bg-zinc-900 px-3 py-3">
<NoteSkeleton /> <NoteSkeleton />

View File

@@ -1,30 +1,31 @@
import { createNote, getNotes } from "@libs/storage"; import { useNewsfeed } from "@app/space/hooks/useNewsfeed";
import { NDKEvent, NDKFilter, NDKSubscription } from "@nostr-dev-kit/ndk"; import { getNotes } from "@libs/storage";
import { Note } from "@shared/notes/note"; import { Note } from "@shared/notes/note";
import { NoteSkeleton } from "@shared/notes/skeleton"; import { NoteSkeleton } from "@shared/notes/skeleton";
import { RelayContext } from "@shared/relayProvider";
import { TitleBar } from "@shared/titleBar"; import { TitleBar } from "@shared/titleBar";
import { useNote } from "@stores/note";
import { useInfiniteQuery } from "@tanstack/react-query"; import { useInfiniteQuery } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual"; import { useVirtualizer } from "@tanstack/react-virtual";
import { dateToUnix } from "@utils/date"; import { useEffect, useRef } from "react";
import { useAccount } from "@utils/hooks/useAccount";
import { useContext, useEffect, useRef } from "react";
const ITEM_PER_PAGE = 10; const ITEM_PER_PAGE = 10;
const TIME = Math.floor(Date.now() / 1000); const TIME = Math.floor(Date.now() / 1000);
export function FollowingBlock({ block }: { block: number }) { export function FollowingBlock({ block }: { block: number }) {
const ndk = useContext(RelayContext); // subscribe for live update
useNewsfeed();
const { account } = useAccount(); const [hasNewNote, toggleHasNewNote] = useNote((state) => [
state.hasNewNote,
state.toggleHasNewNote,
]);
const { const {
status, status,
data, data,
fetchNextPage, fetchNextPage,
hasNextPage, hasNextPage,
isFetching,
isFetchingNextPage, isFetchingNextPage,
refetch,
}: any = useInfiniteQuery({ }: any = useInfiniteQuery({
queryKey: ["newsfeed-circle"], queryKey: ["newsfeed-circle"],
queryFn: async ({ pageParam = 0 }) => { queryFn: async ({ pageParam = 0 }) => {
@@ -61,39 +62,17 @@ export function FollowingBlock({ block }: { block: number }) {
} }
}, [notes.length, fetchNextPage, rowVirtualizer.getVirtualItems()]); }, [notes.length, fetchNextPage, rowVirtualizer.getVirtualItems()]);
useEffect(() => { const refreshFirstPage = () => {
const follows = account ? JSON.parse(account.follows) : []; // refetch
refetch({ refetchPage: (page, index) => index === 0 });
const filter: NDKFilter = { // scroll to top
kinds: [1, 6], rowVirtualizer.scrollToIndex(1);
authors: follows, // stop notify
since: dateToUnix(), toggleHasNewNote(false);
}; };
const sub = account ? ndk.subscribe(filter) : null;
if (sub) {
sub.addListener("event", (event: NDKEvent) => {
createNote(
event.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
);
});
}
return () => {
if (sub) {
sub.stop();
}
};
}, [account]);
const renderItem = (index: string | number) => { const renderItem = (index: string | number) => {
const note = notes[index]; const note = notes[index];
if (!note) return; if (!note) return;
return ( return (
<div key={index} data-index={index} ref={rowVirtualizer.measureElement}> <div key={index} data-index={index} ref={rowVirtualizer.measureElement}>
@@ -103,8 +82,19 @@ export function FollowingBlock({ block }: { block: number }) {
}; };
return ( return (
<div className="shrink-0 w-[400px] border-r border-zinc-900"> <div className="shrink-0 relative w-[400px] border-r border-zinc-900">
<TitleBar title="Circle" /> <TitleBar title="Circle" />
{hasNewNote && (
<div className="z-50 absolute top-12 left-1/2 transform -translate-x-1/2">
<button
type="button"
onClick={() => refreshFirstPage()}
className="inline-flex items-center justify-center w-min px-3.5 py-1.5 rounded-full bg-fuchsia-500 hover:bg-fuchsia-600 border border-fuchsia-800/50 text-sm"
>
Newest
</button>
</div>
)}
<div <div
ref={parentRef} ref={parentRef}
className="scrollbar-hide flex w-full h-full flex-col justify-between gap-1.5 pt-1.5 pb-20 overflow-y-auto" className="scrollbar-hide flex w-full h-full flex-col justify-between gap-1.5 pt-1.5 pb-20 overflow-y-auto"
@@ -138,7 +128,7 @@ export function FollowingBlock({ block }: { block: number }) {
</div> </div>
</div> </div>
)} )}
{isFetching && !isFetchingNextPage && ( {isFetchingNextPage && (
<div className="px-3 py-1.5"> <div className="px-3 py-1.5">
<div className="rounded-xl border-t border-zinc-800/50 bg-zinc-900 px-3 py-3"> <div className="rounded-xl border-t border-zinc-800/50 bg-zinc-900 px-3 py-3">
<NoteSkeleton /> <NoteSkeleton />

View File

@@ -1,3 +1,4 @@
import { useLiveThread } from "@app/space/hooks/useLiveThread";
import { getNoteByID, removeBlock } from "@libs/storage"; import { getNoteByID, removeBlock } from "@libs/storage";
import { Kind1 } from "@shared/notes/contents/kind1"; import { Kind1 } from "@shared/notes/contents/kind1";
import { Kind1063 } from "@shared/notes/contents/kind1063"; import { Kind1063 } from "@shared/notes/contents/kind1063";
@@ -11,14 +12,15 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { parser } from "@utils/parser"; import { parser } from "@utils/parser";
export function ThreadBlock({ params }: { params: any }) { export function ThreadBlock({ params }: { params: any }) {
useLiveThread(params.content);
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { status, data, isFetching } = useQuery( const { status, data } = useQuery(["thread", params.content], async () => {
["thread", params.content], const res = await getNoteByID(params.content);
async () => { res["content"] = parser(res);
return await getNoteByID(params.content); return res;
}, });
);
const block = useMutation({ const block = useMutation({
mutationFn: (id: string) => { mutationFn: (id: string) => {
@@ -29,13 +31,11 @@ export function ThreadBlock({ params }: { params: any }) {
}, },
}); });
const content = data ? parser(data) : null;
return ( return (
<div className="shrink-0 w-[400px] border-r border-zinc-900"> <div className="shrink-0 w-[400px] border-r border-zinc-900">
<TitleBar title={params.title} onClick={() => block.mutate(params.id)} /> <TitleBar title={params.title} onClick={() => block.mutate(params.id)} />
<div className="scrollbar-hide flex w-full h-full flex-col gap-1.5 pt-1.5 pb-20 overflow-y-auto"> <div className="scrollbar-hide flex w-full h-full flex-col gap-1.5 pt-1.5 pb-20 overflow-y-auto">
{status === "loading" || isFetching ? ( {status === "loading" ? (
<div className="px-3 py-1.5"> <div className="px-3 py-1.5">
<div className="rounded-md bg-zinc-900 px-3 py-3 shadow-input shadow-black/20"> <div className="rounded-md bg-zinc-900 px-3 py-3 shadow-input shadow-black/20">
<NoteSkeleton /> <NoteSkeleton />
@@ -46,13 +46,16 @@ export function ThreadBlock({ params }: { params: any }) {
<div className="rounded-md bg-zinc-900 px-5 pt-5"> <div className="rounded-md bg-zinc-900 px-5 pt-5">
<User pubkey={data.pubkey} time={data.created_at} /> <User pubkey={data.pubkey} time={data.created_at} />
<div className="mt-3"> <div className="mt-3">
{data.kind === 1 && <Kind1 content={content} />} {data.kind === 1 && <Kind1 content={data.content} />}
{data.kind === 1063 && <Kind1063 metadata={data.tags} />} {data.kind === 1063 && <Kind1063 metadata={data.tags} />}
<NoteMetadata id={params.content} eventPubkey={data.pubkey} /> <NoteMetadata
id={data.event_id || params.content}
eventPubkey={data.pubkey}
/>
</div> </div>
</div> </div>
<div className="mt-3 bg-zinc-900 rounded-md"> <div className="mt-3 bg-zinc-900 rounded-md">
<NoteReplyForm id={data.id} /> <NoteReplyForm id={params.content} />
</div> </div>
</div> </div>
)} )}

View File

@@ -0,0 +1,46 @@
import { createReplyNote } from "@libs/storage";
import { NDKEvent, NDKFilter } from "@nostr-dev-kit/ndk";
import { RelayContext } from "@shared/relayProvider";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useContext, useEffect, useRef } from "react";
export function useLiveThread(id: string) {
const ndk = useContext(RelayContext);
const queryClient = useQueryClient();
const now = useRef(Math.floor(Date.now() / 1000));
const thread = useMutation({
mutationFn: (data: NDKEvent) => {
return createReplyNote(
id,
data.id,
data.pubkey,
data.kind,
data.tags,
data.content,
data.created_at,
);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["replies", id] });
},
});
useEffect(() => {
const filter: NDKFilter = {
kinds: [1],
"#e": [id],
since: now.current,
};
const sub = ndk.subscribe(filter, { closeOnEose: false });
sub.addListener("event", (event: NDKEvent) => {
thread.mutate(event);
});
return () => {
sub.stop();
};
}, []);
}

View File

@@ -0,0 +1,48 @@
import { createNote } from "@libs/storage";
import { NDKEvent, NDKFilter } from "@nostr-dev-kit/ndk";
import { RelayContext } from "@shared/relayProvider";
import { useNote } from "@stores/note";
import { useAccount } from "@utils/hooks/useAccount";
import { useContext, useEffect, useRef } from "react";
export function useNewsfeed() {
const ndk = useContext(RelayContext);
const sub = useRef(null);
const now = useRef(Math.floor(Date.now() / 1000));
const toggleHasNewNote = useNote((state) => state.toggleHasNewNote);
const { status, account } = useAccount();
useEffect(() => {
if (status === "success" && account) {
const follows = account ? JSON.parse(account.follows) : [];
const filter: NDKFilter = {
kinds: [1, 6],
authors: follows,
since: now.current,
};
sub.current = ndk.subscribe(filter, { closeOnEose: false });
sub.current.addListener("event", (event: NDKEvent) => {
console.log("new note: ", event);
// add to db
createNote(
event.id,
event.pubkey,
event.kind,
event.tags,
event.content,
event.created_at,
);
// notify user about created note
toggleHasNewNote(true);
});
}
return () => {
sub.current.stop();
};
}, [status]);
}

View File

@@ -5,16 +5,15 @@ import { compactNumber } from "@utils/number";
import { shortenKey } from "@utils/shortenKey"; import { shortenKey } from "@utils/shortenKey";
export function Profile({ data }: { data: any }) { export function Profile({ data }: { data: any }) {
const { const { status, data: userStats } = useQuery(
status, ["user-stats", data.pubkey],
data: userStats, async () => {
isFetching, const res = await fetch(
} = useQuery(["user-stats", data.pubkey], async () => { `https://api.nostr.band/v0/stats/profile/${data.pubkey}`,
const res = await fetch( );
`https://api.nostr.band/v0/stats/profile/${data.pubkey}`, return res.json();
); },
return res.json(); );
});
const embedProfile = data.profile ? JSON.parse(data.profile.content) : null; const embedProfile = data.profile ? JSON.parse(data.profile.content) : null;
const profile = embedProfile; const profile = embedProfile;
@@ -51,7 +50,7 @@ export function Profile({ data }: { data: any }) {
</p> </p>
</div> </div>
<div className="mt-8"> <div className="mt-8">
{status === "loading" || isFetching ? ( {status === "loading" ? (
<p>Loading...</p> <p>Loading...</p>
) : ( ) : (
<div className="w-full flex items-center gap-8"> <div className="w-full flex items-center gap-8">

View File

@@ -4,19 +4,16 @@ import { TitleBar } from "@shared/titleBar";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
export function TrendingNotes() { export function TrendingNotes() {
const { status, data, isFetching } = useQuery( const { status, data } = useQuery(["trending-notes"], async () => {
["trending-notes"], const res = await fetch("https://api.nostr.band/v0/trending/notes");
async () => { return res.json();
const res = await fetch("https://api.nostr.band/v0/trending/notes"); });
return res.json();
},
);
return ( return (
<div className="shrink-0 w-[360px] flex-col flex border-r border-zinc-900"> <div className="shrink-0 w-[360px] flex-col flex border-r border-zinc-900">
<TitleBar title="Trending Posts" /> <TitleBar title="Trending Posts" />
<div className="scrollbar-hide flex w-full h-full flex-col justify-between gap-1.5 pt-1.5 pb-20 overflow-y-auto"> <div className="scrollbar-hide flex w-full h-full flex-col justify-between gap-1.5 pt-1.5 pb-20 overflow-y-auto">
{status === "loading" || isFetching ? ( {status === "loading" ? (
<div className="px-3 py-1.5"> <div className="px-3 py-1.5">
<div className="rounded-md bg-zinc-900 px-3 py-3 shadow-input shadow-black/20"> <div className="rounded-md bg-zinc-900 px-3 py-3 shadow-input shadow-black/20">
<NoteSkeleton /> <NoteSkeleton />

View File

@@ -4,19 +4,16 @@ import { TitleBar } from "@shared/titleBar";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
export function TrendingProfiles() { export function TrendingProfiles() {
const { status, data, isFetching } = useQuery( const { status, data } = useQuery(["trending-profiles"], async () => {
["trending-profiles"], const res = await fetch("https://api.nostr.band/v0/trending/profiles");
async () => { return res.json();
const res = await fetch("https://api.nostr.band/v0/trending/profiles"); });
return res.json();
},
);
return ( return (
<div className="shrink-0 w-[360px] flex-col flex border-r border-zinc-900"> <div className="shrink-0 w-[360px] flex-col flex border-r border-zinc-900">
<TitleBar title="Trending Profiles" /> <TitleBar title="Trending Profiles" />
<div className="scrollbar-hide flex w-full h-full flex-col justify-between gap-1.5 pt-1.5 pb-20 overflow-y-auto"> <div className="scrollbar-hide flex w-full h-full flex-col justify-between gap-1.5 pt-1.5 pb-20 overflow-y-auto">
{status === "loading" || isFetching ? ( {status === "loading" ? (
<div className="px-3 py-1.5"> <div className="px-3 py-1.5">
<div className="rounded-md bg-zinc-900 px-3 py-3 shadow-input shadow-black/20"> <div className="rounded-md bg-zinc-900 px-3 py-3 shadow-input shadow-black/20">
<NoteSkeleton /> <NoteSkeleton />

View File

@@ -1,3 +1,4 @@
import { createReplyNote } from "./storage";
import NDK, { import NDK, {
NDKConstructorParams, NDKConstructorParams,
NDKEvent, NDKEvent,
@@ -10,12 +11,22 @@ import { FULL_RELAYS } from "@stores/constants";
import { useAccount } from "@utils/hooks/useAccount"; import { useAccount } from "@utils/hooks/useAccount";
import { useContext } from "react"; import { useContext } from "react";
export async function initNDK( export async function initNDK(relays?: string[]): Promise<NDK> {
relays?: string[],
cache?: boolean,
): Promise<NDK> {
const opts: NDKConstructorParams = {}; const opts: NDKConstructorParams = {};
opts.explicitRelayUrls = relays || FULL_RELAYS; const defaultRelays = new Set(relays || FULL_RELAYS);
/*
for (const relay of defaultRelays) {
const url = new URL(relay);
url.protocol = url.protocol = url.protocol.replace("wss", "https");
const res = await fetch(url.href, { method: "HEAD", timeout: 5 });
if (!res.ok) {
defaultRelays.delete(relay);
}
}
*/
opts.explicitRelayUrls = [...defaultRelays];
const ndk = new NDK(opts); const ndk = new NDK(opts);
await ndk.connect(); await ndk.connect();
@@ -40,7 +51,7 @@ export async function prefetchEvents(
}); });
relaySetSubscription.on("eose", () => { relaySetSubscription.on("eose", () => {
setTimeout(() => resolve(new Set(events.values())), 5000); setTimeout(() => resolve(new Set(events.values())), 3000);
}); });
}); });
} }
@@ -54,11 +65,15 @@ export function usePublish() {
ndk.signer = signer; ndk.signer = signer;
} }
function publish({ const publish = ({
content, content,
kind, kind,
tags, tags,
}: { content: string; kind: NDKKind; tags: string[][] }) { }: {
content: string;
kind: NDKKind;
tags: string[][];
}): NDKEvent => {
const event = new NDKEvent(ndk); const event = new NDKEvent(ndk);
event.content = content; event.content = content;
@@ -68,7 +83,9 @@ export function usePublish() {
event.tags = tags; event.tags = tags;
event.publish(); event.publish();
}
return event;
};
return publish; return publish;
} }

View File

@@ -20,6 +20,6 @@ root.render(
<RelayProvider> <RelayProvider>
<App /> <App />
</RelayProvider> </RelayProvider>
<ReactQueryDevtools initialIsOpen={false} /> <ReactQueryDevtools initialIsOpen={false} position="top-right" />
</QueryClientProvider>, </QueryClientProvider>,
); );

View File

@@ -87,19 +87,21 @@ export function ActiveAccount({ data }: { data: any }) {
}; };
}, []); }, []);
if (status === "loading") {
return <div className="w-9 h-9 rounded bg-zinc-800 animate-pulse" />;
}
return ( return (
<button type="button" className="relative inline-block h-9 w-9"> <div className="inline-flex items-center gap-2">
{status === "loading" ? ( <div className="relative inline-block h-9 w-9">
<div className="w-9 h-9 rounded bg-zinc-800 animate-pulse" />
) : (
<Image <Image
src={user.image} src={user.image}
fallback={DEFAULT_AVATAR} fallback={DEFAULT_AVATAR}
alt={data.npub} alt={data.npub}
className="h-9 w-9 rounded object-cover" className="h-9 w-9 rounded object-cover"
/> />
)} <NetworkStatusIndicator />
<NetworkStatusIndicator /> </div>
</button> </div>
); );
} }

View File

@@ -7,13 +7,12 @@ import { useState } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
export function MultiAccounts() { export function MultiAccounts() {
const { const { status, data: activeAccount } = useQuery(
status, ["activeAccount"],
data: activeAccount, async () => {
isFetching, return await getActiveAccount();
} = useQuery(["activeAccount"], async () => { },
return await getActiveAccount(); );
});
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@@ -25,7 +24,7 @@ export function MultiAccounts() {
<div className="flex flex-col gap-2 rounded-xl p-2 border-t border-zinc-800/50 bg-zinc-900/80 backdrop-blur-md"> <div className="flex flex-col gap-2 rounded-xl p-2 border-t border-zinc-800/50 bg-zinc-900/80 backdrop-blur-md">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{status === "loading" || isFetching ? ( {status === "loading" ? (
<div className="group relative flex h-9 w-9 shrink animate-pulse items-center justify-center rounded-lg bg-zinc-900" /> <div className="group relative flex h-9 w-9 shrink animate-pulse items-center justify-center rounded-lg bg-zinc-900" />
) : ( ) : (
<ActiveAccount data={activeAccount} /> <ActiveAccount data={activeAccount} />

View File

@@ -8,7 +8,7 @@ import { useEvent } from "@utils/hooks/useEvent";
import { memo } from "react"; import { memo } from "react";
export const MentionNote = memo(function MentionNote({ id }: { id: string }) { export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
const { status, data, isFetching } = useEvent(id); const { status, data } = useEvent(id);
const kind1 = data?.kind === 1 ? data.content : null; const kind1 = data?.kind === 1 ? data.content : null;
const kind1063 = data?.kind === 1063 ? data.tags : null; const kind1063 = data?.kind === 1063 ? data.tags : null;
@@ -39,7 +39,7 @@ export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
onKeyDown={(e) => openThread(e, id)} onKeyDown={(e) => openThread(e, id)}
className="mt-3 rounded-lg bg-zinc-800 border-t border-zinc-700/50 px-3 py-3" className="mt-3 rounded-lg bg-zinc-800 border-t border-zinc-700/50 px-3 py-3"
> >
{isFetching || status === "loading" ? ( {status === "loading" ? (
<NoteSkeleton /> <NoteSkeleton />
) : ( ) : (
<> <>

View File

@@ -19,60 +19,57 @@ export function NoteMetadata({
currentBlock?: number; currentBlock?: number;
}) { }) {
const ndk = useContext(RelayContext); const ndk = useContext(RelayContext);
const { status, data, isFetching } = useQuery( const { status, data } = useQuery(["note-metadata", id], async () => {
["note-metadata", id], let replies = 0;
async () => { let reposts = 0;
let replies = 0; let zap = 0;
let reposts = 0;
let zap = 0;
const filter: NDKFilter = { const filter: NDKFilter = {
"#e": [id], "#e": [id],
kinds: [1, 6, 9735], kinds: [1, 6, 9735],
}; };
const events = await ndk.fetchEvents(filter); const events = await ndk.fetchEvents(filter);
events.forEach((event: NDKEvent) => { events.forEach((event: NDKEvent) => {
switch (event.kind) { switch (event.kind) {
case 1: case 1:
replies += 1; replies += 1;
createReplyNote( createReplyNote(
id, id,
event.id, event.id,
event.pubkey, event.pubkey,
event.kind, event.kind,
event.tags, event.tags,
event.content, event.content,
event.created_at, event.created_at,
);
break;
case 6:
reposts += 1;
break;
case 9735: {
const bolt11 = event.tags.find((tag) => tag[0] === "bolt11")[1];
if (bolt11) {
const decoded = decode(bolt11);
const amount = decoded.sections.find(
(item) => item.name === "amount",
); );
break; const sats = amount.value / 1000;
case 6: zap += sats;
reposts += 1;
break;
case 9735: {
const bolt11 = event.tags.find((tag) => tag[0] === "bolt11")[1];
if (bolt11) {
const decoded = decode(bolt11);
const amount = decoded.sections.find(
(item) => item.name === "amount",
);
const sats = amount.value / 1000;
zap += sats;
}
break;
} }
default: break;
break;
} }
}); default:
break;
}
});
return { replies, reposts, zap }; return { replies, reposts, zap };
}, });
);
return ( return (
<div className="inline-flex items-center w-full h-12 mt-2"> <div className="inline-flex items-center w-full h-12 mt-2">
{status === "loading" || isFetching ? ( {status === "loading" ? (
<> <>
<div className="w-20 group inline-flex items-center gap-1.5"> <div className="w-20 group inline-flex items-center gap-1.5">
<ReplyIcon <ReplyIcon

View File

@@ -9,12 +9,12 @@ export function NoteParent({
id, id,
currentBlock, currentBlock,
}: { id: string; currentBlock: number }) { }: { id: string; currentBlock: number }) {
const { status, data, isFetching } = useEvent(id); const { status, data } = useEvent(id);
return ( return (
<div className="relative overflow-hidden flex flex-col pb-6"> <div className="relative overflow-hidden flex flex-col pb-6">
<div className="absolute left-[18px] top-0 h-full w-0.5 bg-gradient-to-t from-zinc-800 to-zinc-600" /> <div className="absolute left-[18px] top-0 h-full w-0.5 bg-gradient-to-t from-zinc-800 to-zinc-600" />
{isFetching || status === "loading" ? ( {status === "loading" ? (
<NoteSkeleton /> <NoteSkeleton />
) : ( ) : (
<> <>

View File

@@ -14,7 +14,7 @@ export function NoteReplyForm({ id }: { id: string }) {
const [value, setValue] = useState(""); const [value, setValue] = useState("");
const submitEvent = () => { const submit = () => {
const tags = [["e", id]]; const tags = [["e", id]];
// publish event // publish event
@@ -28,7 +28,7 @@ export function NoteReplyForm({ id }: { id: string }) {
<div className="flex flex-col"> <div className="flex flex-col">
<div className="relative w-full flex-1 overflow-hidden"> <div className="relative w-full flex-1 overflow-hidden">
<textarea <textarea
name="content" value={value}
onChange={(e) => setValue(e.target.value)} onChange={(e) => setValue(e.target.value)}
placeholder="Reply to this thread..." placeholder="Reply to this thread..."
className="relative h-20 w-full resize-none rounded-md px-5 py-3 text-base bg-transparent !outline-none placeholder:text-zinc-400 dark:text-zinc-100 dark:placeholder:text-zinc-500" className="relative h-20 w-full resize-none rounded-md px-5 py-3 text-base bg-transparent !outline-none placeholder:text-zinc-400 dark:text-zinc-100 dark:placeholder:text-zinc-500"
@@ -62,7 +62,7 @@ export function NoteReplyForm({ id }: { id: string }) {
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button
onClick={() => submitEvent()} onClick={() => submit()}
disabled={value.length === 0 ? true : false} disabled={value.length === 0 ? true : false}
preset="publish" preset="publish"
> >

View File

@@ -12,7 +12,7 @@ export function Reply({ data }: { data: any }) {
<User pubkey={data.pubkey} time={data.created_at} /> <User pubkey={data.pubkey} time={data.created_at} />
<div className="-mt-[20px] pl-[50px]"> <div className="-mt-[20px] pl-[50px]">
<Kind1 content={content} /> <Kind1 content={content} />
<NoteMetadata id={data.id} eventPubkey={data.pubkey} /> <NoteMetadata id={data.event_id} eventPubkey={data.pubkey} />
</div> </div>
</div> </div>
</div> </div>

View File

@@ -1,11 +1,10 @@
import { getReplies } from "@libs/storage"; import { getReplies } from "@libs/storage";
import { NDKEvent } from "@nostr-dev-kit/ndk"; import { NDKEvent } from "@nostr-dev-kit/ndk";
import { EmptyIcon } from "@shared/icons";
import { Reply } from "@shared/notes/replies/item"; import { Reply } from "@shared/notes/replies/item";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
export function RepliesList({ parent_id }: { parent_id: string }) { export function RepliesList({ parent_id }: { parent_id: string }) {
const { data } = useQuery(["replies", parent_id], async () => { const { status, data } = useQuery(["replies", parent_id], async () => {
return await getReplies(parent_id); return await getReplies(parent_id);
}); });
@@ -15,7 +14,7 @@ export function RepliesList({ parent_id }: { parent_id: string }) {
<h5 className="text-lg font-semibold text-zinc-300">Replies</h5> <h5 className="text-lg font-semibold text-zinc-300">Replies</h5>
</div> </div>
<div className="flex flex-col"> <div className="flex flex-col">
{!data ? ( {status === "loading" ? (
<div className="flex gap-2 px-3 py-4"> <div className="flex gap-2 px-3 py-4">
<div className="relative h-9 w-9 shrink animate-pulse rounded-md bg-zinc-800" /> <div className="relative h-9 w-9 shrink animate-pulse rounded-md bg-zinc-800" />
<div className="flex w-full flex-1 flex-col justify-center gap-1"> <div className="flex w-full flex-1 flex-col justify-center gap-1">

View File

@@ -12,12 +12,12 @@ export function Repost({
currentBlock, currentBlock,
}: { event: LumeEvent; currentBlock?: number }) { }: { event: LumeEvent; currentBlock?: number }) {
const repostID = getRepostID(event.tags); const repostID = getRepostID(event.tags);
const { status, data, isFetching } = useEvent(repostID); const { status, data } = useEvent(repostID);
return ( return (
<div className="relative flex flex-col mt-12"> <div className="relative flex flex-col mt-12">
<div className="absolute left-[18px] -top-10 h-[50px] w-0.5 bg-gradient-to-t from-zinc-800 to-zinc-600" /> <div className="absolute left-[18px] -top-10 h-[50px] w-0.5 bg-gradient-to-t from-zinc-800 to-zinc-600" />
{isFetching || status === "loading" ? ( {status === "loading" ? (
<NoteSkeleton /> <NoteSkeleton />
) : ( ) : (
<> <>

13
src/stores/note.tsx Normal file
View File

@@ -0,0 +1,13 @@
import { create } from "zustand";
interface NoteState {
hasNewNote: boolean;
toggleHasNewNote: (by: boolean) => void;
}
export const useNote = create<NoteState>((set) => ({
hasNewNote: false,
toggleHasNewNote: (status: boolean) => {
set({ hasNewNote: status });
},
}));