refactor
This commit is contained in:
@@ -47,17 +47,9 @@ try {
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
async getInboxes(id: string) : Promise<Result<string[], string>> {
|
||||
async getChats(dbOnly: boolean) : Promise<Result<string[], string>> {
|
||||
try {
|
||||
return { status: "ok", data: await TAURI_INVOKE("get_inboxes", { id }) };
|
||||
} catch (e) {
|
||||
if(e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
async getChats() : Promise<Result<string[], string>> {
|
||||
try {
|
||||
return { status: "ok", data: await TAURI_INVOKE("get_chats") };
|
||||
return { status: "ok", data: await TAURI_INVOKE("get_chats", { dbOnly }) };
|
||||
} catch (e) {
|
||||
if(e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
@@ -71,25 +63,17 @@ try {
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
async sendMessage(to: string, message: string, relays: string[]) : Promise<Result<null, string>> {
|
||||
async getInboxes(id: string) : Promise<Result<string[], string>> {
|
||||
try {
|
||||
return { status: "ok", data: await TAURI_INVOKE("send_message", { to, message, relays }) };
|
||||
return { status: "ok", data: await TAURI_INVOKE("get_inboxes", { id }) };
|
||||
} catch (e) {
|
||||
if(e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
async subscribeTo(id: string, relays: string[]) : Promise<Result<null, string>> {
|
||||
async sendMessage(to: string, message: string) : Promise<Result<null, string>> {
|
||||
try {
|
||||
return { status: "ok", data: await TAURI_INVOKE("subscribe_to", { id, relays }) };
|
||||
} catch (e) {
|
||||
if(e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
}
|
||||
},
|
||||
async unsubscribe(id: string) : Promise<Result<null, null>> {
|
||||
try {
|
||||
return { status: "ok", data: await TAURI_INVOKE("unsubscribe", { id }) };
|
||||
return { status: "ok", data: await TAURI_INVOKE("send_message", { to, message }) };
|
||||
} catch (e) {
|
||||
if(e instanceof Error) throw e;
|
||||
else return { status: "error", error: e as any };
|
||||
|
||||
@@ -75,19 +75,7 @@ export function getReceivers(tags: string[][]) {
|
||||
return p;
|
||||
}
|
||||
|
||||
export const useRelays = (id: string) =>
|
||||
useQuery({
|
||||
queryKey: ["relays", id],
|
||||
queryFn: async () => {
|
||||
const res = await commands.getInboxes(id);
|
||||
|
||||
if (res.status === "ok") {
|
||||
return res.data;
|
||||
} else {
|
||||
throw new Error(res.error);
|
||||
}
|
||||
},
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnMount: false,
|
||||
refetchOnReconnect: false,
|
||||
});
|
||||
export function getChatId(pubkey: string, tags: string[][]) {
|
||||
const id = [pubkey, tags.map((tag) => tag[0] === "p" && tag[1])].join("-");
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -55,7 +55,6 @@ export function UserProvider({
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
staleTime: Number.POSITIVE_INFINITY,
|
||||
retry: 2,
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
27
src/main.tsx
27
src/main.tsx
@@ -1,16 +1,28 @@
|
||||
import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client";
|
||||
import { RouterProvider, createRouter } from "@tanstack/react-router";
|
||||
import { type } from "@tauri-apps/plugin-os";
|
||||
import { StrictMode } from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import "./app.css";
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
// Import the generated route tree
|
||||
import { routeTree } from "./routes.gen";
|
||||
|
||||
// Create a new router instance
|
||||
const queryClient = new QueryClient();
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
gcTime: 1000 * 60 * 60 * 24,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const persister = createSyncStoragePersister({
|
||||
storage: window.localStorage,
|
||||
});
|
||||
|
||||
const platform = type();
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
context: {
|
||||
@@ -32,9 +44,12 @@ if (!rootElement.innerHTML) {
|
||||
const root = ReactDOM.createRoot(rootElement);
|
||||
root.render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PersistQueryClientProvider
|
||||
client={queryClient}
|
||||
persistOptions={{ persister }}
|
||||
>
|
||||
<RouterProvider router={router} />
|
||||
</QueryClientProvider>
|
||||
</PersistQueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
import { Route as rootRoute } from './routes/__root'
|
||||
import { Route as IndexImport } from './routes/index'
|
||||
import { Route as AccountChatsIdImport } from './routes/$account.chats.$id'
|
||||
|
||||
// Create Virtual Routes
|
||||
|
||||
@@ -23,7 +24,6 @@ const ImportKeyLazyImport = createFileRoute('/import-key')()
|
||||
const CreateAccountLazyImport = createFileRoute('/create-account')()
|
||||
const AccountChatsLazyImport = createFileRoute('/$account/chats')()
|
||||
const AccountChatsNewLazyImport = createFileRoute('/$account/chats/new')()
|
||||
const AccountChatsIdLazyImport = createFileRoute('/$account/chats/$id')()
|
||||
|
||||
// Create/Update Routes
|
||||
|
||||
@@ -68,12 +68,10 @@ const AccountChatsNewLazyRoute = AccountChatsNewLazyImport.update({
|
||||
import('./routes/$account.chats.new.lazy').then((d) => d.Route),
|
||||
)
|
||||
|
||||
const AccountChatsIdLazyRoute = AccountChatsIdLazyImport.update({
|
||||
const AccountChatsIdRoute = AccountChatsIdImport.update({
|
||||
path: '/$id',
|
||||
getParentRoute: () => AccountChatsLazyRoute,
|
||||
} as any).lazy(() =>
|
||||
import('./routes/$account.chats.$id.lazy').then((d) => d.Route),
|
||||
)
|
||||
} as any)
|
||||
|
||||
// Populate the FileRoutesByPath interface
|
||||
|
||||
@@ -125,7 +123,7 @@ declare module '@tanstack/react-router' {
|
||||
id: '/$account/chats/$id'
|
||||
path: '/$id'
|
||||
fullPath: '/$account/chats/$id'
|
||||
preLoaderRoute: typeof AccountChatsIdLazyImport
|
||||
preLoaderRoute: typeof AccountChatsIdImport
|
||||
parentRoute: typeof AccountChatsLazyImport
|
||||
}
|
||||
'/$account/chats/new': {
|
||||
@@ -147,7 +145,7 @@ export const routeTree = rootRoute.addChildren({
|
||||
NewLazyRoute,
|
||||
NostrConnectLazyRoute,
|
||||
AccountChatsLazyRoute: AccountChatsLazyRoute.addChildren({
|
||||
AccountChatsIdLazyRoute,
|
||||
AccountChatsIdRoute,
|
||||
AccountChatsNewLazyRoute,
|
||||
}),
|
||||
})
|
||||
@@ -191,7 +189,7 @@ export const routeTree = rootRoute.addChildren({
|
||||
]
|
||||
},
|
||||
"/$account/chats/$id": {
|
||||
"filePath": "$account.chats.$id.lazy.tsx",
|
||||
"filePath": "$account.chats.$id.tsx",
|
||||
"parent": "/$account/chats"
|
||||
},
|
||||
"/$account/chats/new": {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { commands } from "@/commands";
|
||||
import { cn, getReceivers, time, useRelays } from "@/commons";
|
||||
import { cn, getReceivers, time } from "@/commons";
|
||||
import { Spinner } from "@/components/spinner";
|
||||
import { ArrowUp, CloudArrowUp, Paperclip } from "@phosphor-icons/react";
|
||||
import { ArrowUp, Paperclip } from "@phosphor-icons/react";
|
||||
import * as ScrollArea from "@radix-ui/react-scroll-area";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { createLazyFileRoute } from "@tanstack/react-router";
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { message } from "@tauri-apps/plugin-dialog";
|
||||
import type { NostrEvent } from "nostr-tools";
|
||||
@@ -17,24 +18,27 @@ type Payload = {
|
||||
sender: string;
|
||||
};
|
||||
|
||||
export const Route = createLazyFileRoute("/$account/chats/$id")({
|
||||
export const Route = createFileRoute("/$account/chats/$id")({
|
||||
beforeLoad: async ({ params }) => {
|
||||
const inboxRelays: string[] = await invoke("get_inboxes", {
|
||||
id: params.id,
|
||||
});
|
||||
|
||||
return { inboxRelays };
|
||||
},
|
||||
component: Screen,
|
||||
pendingComponent: Pending,
|
||||
});
|
||||
|
||||
function Pending() {
|
||||
return (
|
||||
<div className="size-full flex items-center justify-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Screen() {
|
||||
const { id } = Route.useParams();
|
||||
const { isLoading, data: relays } = useRelays(id);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && relays?.length)
|
||||
commands.subscribeTo(id, relays).then(() => console.log("sub: ", id));
|
||||
|
||||
return () => {
|
||||
if (!isLoading && relays?.length)
|
||||
commands.unsubscribe(id).then(() => console.log("unsub: ", id));
|
||||
};
|
||||
}, [isLoading, relays]);
|
||||
|
||||
return (
|
||||
<div className="size-full flex flex-col">
|
||||
<div className="h-11 shrink-0 border-b border-neutral-100 dark:border-neutral-800" />
|
||||
@@ -46,7 +50,6 @@ function Screen() {
|
||||
|
||||
function List() {
|
||||
const { account, id } = Route.useParams();
|
||||
const { isLoading: rl, isError: rE } = useRelays(id);
|
||||
const { isLoading, isError, data } = useQuery({
|
||||
queryKey: ["chats", id],
|
||||
queryFn: async () => {
|
||||
@@ -63,7 +66,6 @@ function List() {
|
||||
throw new Error(res.error);
|
||||
}
|
||||
},
|
||||
enabled: !rl && !rE,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
@@ -120,11 +122,8 @@ function List() {
|
||||
await queryClient.setQueryData(
|
||||
["chats", id],
|
||||
(prevEvents: NostrEvent[]) => {
|
||||
if (!prevEvents) {
|
||||
return prevEvents;
|
||||
}
|
||||
if (!prevEvents) return prevEvents;
|
||||
return [...prevEvents, event];
|
||||
// queryClient.invalidateQueries(['chats', id]);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -144,14 +143,34 @@ function List() {
|
||||
ref={ref}
|
||||
className="relative h-full py-2 [&>div]:!flex [&>div]:flex-col [&>div]:justify-end [&>div]:min-h-full"
|
||||
>
|
||||
<Virtualizer scrollRef={ref}>
|
||||
<Virtualizer scrollRef={ref} shift>
|
||||
{isLoading || !data ? (
|
||||
<div className="w-full h-56 flex items-center justify-center">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Spinner />
|
||||
Loading message...
|
||||
<>
|
||||
<div className="flex items-center justify-between gap-3 my-1.5 px-3">
|
||||
<div className="flex-1 min-w-0 inline-flex">
|
||||
<div className="py-2 px-3 w-fit max-w-[400px] bg-neutral-100 dark:bg-neutral-800 rounded-l-md rounded-r-xl rounded-t-2xl">
|
||||
Loading...
|
||||
</div>
|
||||
</div>
|
||||
<div className="shrink-0 w-16 flex items-center justify-end">
|
||||
<span className="text-xs text-right text-neutral-600 dark:text-neutral-400">
|
||||
{time(Math.floor(Date.now() / 1000))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3 my-1.5 px-3">
|
||||
<div className="flex-1 min-w-0 inline-flex justify-end">
|
||||
<div className="py-2 px-3 w-fit max-w-[400px] bg-blue-500 text-white rounded-l-xl rounded-r-md rounded-t-2xl">
|
||||
Loading...
|
||||
</div>
|
||||
</div>
|
||||
<div className="shrink-0 w-16 flex items-center justify-end">
|
||||
<span className="text-xs text-right text-neutral-600 dark:text-neutral-400">
|
||||
{time(Math.floor(Date.now() / 1000))}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : isError ? (
|
||||
<div className="w-full h-56 flex items-center justify-center">
|
||||
<div className="flex items-center gap-1.5">
|
||||
@@ -176,34 +195,32 @@ function List() {
|
||||
|
||||
function Form() {
|
||||
const { id } = Route.useParams();
|
||||
const { isLoading, isError, data: relays } = useRelays(id);
|
||||
const { inboxRelays } = Route.useRouteContext();
|
||||
|
||||
const [newMessage, setNewMessage] = useState("");
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// const queryClient = useQueryClient();
|
||||
|
||||
const submit = async () => {
|
||||
startTransition(async () => {
|
||||
if (newMessage.length < 1) return;
|
||||
if (!newMessage.length) return;
|
||||
if (!inboxRelays?.length) return;
|
||||
|
||||
const res = await commands.sendMessage(id, newMessage, relays);
|
||||
const res = await commands.sendMessage(id, newMessage);
|
||||
|
||||
if (res.status === "ok") {
|
||||
setNewMessage("");
|
||||
} else {
|
||||
if (res.status === "error") {
|
||||
await message(res.error, { title: "Coop", kind: "error" });
|
||||
return;
|
||||
}
|
||||
|
||||
setNewMessage("");
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-12 shrink-0 flex items-center justify-center px-3.5">
|
||||
{isLoading ? (
|
||||
<div className="inline-flex items-center justify-center gap-2 h-9 w-fit px-3 bg-neutral-100 dark:bg-neutral-800 rounded-full text-sm">
|
||||
<Spinner />
|
||||
Connecting to inbox relays
|
||||
</div>
|
||||
) : isError || !relays.length ? (
|
||||
{!inboxRelays.length ? (
|
||||
<div className="inline-flex items-center justify-center gap-2 h-9 w-fit px-3 bg-neutral-100 dark:bg-neutral-800 rounded-full text-sm">
|
||||
This user doesn't have inbox relays. You cannot send messages to them.
|
||||
</div>
|
||||
@@ -216,12 +233,14 @@ function Form() {
|
||||
>
|
||||
<Paperclip className="size-5" />
|
||||
</div>
|
||||
{/*
|
||||
<div
|
||||
title="Inbox Relays"
|
||||
className="size-9 inline-flex items-center justify-center hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-full"
|
||||
>
|
||||
<CloudArrowUp className="size-5" />
|
||||
</div>
|
||||
*/}
|
||||
</div>
|
||||
<input
|
||||
placeholder="Message..."
|
||||
@@ -3,7 +3,7 @@ import { ago, cn } from "@/commons";
|
||||
import { User } from "@/components/user";
|
||||
import { Plus, UsersThree } from "@phosphor-icons/react";
|
||||
import * as ScrollArea from "@radix-ui/react-scroll-area";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Link, Outlet, createLazyFileRoute } from "@tanstack/react-router";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import type { NostrEvent } from "nostr-tools";
|
||||
@@ -62,10 +62,11 @@ function Header() {
|
||||
|
||||
function ChatList() {
|
||||
const { account } = Route.useParams();
|
||||
const { isLoading, isError, data } = useQuery({
|
||||
const { queryClient } = Route.useRouteContext();
|
||||
const { isLoading, data } = useQuery({
|
||||
queryKey: ["chats"],
|
||||
queryFn: async () => {
|
||||
const res = await commands.getChats();
|
||||
const res = await commands.getChats(true);
|
||||
|
||||
if (res.status === "ok") {
|
||||
const raw = res.data;
|
||||
@@ -76,21 +77,10 @@ function ChatList() {
|
||||
throw new Error(res.error);
|
||||
}
|
||||
},
|
||||
select: (data) => data.sort((a, b) => b.created_at - a.created_at),
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
useEffect(() => {
|
||||
const unlisten = listen("synchronized", async () => {
|
||||
await queryClient.refetchQueries({ queryKey: ["chats"] });
|
||||
});
|
||||
|
||||
return () => {
|
||||
unlisten.then((f) => f());
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const unlisten = listen<Payload>("event", async (data) => {
|
||||
const event: NostrEvent = JSON.parse(data.payload.event);
|
||||
@@ -127,9 +117,9 @@ function ChatList() {
|
||||
<ScrollArea.Viewport className="relative h-full px-1.5">
|
||||
{isLoading ? (
|
||||
<div>
|
||||
{Array.from(Array(5)).map((_, index) => (
|
||||
{[...Array(5).keys()].map((i) => (
|
||||
<div
|
||||
key={index}
|
||||
key={i}
|
||||
className="flex items-center rounded-lg p-2 mb-1 gap-2"
|
||||
>
|
||||
<div className="size-9 rounded-full animate-pulse bg-black/10 dark:bg-white/10" />
|
||||
@@ -137,12 +127,10 @@ function ChatList() {
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : isError ? (
|
||||
<div className="p-2">Error</div>
|
||||
) : (
|
||||
data.map((item) => (
|
||||
<Link
|
||||
key={item.pubkey}
|
||||
key={item.id + item.pubkey}
|
||||
to="/$account/chats/$id"
|
||||
params={{ account, id: item.pubkey }}
|
||||
>
|
||||
@@ -188,7 +176,7 @@ function CurrentUser() {
|
||||
const { account } = Route.useParams();
|
||||
|
||||
return (
|
||||
<div className="shrink-0 h-12 flex items-center px-2.5 border-t border-black/5 dark:border-white/5">
|
||||
<div className="shrink-0 h-12 flex items-center px-3.5 border-t border-black/5 dark:border-white/5">
|
||||
<User.Provider pubkey={account}>
|
||||
<User.Root className="inline-flex items-center gap-2">
|
||||
<User.Avatar className="size-8 rounded-full" />
|
||||
|
||||
Reference in New Issue
Block a user