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"
>
{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" />

View File

@@ -6,54 +6,52 @@ import { NavLink } from "react-router-dom";
import { twMerge } from "tailwind-merge";
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 (
<>
{status === "loading" && isFetching ? (
<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>
<NavLink
to={`/app/chat/${data.sender_pubkey}`}
preventScrollReset={true}
className={({ isActive }) =>
twMerge(
"inline-flex h-9 items-center gap-2.5 rounded-md px-2.5",
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>
) : (
<NavLink
to={`/app/chat/${data.sender_pubkey}`}
preventScrollReset={true}
className={({ isActive }) =>
twMerge(
"inline-flex h-9 items-center gap-2.5 rounded-md px-2.5",
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 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>
)}
</>
<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 (
<div className="flex flex-col">
<NewMessageModal />
@@ -37,24 +52,11 @@ export function ChatsList() {
<div className="h-3 w-full rounded-sm animate-pulse bg-zinc-800" />
</div>
)}
{status === "loading" ? (
<>
<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>
</>
) : (
chats.map((item) => {
if (account.pubkey !== item.sender_pubkey) {
return <ChatsListItem key={item.sender_pubkey} data={item} />;
}
})
)}
{chats.map((item) => {
if (account.pubkey !== item.sender_pubkey) {
return <ChatsListItem key={item.sender_pubkey} data={item} />;
}
})}
{isFetching && (
<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" />

View File

@@ -6,44 +6,44 @@ import { NavLink } from "react-router-dom";
import { twMerge } from "tailwind-merge";
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 (
<>
{status === "loading" && isFetching ? (
<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>
) : (
<NavLink
to={`/app/chat/${data.pubkey}`}
preventScrollReset={true}
className={({ isActive }) =>
twMerge(
"inline-flex h-9 items-center gap-2.5 rounded-md px-2.5",
isActive ? "bg-zinc-900/50 text-zinc-100" : "",
)
}
>
<div className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded border-t border-zinc-800/50 bg-zinc-900">
<Image
src={user?.image}
fallback={DEFAULT_AVATAR}
alt={data.pubkey}
className="h-6 w-6 rounded bg-white object-cover"
/>
</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>
)}
</>
<NavLink
to={`/app/chat/${data.pubkey}`}
preventScrollReset={true}
className={({ isActive }) =>
twMerge(
"inline-flex h-9 items-center gap-2.5 rounded-md px-2.5",
isActive ? "bg-zinc-900/50 text-zinc-100" : "",
)
}
>
<div className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded border-t border-zinc-800/50 bg-zinc-900">
<Image
src={user?.image}
fallback={DEFAULT_AVATAR}
alt={data.pubkey}
className="h-6 w-6 rounded bg-white object-cover"
/>
</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() {
try {
const follows = JSON.parse(account.follows);
let queryNoteSince: number;
let since: number;
if (totalNotes === 0) {
queryNoteSince = dateToUnix(getHourAgo(48, now.current));
if (totalNotes === 0 || lastLogin === 0) {
since = dateToUnix(getHourAgo(48, now.current));
} else {
if (lastLogin > 0) {
queryNoteSince = lastLogin;
} else {
queryNoteSince = dateToUnix(getHourAgo(48, now.current));
}
since = lastLogin;
}
const filter: NDKFilter = {
kinds: [1, 6],
authors: follows,
since: queryNoteSince,
since: since,
};
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 }) {
const queryClient = useQueryClient();
const {
status,
data,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
}: any = useInfiniteQuery({
queryKey: ["newsfeed", params.content],
queryFn: async ({ pageParam = 0 }) => {
return await getNotesByAuthors(
params.content,
TIME,
ITEM_PER_PAGE,
pageParam,
);
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
const { status, data, fetchNextPage, hasNextPage, isFetchingNextPage }: any =
useInfiniteQuery({
queryKey: ["newsfeed", params.content],
queryFn: async ({ pageParam = 0 }) => {
return await getNotesByAuthors(
params.content,
TIME,
ITEM_PER_PAGE,
pageParam,
);
},
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
const notes = data ? data.pages.flatMap((d: { data: any }) => d.data) : [];
const parentRef = useRef();
@@ -119,7 +113,7 @@ export function FeedBlock({ params }: { params: any }) {
</div>
</div>
)}
{isFetching && !isFetchingNextPage && (
{isFetchingNextPage && (
<div className="px-3 py-1.5">
<div className="rounded-xl border-t border-zinc-800/50 bg-zinc-900 px-3 py-3">
<NoteSkeleton />

View File

@@ -1,30 +1,31 @@
import { createNote, getNotes } from "@libs/storage";
import { NDKEvent, NDKFilter, NDKSubscription } from "@nostr-dev-kit/ndk";
import { useNewsfeed } from "@app/space/hooks/useNewsfeed";
import { getNotes } from "@libs/storage";
import { Note } from "@shared/notes/note";
import { NoteSkeleton } from "@shared/notes/skeleton";
import { RelayContext } from "@shared/relayProvider";
import { TitleBar } from "@shared/titleBar";
import { useNote } from "@stores/note";
import { useInfiniteQuery } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { dateToUnix } from "@utils/date";
import { useAccount } from "@utils/hooks/useAccount";
import { useContext, useEffect, useRef } from "react";
import { useEffect, useRef } from "react";
const ITEM_PER_PAGE = 10;
const TIME = Math.floor(Date.now() / 1000);
export function FollowingBlock({ block }: { block: number }) {
const ndk = useContext(RelayContext);
const { account } = useAccount();
// subscribe for live update
useNewsfeed();
const [hasNewNote, toggleHasNewNote] = useNote((state) => [
state.hasNewNote,
state.toggleHasNewNote,
]);
const {
status,
data,
fetchNextPage,
hasNextPage,
isFetching,
isFetchingNextPage,
refetch,
}: any = useInfiniteQuery({
queryKey: ["newsfeed-circle"],
queryFn: async ({ pageParam = 0 }) => {
@@ -61,39 +62,17 @@ export function FollowingBlock({ block }: { block: number }) {
}
}, [notes.length, fetchNextPage, rowVirtualizer.getVirtualItems()]);
useEffect(() => {
const follows = account ? JSON.parse(account.follows) : [];
const filter: NDKFilter = {
kinds: [1, 6],
authors: follows,
since: dateToUnix(),
};
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 refreshFirstPage = () => {
// refetch
refetch({ refetchPage: (page, index) => index === 0 });
// scroll to top
rowVirtualizer.scrollToIndex(1);
// stop notify
toggleHasNewNote(false);
};
const renderItem = (index: string | number) => {
const note = notes[index];
if (!note) return;
return (
<div key={index} data-index={index} ref={rowVirtualizer.measureElement}>
@@ -103,8 +82,19 @@ export function FollowingBlock({ block }: { block: number }) {
};
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" />
{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
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"
@@ -138,7 +128,7 @@ export function FollowingBlock({ block }: { block: number }) {
</div>
</div>
)}
{isFetching && !isFetchingNextPage && (
{isFetchingNextPage && (
<div className="px-3 py-1.5">
<div className="rounded-xl border-t border-zinc-800/50 bg-zinc-900 px-3 py-3">
<NoteSkeleton />

View File

@@ -1,3 +1,4 @@
import { useLiveThread } from "@app/space/hooks/useLiveThread";
import { getNoteByID, removeBlock } from "@libs/storage";
import { Kind1 } from "@shared/notes/contents/kind1";
import { Kind1063 } from "@shared/notes/contents/kind1063";
@@ -11,14 +12,15 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { parser } from "@utils/parser";
export function ThreadBlock({ params }: { params: any }) {
useLiveThread(params.content);
const queryClient = useQueryClient();
const { status, data, isFetching } = useQuery(
["thread", params.content],
async () => {
return await getNoteByID(params.content);
},
);
const { status, data } = useQuery(["thread", params.content], async () => {
const res = await getNoteByID(params.content);
res["content"] = parser(res);
return res;
});
const block = useMutation({
mutationFn: (id: string) => {
@@ -29,13 +31,11 @@ export function ThreadBlock({ params }: { params: any }) {
},
});
const content = data ? parser(data) : null;
return (
<div className="shrink-0 w-[400px] border-r border-zinc-900">
<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">
{status === "loading" || isFetching ? (
{status === "loading" ? (
<div className="px-3 py-1.5">
<div className="rounded-md bg-zinc-900 px-3 py-3 shadow-input shadow-black/20">
<NoteSkeleton />
@@ -46,13 +46,16 @@ export function ThreadBlock({ params }: { params: any }) {
<div className="rounded-md bg-zinc-900 px-5 pt-5">
<User pubkey={data.pubkey} time={data.created_at} />
<div className="mt-3">
{data.kind === 1 && <Kind1 content={content} />}
{data.kind === 1 && <Kind1 content={data.content} />}
{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 className="mt-3 bg-zinc-900 rounded-md">
<NoteReplyForm id={data.id} />
<NoteReplyForm id={params.content} />
</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";
export function Profile({ data }: { data: any }) {
const {
status,
data: userStats,
isFetching,
} = useQuery(["user-stats", data.pubkey], async () => {
const res = await fetch(
`https://api.nostr.band/v0/stats/profile/${data.pubkey}`,
);
return res.json();
});
const { status, data: userStats } = useQuery(
["user-stats", data.pubkey],
async () => {
const res = await fetch(
`https://api.nostr.band/v0/stats/profile/${data.pubkey}`,
);
return res.json();
},
);
const embedProfile = data.profile ? JSON.parse(data.profile.content) : null;
const profile = embedProfile;
@@ -51,7 +50,7 @@ export function Profile({ data }: { data: any }) {
</p>
</div>
<div className="mt-8">
{status === "loading" || isFetching ? (
{status === "loading" ? (
<p>Loading...</p>
) : (
<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";
export function TrendingNotes() {
const { status, data, isFetching } = useQuery(
["trending-notes"],
async () => {
const res = await fetch("https://api.nostr.band/v0/trending/notes");
return res.json();
},
);
const { status, data } = useQuery(["trending-notes"], async () => {
const res = await fetch("https://api.nostr.band/v0/trending/notes");
return res.json();
});
return (
<div className="shrink-0 w-[360px] flex-col flex border-r border-zinc-900">
<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">
{status === "loading" || isFetching ? (
{status === "loading" ? (
<div className="px-3 py-1.5">
<div className="rounded-md bg-zinc-900 px-3 py-3 shadow-input shadow-black/20">
<NoteSkeleton />

View File

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