This commit is contained in:
Ren Amamiya 2023-06-25 20:36:19 +07:00
parent fe25dbaed0
commit 6af0b453e3
25 changed files with 183 additions and 114 deletions

View File

@ -6,5 +6,6 @@ CREATE TABLE
kind INTEGER NOT NULL,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (account_id) REFERENCES accounts (id)
);

View File

@ -18,8 +18,6 @@ import { TrendingScreen } from "@app/trending";
import { AppLayout } from "@shared/appLayout";
import { AuthLayout } from "@shared/authLayout";
import { Protected } from "@shared/protected";
import { RelayProvider } from "@shared/relayProvider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RouterProvider, createBrowserRouter } from "react-router-dom";
const router = createBrowserRouter([
@ -74,18 +72,12 @@ const router = createBrowserRouter([
},
]);
const queryClient = new QueryClient();
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<RelayProvider>
<RouterProvider
router={router}
fallbackElement={<p>Loading..</p>}
future={{ v7_startTransition: true }}
/>
</RelayProvider>
</QueryClientProvider>
<RouterProvider
router={router}
fallbackElement={<p>Loading..</p>}
future={{ v7_startTransition: true }}
/>
);
}

View File

@ -1,6 +1,6 @@
import { createAccount, createBlock } from "@libs/storage";
import { Button } from "@shared/button";
import { EyeOffIcon, EyeOnIcon } from "@shared/icons";
import { EyeOffIcon, EyeOnIcon, LoaderIcon } from "@shared/icons";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { generatePrivateKey, getPublicKey, nip19 } from "nostr-tools";
import { useMemo, useState } from "react";
@ -11,6 +11,7 @@ export function CreateStep1Screen() {
const queryClient = useQueryClient();
const [type, setType] = useState("password");
const [loading, setLoading] = useState(false);
const privkey = useMemo(() => generatePrivateKey(), []);
const pubkey = getPublicKey(privkey);
@ -27,21 +28,17 @@ export function CreateStep1Screen() {
};
const account = useMutation({
mutationFn: (data: any) =>
createAccount(data.npub, data.pubkey, data.privkey, null, 1),
onSuccess: () => {
createBlock(
0,
"Preserve your freedom",
"https://void.cat/d/949GNg7ZjSLHm2eTR3jZqv",
);
queryClient.invalidateQueries({ queryKey: ["currentAccount"] });
// redirect to next step
navigate("/auth/create/step-2", { replace: true });
mutationFn: (data: any) => {
return createAccount(data.npub, data.pubkey, data.privkey, null, 1);
},
onSuccess: (data: any) => {
queryClient.setQueryData(["currentAccount"], data);
},
});
const submit = async () => {
const submit = () => {
setLoading(true);
account.mutate({
npub,
pubkey,
@ -49,6 +46,9 @@ export function CreateStep1Screen() {
follows: null,
is_active: 1,
});
// redirect to next step
setTimeout(() => navigate("/auth/create/step-2", { replace: true }), 1200);
};
return (
@ -102,7 +102,11 @@ export function CreateStep1Screen() {
</div>
</div>
<Button preset="large" onClick={() => submit()}>
Continue
{loading ? (
<LoaderIcon className="h-4 w-4 animate-spin text-black dark:text-zinc-100" />
) : (
"Continue →"
)}
</Button>
</div>
</div>

View File

@ -127,8 +127,9 @@ export function CreateStep4Screen() {
};
const update = useMutation({
mutationFn: (follows: any) =>
updateAccount("follows", follows, account.pubkey),
mutationFn: (follows: any) => {
return updateAccount("follows", follows, account.pubkey);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["currentAccount"] });
},

View File

@ -2,6 +2,7 @@ import { createAccount, createBlock } from "@libs/storage";
import { LoaderIcon } from "@shared/icons";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { getPublicKey, nip19 } from "nostr-tools";
import { useState } from "react";
import { Resolver, useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
@ -27,18 +28,14 @@ export function ImportStep1Screen() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [loading, setLoading] = useState(false);
const account = useMutation({
mutationFn: (data: any) =>
createAccount(data.npub, data.pubkey, data.privkey, null, 1),
onSuccess: () => {
createBlock(
0,
"Preserve your freedom",
"https://void.cat/d/949GNg7ZjSLHm2eTR3jZqv",
);
queryClient.invalidateQueries({ queryKey: ["currentAccount"] });
// redirect to next step
navigate("/auth/import/step-2", { replace: true });
mutationFn: (data: any) => {
return createAccount(data.npub, data.pubkey, data.privkey, null, 1);
},
onSuccess: (data: any) => {
queryClient.setQueryData(["currentAccount"], data);
},
});
@ -46,13 +43,14 @@ export function ImportStep1Screen() {
register,
setError,
handleSubmit,
formState: { errors, isDirty, isValid, isSubmitting },
formState: { errors, isDirty, isValid },
} = useForm<FormValues>({ resolver });
const onSubmit = async (data: any) => {
try {
let privkey = data["key"];
setLoading(true);
let privkey = data["key"];
if (privkey.substring(0, 4) === "nsec") {
privkey = nip19.decode(privkey).data;
}
@ -69,6 +67,12 @@ export function ImportStep1Screen() {
follows: null,
is_active: 1,
});
// redirect to step 2
setTimeout(
() => navigate("/auth/import/step-2", { replace: true }),
1200,
);
}
} catch (error) {
setError("key", {
@ -102,7 +106,7 @@ export function ImportStep1Screen() {
disabled={!isDirty || !isValid}
className="inline-flex items-center justify-center h-11 w-full bg-fuchsia-500 rounded-md font-medium text-zinc-100 hover:bg-fuchsia-600"
>
{isSubmitting ? (
{loading ? (
<LoaderIcon className="h-4 w-4 animate-spin text-black dark:text-zinc-100" />
) : (
"Continue →"

View File

@ -18,12 +18,11 @@ export function ImportStep2Screen() {
const { status, account } = useAccount();
const update = useMutation({
mutationFn: (follows: any) =>
updateAccount("follows", follows, account.pubkey),
mutationFn: (follows: any) => {
return updateAccount("follows", follows, account.pubkey);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["currentAccount"] });
// redirect to next step
navigate("/auth/onboarding", { replace: true });
},
});
@ -40,11 +39,16 @@ export function ImportStep2Screen() {
// update
update.mutate(followsList);
// redirect to next step
setTimeout(() => navigate("/auth/onboarding", { replace: true }), 1200);
} catch {
console.log("error");
}
};
console.log(account);
return (
<div className="mx-auto w-full max-w-md">
<div className="mb-8 text-center">

View File

@ -41,15 +41,16 @@ export function ChannelCreateModal() {
} = useForm();
const addChannel = useMutation({
mutationFn: (event: any) =>
createChannel(
mutationFn: (event: any) => {
return createChannel(
event.id,
event.pubkey,
event.name,
event.picture,
event.about,
event.created_at,
),
);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["channels"] });
},

View File

@ -26,6 +26,7 @@ export function NewMessageModal() {
const openChat = (npub: string) => {
const pubkey = nip19.decode(npub).data;
closeModal();
navigate(`/app/chat/${pubkey}`);
};
@ -110,10 +111,10 @@ export function NewMessageModal() {
className="w-9 h-9 shrink-0 object-cover rounded"
/>
<div className="inline-flex flex-col gap-1">
<h3 className="leading-none font-medium text-zinc-100">
<h3 className="leading-none max-w-[15rem] font-medium text-zinc-100">
{pleb.display_name || pleb.name}
</h3>
<span className="leading-none text-sm text-zinc-400">
<span className="leading-none max-w-[10rem] text-sm text-zinc-400">
{pleb.nip05 ||
pleb.npub.substring(0, 16).concat("...")}
</span>

View File

@ -2,14 +2,12 @@ import { Dialog, Transition } from "@headlessui/react";
import { createBlock } from "@libs/storage";
import { CancelIcon } from "@shared/icons";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useAccount } from "@utils/hooks/useAccount";
import { nip19 } from "nostr-tools";
import { Fragment, useState } from "react";
import { useForm } from "react-hook-form";
export function AddFeedBlock({ parentState }: { parentState: any }) {
const queryClient = useQueryClient();
const { account } = useAccount();
const [loading, setLoading] = useState(false);
const [isOpen, setIsOpen] = useState(true);
@ -22,7 +20,9 @@ export function AddFeedBlock({ parentState }: { parentState: any }) {
};
const block = useMutation({
mutationFn: (data: any) => createBlock(data.kind, data.title, data.content),
mutationFn: (data: any) => {
return createBlock(data.kind, data.title, data.content);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["blocks"] });
},

View File

@ -90,7 +90,9 @@ export function AddImageBlock({ parentState }: { parentState: any }) {
};
const block = useMutation({
mutationFn: (data: any) => createBlock(data.kind, data.title, data.content),
mutationFn: (data: any) => {
return createBlock(data.kind, data.title, data.content);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["blocks"] });
},

View File

@ -64,7 +64,9 @@ export function FeedBlock({ params }: { params: any }) {
}, [notes.length, fetchNextPage, rowVirtualizer.getVirtualItems()]);
const block = useMutation({
mutationFn: (id: string) => removeBlock(id),
mutationFn: (id: string) => {
return removeBlock(id);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["blocks"] });
},

View File

@ -1,4 +1,5 @@
import { removeBlock } from "@libs/storage";
import { CancelIcon } from "@shared/icons";
import { Image } from "@shared/image";
import { TitleBar } from "@shared/titleBar";
import { DEFAULT_AVATAR } from "@stores/constants";
@ -8,7 +9,9 @@ export function ImageBlock({ params }: { params: any }) {
const queryClient = useQueryClient();
const block = useMutation({
mutationFn: (id: string) => removeBlock(id),
mutationFn: (id: string) => {
return removeBlock(id);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["blocks"] });
},
@ -16,15 +19,24 @@ export function ImageBlock({ params }: { params: any }) {
return (
<div className="shrink-0 w-[350px] h-full flex flex-col justify-between border-r border-zinc-900">
<div className="flex-1 w-full h-full overflow-hidden p-3">
<div className="w-full h-full">
<Image
src={params.content}
fallback={DEFAULT_AVATAR}
alt={params.title}
className="w-full h-full object-cover rounded-xl border-t border-zinc-800/50"
/>
<div className="relative flex-1 w-full h-full p-3 overflow-hidden">
<div className="absolute top-3 left-0 w-full h-16 px-3">
<div className="h-16 rounded-t-xl overflow-hidden flex items-center justify-end px-5">
<button
type="button"
onClick={() => block.mutate(params.id)}
className="inline-flex h-7 w-7 rounded-md items-center justify-center bg-white/30 backdrop-blur-lg"
>
<CancelIcon width={16} height={16} className="text-white" />
</button>
</div>
</div>
<Image
src={params.content}
fallback={DEFAULT_AVATAR}
alt={params.title}
className="w-full h-full object-cover rounded-xl border-t border-zinc-800/50"
/>
</div>
</div>
);

View File

@ -21,7 +21,9 @@ export function ThreadBlock({ params }: { params: any }) {
);
const block = useMutation({
mutationFn: (id: string) => removeBlock(id),
mutationFn: (id: string) => {
return removeBlock(id);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["blocks"] });
},

View File

@ -345,7 +345,7 @@ export async function getLinkPreview(text: string) {
const fetchUrl = text;
const options: FetchOptions = {
method: "GET",
timeout: 30,
timeout: 5,
responseType: ResponseType.Text,
};

View File

@ -45,10 +45,19 @@ export async function createAccount(
is_active?: number,
) {
const db = await connect();
return await db.execute(
const res = await db.execute(
"INSERT OR IGNORE INTO accounts (npub, pubkey, privkey, follows, is_active) VALUES (?, ?, ?, ?, ?);",
[npub, pubkey, privkey, follows || "", is_active || 0],
);
if (res) {
await createBlock(
0,
"Preserve your freedom",
"https://void.cat/d/949GNg7ZjSLHm2eTR3jZqv",
);
}
const getAccount = await getActiveAccount();
return getAccount;
}
// update account
@ -408,7 +417,7 @@ export async function getBlocks() {
const db = await connect();
const activeAccount = await getActiveAccount();
const result: any = await db.select(
`SELECT * FROM blocks WHERE account_id <= "${activeAccount.id}";`,
`SELECT * FROM blocks WHERE account_id = "${activeAccount.id}" ORDER BY created_at DESC;`,
);
return result;
}

View File

@ -1,6 +1,23 @@
import App from "./app";
import { RelayProvider } from "@shared/relayProvider";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRoot } from "react-dom/client";
const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 24,
},
},
});
const container = document.getElementById("root");
const root = createRoot(container);
root.render(<App />);
root.render(
<QueryClientProvider client={queryClient}>
<RelayProvider>
<App />
</RelayProvider>
</QueryClientProvider>,
);

View File

@ -16,7 +16,9 @@ export const MentionNote = memo(function MentionNote({ id }: { id: string }) {
const queryClient = useQueryClient();
const block = useMutation({
mutationFn: (data: any) => createBlock(data.kind, data.title, data.content),
mutationFn: (data: any) => {
return createBlock(data.kind, data.title, data.content);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["blocks"] });
},

View File

@ -10,7 +10,9 @@ export function NoteReply({
const queryClient = useQueryClient();
const block = useMutation({
mutationFn: (data: any) => createBlock(data.kind, data.title, data.content),
mutationFn: (data: any) => {
return createBlock(data.kind, data.title, data.content);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["blocks"] });
},

View File

@ -71,7 +71,7 @@ export function Note({ event, block }: Note) {
time={event.created_at}
repost={isRepost}
/>
<div className="-mt-5 pl-[49px]">
<div className="z-10 relative -mt-6 pl-[49px]">
{renderContent}
{!isRepost && (
<NoteMetadata

View File

@ -11,9 +11,6 @@ export function NoteParent({
}: { id: string; currentBlock: number }) {
const { status, data, isFetching } = useEvent(id);
const kind1 = data?.kind === 1 ? data.content : null;
const kind1063 = data?.kind === 1063 ? data.tags : null;
return (
<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" />
@ -22,10 +19,10 @@ export function NoteParent({
) : (
<>
<User pubkey={data.pubkey} time={data.created_at} />
<div className="-mt-5 pl-[49px]">
{kind1 && <Kind1 content={kind1} />}
{kind1063 && <Kind1063 metadata={kind1063} />}
{!kind1 && !kind1063 && (
<div className="z-10 relative -mt-6 pl-[49px]">
{data.kind === 1 && <Kind1 content={data.content} />}
{data.kind === 1063 && <Kind1063 metadata={data.tags} />}
{data.kind !== 1 && data.kind !== 1063 && (
<div className="flex flex-col gap-2">
<div className="px-2 py-2 inline-flex flex-col gap-1 bg-zinc-800 rounded-md">
<span className="text-zinc-500 text-sm font-medium leading-none">

View File

@ -3,11 +3,11 @@ import { useOpenGraph } from "@utils/hooks/useOpenGraph";
export function LinkPreview({ urls }: { urls: string[] }) {
const domain = new URL(urls[0]);
const { status, data, isFetching } = useOpenGraph(urls[0]);
const { status, data, error } = useOpenGraph(urls[0]);
return (
<div className="mt-3 max-w-[420px] overflow-hidden rounded-lg bg-zinc-800">
{isFetching || status === "loading" ? (
{status === "loading" ? (
<div className="flex flex-col">
<div className="w-full h-44 bg-zinc-700 animate-pulse" />
<div className="flex flex-col gap-2 px-3 py-3">
@ -25,25 +25,35 @@ export function LinkPreview({ urls }: { urls: string[] }) {
target="_blank"
rel="noreferrer"
>
<Image
src={data.images[0]}
fallback="https://void.cat/d/XTmrMkpid8DGLjv1AzdvcW"
alt={urls[0]}
className="w-full h-44 object-cover rounded-t-lg"
/>
<div className="flex flex-col gap-2 px-3 py-3">
<h5 className="leading-none font-medium text-zinc-200 line-clamp-1">
{data.title}
</h5>
{data.description && (
{error ? (
<div className="px-3 py-3">
<p className="text-sm text-zinc-400 break-all line-clamp-3">
{data.description}
Can't fetch open graph, click to open webpage
</p>
)}
<span className="mt-2.5 leading-none text-sm text-zinc-500">
{domain.hostname}
</span>
</div>
</div>
) : (
<>
<Image
src={data.images[0]}
fallback="https://void.cat/d/XTmrMkpid8DGLjv1AzdvcW"
alt={urls[0]}
className="w-full h-44 object-cover rounded-t-lg"
/>
<div className="flex flex-col gap-2 px-3 py-3">
<h5 className="leading-none font-medium text-zinc-200 line-clamp-1">
{data.title}
</h5>
{data.description && (
<p className="text-sm text-zinc-400 break-all line-clamp-3">
{data.description}
</p>
)}
<span className="mt-2.5 leading-none text-sm text-zinc-500">
{domain.hostname}
</span>
</div>
</>
)}
</a>
)}
</div>

View File

@ -14,9 +14,6 @@ export function Repost({
const repostID = getRepostID(event.tags);
const { status, data, isFetching } = useEvent(repostID);
const kind1 = data?.kind === 1 ? data.content : null;
const kind1063 = data?.kind === 1063 ? data.tags : null;
return (
<div className="relative overflow-hidden flex flex-col mt-12">
{isFetching || status === "loading" ? (
@ -24,10 +21,10 @@ export function Repost({
) : (
<>
<User pubkey={data.pubkey} time={data.created_at} />
<div className="-mt-5 pl-[49px]">
{kind1 && <Kind1 content={kind1} />}
{kind1063 && <Kind1063 metadata={kind1063} />}
{!kind1 && !kind1063 && (
<div className="z-10 relative -mt-6 pl-[49px]">
{data.kind === 1 && <Kind1 content={data.content} />}
{data.kind === 1063 && <Kind1063 metadata={data.tags} />}
{data.kind !== 1 && data.kind !== 1063 && (
<div className="flex flex-col gap-2">
<div className="px-2 py-2 inline-flex flex-col gap-1 bg-zinc-800 rounded-md">
<span className="text-zinc-500 text-sm font-medium leading-none">

View File

@ -5,8 +5,7 @@ import { createContext } from "react";
export const RelayContext = createContext<NDK>(null);
const ndk = new NDK({ explicitRelayUrls: FULL_RELAYS });
await ndk.connect();
const ndk = await initNDK(FULL_RELAYS);
export function RelayProvider({ children }: { children: React.ReactNode }) {
return <RelayContext.Provider value={ndk}>{children}</RelayContext.Provider>;

View File

@ -2,10 +2,16 @@ import { getActiveAccount } from "@libs/storage";
import { useQuery } from "@tanstack/react-query";
export function useAccount() {
const { status, data: account } = useQuery(["currentAccount"], async () => {
const res = await getActiveAccount();
return res;
});
const { status, data: account } = useQuery(
["currentAccount"],
async () => await getActiveAccount(),
{
staleTime: Infinity,
refetchOnMount: true,
refetchOnWindowFocus: false,
refetchOnReconnect: true,
},
);
return { status, account };
}

View File

@ -5,7 +5,11 @@ export function useOpenGraph(url: string) {
const { status, data, error, isFetching } = useQuery(
["preview", url],
async () => {
return await getLinkPreview(url);
const res = await getLinkPreview(url);
if (!res) {
throw new Error("Can' fetch");
}
return res;
},
{
refetchOnWindowFocus: false,