add follow/unfollow function

This commit is contained in:
Ren Amamiya
2023-06-27 16:12:21 +07:00
parent 6abff45678
commit a29ef03198
9 changed files with 85 additions and 69 deletions

View File

@@ -15,6 +15,7 @@ import { ErrorScreen } from "@app/error";
import { Root } from "@app/root";
import { SpaceScreen } from "@app/space";
import { TrendingScreen } from "@app/trending";
import { UserScreen } from "@app/user";
import { AppLayout } from "@shared/appLayout";
import { AuthLayout } from "@shared/authLayout";
import { Protected } from "@shared/protected";
@@ -66,6 +67,7 @@ const router = createBrowserRouter([
children: [
{ path: "space", element: <SpaceScreen /> },
{ path: "trending", element: <TrendingScreen /> },
{ path: "user/:pubkey", element: <UserScreen /> },
{ path: "chat/:pubkey", element: <ChatScreen /> },
{ path: "channel/:id", element: <ChannelScreen /> },
],

View File

@@ -55,7 +55,7 @@ export function ThreadBlock({ params }: { params: any }) {
</div>
</div>
<div className="mt-3 bg-zinc-900 rounded-md">
<NoteReplyForm id={params.content} />
<NoteReplyForm rootID={params.content} />
</div>
</div>
)}

View File

@@ -4,8 +4,11 @@ import { TitleBar } from "@shared/titleBar";
import { useQuery } from "@tanstack/react-query";
export function TrendingNotes() {
const { status, data } = useQuery(["trending-notes"], async () => {
const { status, data, error } = useQuery(["trending-notes"], async () => {
const res = await fetch("https://api.nostr.band/v0/trending/notes");
if (!res.ok) {
throw new Error("Error");
}
return res.json();
});
@@ -13,6 +16,7 @@ export function TrendingNotes() {
<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">
{error && <p>Failed to fetch</p>}
{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">

View File

@@ -4,8 +4,11 @@ import { TitleBar } from "@shared/titleBar";
import { useQuery } from "@tanstack/react-query";
export function TrendingProfiles() {
const { status, data } = useQuery(["trending-profiles"], async () => {
const { status, data, error } = useQuery(["trending-profiles"], async () => {
const res = await fetch("https://api.nostr.band/v0/trending/profiles");
if (!res.ok) {
throw new Error("Error");
}
return res.json();
});
@@ -13,6 +16,7 @@ export function TrendingProfiles() {
<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">
{error && <p>Failed to fetch</p>}
{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">

View File

@@ -1,57 +1,50 @@
import { NDKEvent, NDKPrivateKeySigner } from "@nostr-dev-kit/ndk";
import { usePublish } from "@libs/ndk";
import { Image } from "@shared/image";
import { RelayContext } from "@shared/relayProvider";
import { DEFAULT_AVATAR } from "@stores/constants";
import { useQuery } from "@tanstack/react-query";
import { dateToUnix } from "@utils/date";
import { useAccount } from "@utils/hooks/useAccount";
import { usePageContext } from "@utils/hooks/usePageContext";
import { useFollows } from "@utils/hooks/useFollows";
import { useProfile } from "@utils/hooks/useProfile";
import { compactNumber } from "@utils/number";
import { shortenKey } from "@utils/shortenKey";
import { useContext } from "react";
import { Link } from "react-router-dom";
import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
export function UserScreen() {
const ndk = useContext(RelayContext);
const pageContext = usePageContext();
const searchParams: any = pageContext.urlParsed.search;
const pubkey = searchParams.pubkey || "";
const publish = usePublish();
const [followed, setFollowed] = useState(false);
const { account } = useAccount();
const { pubkey } = useParams();
const { user } = useProfile(pubkey);
const { data: userStats, error } = useQuery(["user", pubkey], async () => {
const { status: followsStatus, follows } = useFollows();
const {
status: userStatsStatus,
data: userStats,
error,
} = useQuery(["user", pubkey], async () => {
const res = await fetch(
`https://api.nostr.band/v0/stats/profile/${pubkey}`,
);
if (res.ok) {
return await res.json();
if (!res.ok) {
throw new Error("Error");
}
return await res.json();
});
const follows = account ? JSON.parse(account.follows) : [];
const follow = (pubkey: string) => {
try {
const followsAsSet = new Set(follows);
followsAsSet.add(pubkey);
const signer = new NDKPrivateKeySigner(account.privkey);
ndk.signer = signer;
const tags = [];
followsAsSet.forEach((item) => {
tags.push(["p", item]);
});
const event = new NDKEvent(ndk);
event.content = "";
event.created_at = dateToUnix();
event.pubkey = pubkey;
event.kind = 3;
event.tags = tags;
// publish event
event.publish();
publish({ content: "", kind: 3, tags: tags });
// update state
setFollowed(true);
} catch (error) {
console.log(error);
}
@@ -62,27 +55,29 @@ export function UserScreen() {
const followsAsSet = new Set(follows);
followsAsSet.delete(pubkey);
const signer = new NDKPrivateKeySigner(account.privkey);
ndk.signer = signer;
const tags = [];
followsAsSet.forEach((item) => {
tags.push(["p", item]);
});
const event = new NDKEvent(ndk);
event.content = "";
event.created_at = dateToUnix();
event.pubkey = pubkey;
event.kind = 3;
event.tags = tags;
// publish event
event.publish();
publish({ content: "", kind: 3, tags: tags });
// update state
setFollowed(false);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
if (followsStatus === "success" && follows) {
if (follows.includes(pubkey)) {
setFollowed(true);
}
}
}, [followsStatus]);
return (
<div className="h-full w-full">
<div
@@ -119,7 +114,7 @@ export function UserScreen() {
</div>
<div className="mt-8">
{error && <p>Failed to fetch user stats</p>}
{!userStats ? (
{userStatsStatus === "loading" ? (
<p>Loading...</p>
) : (
<div className="w-full flex items-center gap-10">
@@ -166,7 +161,14 @@ export function UserScreen() {
</div>
)}
<div className="mt-6 flex items-center gap-2">
{follows.includes(pubkey) ? (
{followsStatus === "loading" ? (
<button
type="button"
className="inline-flex w-44 h-10 items-center justify-center rounded-md bg-zinc-900 hover:bg-fuchsia-500 text-sm font-medium"
>
Loading...
</button>
) : followed ? (
<button
type="button"
onClick={() => unfollow(pubkey)}

View File

@@ -1,12 +1,12 @@
import { usePublish } from "@libs/ndk";
import { Button } from "@shared/button";
import { Image } from "@shared/image";
import { DEFAULT_AVATAR } from "@stores/constants";
import { DEFAULT_AVATAR, FULL_RELAYS } from "@stores/constants";
import { useAccount } from "@utils/hooks/useAccount";
import { useProfile } from "@utils/hooks/useProfile";
import { useState } from "react";
export function NoteReplyForm({ id }: { id: string }) {
export function NoteReplyForm({ rootID }: { rootID: string }) {
const publish = usePublish();
const { account } = useAccount();
@@ -15,7 +15,7 @@ export function NoteReplyForm({ id }: { id: string }) {
const [value, setValue] = useState("");
const submit = () => {
const tags = [["e", id]];
const tags = [["e", rootID, FULL_RELAYS[0], "root"]];
// publish event
publish({ content: value, kind: 1, tags });

View File

@@ -33,7 +33,7 @@ export function User({
}`}
>
<Popover.Button
className={`${avatarWidth} ${avatarHeight} relative z-10 bg-zinc-900 shrink-0 overflow-hidden`}
className={`${avatarWidth} ${avatarHeight} relative z-50 bg-zinc-900 shrink-0 overflow-hidden`}
>
<Image
src={user?.image}

View File

@@ -0,0 +1,27 @@
import { useAccount } from "./useAccount";
import { RelayContext } from "@shared/relayProvider";
import { useQuery } from "@tanstack/react-query";
import { nip02ToArray } from "@utils/transform";
import { useContext } from "react";
export function useFollows() {
const ndk = useContext(RelayContext);
const { account } = useAccount();
const { status, data: follows } = useQuery(
["follows", account.pubkey],
async () => {
const res = await ndk.fetchEvents({
kinds: [3],
authors: [account.pubkey],
});
const latest = [...res].slice(-1)[0];
const list = nip02ToArray(latest.tags);
return list;
},
{
enabled: account ? true : false,
},
);
return { status, follows };
}

View File

@@ -1,23 +0,0 @@
// `usePageContext` allows us to access `pageContext` in any React component.
// See https://vite-plugin-ssr.com/pageContext-anywhere
import type { PageContext } from "@renderer/types";
import { createContext, useContext } from "react";
const Context = createContext<PageContext>(undefined as any);
export function PageContextProvider({
pageContext,
children,
}: {
pageContext: PageContext;
children: React.ReactNode;
}) {
return <Context.Provider value={pageContext}>{children}</Context.Provider>;
}
// eslint-disable-next-line react-refresh/only-export-components
export function usePageContext() {
const pageContext = useContext(Context);
return pageContext;
}