diff --git a/src/lib/orpc-client.ts b/src/lib/orpc-client.ts new file mode 100644 index 0000000..8751d1a --- /dev/null +++ b/src/lib/orpc-client.ts @@ -0,0 +1,24 @@ +import { createORPCClient } from '@orpc/client' +import { RPCLink } from '@orpc/client/fetch' +import { createTanstackQueryUtils } from '@orpc/tanstack-query' + +import type { RouterClient } from '@orpc/server' + +import type { AppRouter } from '#/orpc/router' + +const link = new RPCLink({ + fetch: (request, init) => { + return fetch(new Request(request, { credentials: 'same-origin' }), init) + }, + url: () => { + if (typeof window !== 'undefined') { + return new URL('/api/rpc', window.location.origin).toString() + } + + return 'http://localhost/api/rpc' + }, +}) + +export const rpcClient: RouterClient = createORPCClient(link) + +export const orpc = createTanstackQueryUtils(rpcClient) diff --git a/src/routes/dashboard.tsx b/src/routes/dashboard.tsx index 2c5ff72..6211ded 100644 --- a/src/routes/dashboard.tsx +++ b/src/routes/dashboard.tsx @@ -1,17 +1,266 @@ +import { useEffect, useMemo, useState, type FormEvent, type ReactNode } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { Navigate, createFileRoute } from '@tanstack/react-router' +import { + AtSign, + Clock3, + Inbox as InboxIcon, + LoaderCircle, + MailPlus, + RefreshCw, + Reply, + Send, + Sparkles, +} from 'lucide-react' + +import { Button } from '#/components/ui/button' +import { Input } from '#/components/ui/input' +import { Label } from '#/components/ui/label' +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '#/components/ui/select' +import { Textarea } from '#/components/ui/textarea' import { authClient } from '#/lib/auth-client' +import { orpc, rpcClient } from '#/lib/orpc-client' +import { cn } from '#/lib/utils' export const Route = createFileRoute('/dashboard')({ component: DashboardPage, }) +type ComposeMode = 'new' | 'reply' + +type ComposeState = { + mode: ComposeMode + inboxId: string + replyToThreadId?: string + to: string + cc: string + bcc: string + subject: string + text: string + html: string +} + +type ActionNotice = { + tone: 'error' | 'success' + text: string +} + +type InboxRecord = Awaited> +type ThreadListResult = Awaited> +type ThreadSummary = ThreadListResult['items'][number] +type MessageListResult = Awaited> +type MessageSummary = MessageListResult['items'][number] +type MessageDetail = Awaited> +type SendMessageInput = Parameters[0] + function DashboardPage() { + const queryClient = useQueryClient() const { data: session, isPending } = authClient.useSession() + const [isClient, setIsClient] = useState(false) + const [selectedInboxId, setSelectedInboxId] = useState(null) + const [selectedThreadId, setSelectedThreadId] = useState(null) + const [selectedMessageId, setSelectedMessageId] = useState(null) + const [aliasDraft, setAliasDraft] = useState('') + const [composeState, setComposeState] = useState(null) + const [actionNotice, setActionNotice] = useState(null) + + useEffect(() => { + setIsClient(true) + }, []) + + const isReady = isClient && Boolean(session?.user) + + const inboxesQuery = useQuery( + orpc.inboxes.list.queryOptions({ + enabled: isReady, + staleTime: 5_000, + }), + ) + + const inboxes: InboxRecord[] = inboxesQuery.data ?? [] + const selectedInbox = useMemo( + () => inboxes.find((inbox) => inbox.id === selectedInboxId) ?? null, + [inboxes, selectedInboxId], + ) + + const threadsQuery = useQuery( + orpc.threads.listByInbox.queryOptions({ + enabled: isReady && Boolean(selectedInboxId), + input: { + inboxId: selectedInboxId ?? '', + limit: 25, + }, + staleTime: 3_000, + }), + ) + + const threads: ThreadSummary[] = threadsQuery.data?.items ?? [] + const selectedThread = useMemo( + () => threads.find((thread) => thread.id === selectedThreadId) ?? null, + [threads, selectedThreadId], + ) + + const messagesQuery = useQuery( + orpc.threads.listMessages.queryOptions({ + enabled: isReady && Boolean(selectedThreadId), + input: { + limit: 100, + threadId: selectedThreadId ?? '', + }, + staleTime: 3_000, + }), + ) + + const threadMessages: MessageSummary[] = messagesQuery.data?.items ?? [] + const selectedMessageSummary = useMemo( + () => threadMessages.find((message) => message.id === selectedMessageId) ?? null, + [threadMessages, selectedMessageId], + ) + + const messageDetailQuery = useQuery( + orpc.messages.get.queryOptions({ + enabled: isReady && Boolean(selectedMessageId), + input: { + messageId: selectedMessageId ?? '', + }, + staleTime: 3_000, + }), + ) + + const selectedMessage: MessageDetail | null = messageDetailQuery.data ?? null + + useEffect(() => { + if (inboxes.length === 0) { + setSelectedInboxId(null) + return + } + + if (!selectedInboxId || !inboxes.some((inbox) => inbox.id === selectedInboxId)) { + setSelectedInboxId(inboxes[0]!.id) + } + }, [inboxes, selectedInboxId]) + + useEffect(() => { + if (threads.length === 0) { + setSelectedThreadId(null) + return + } + + if (!selectedThreadId || !threads.some((thread) => thread.id === selectedThreadId)) { + setSelectedThreadId(threads[0]!.id) + } + }, [selectedThreadId, threads]) + + useEffect(() => { + if (threadMessages.length === 0) { + setSelectedMessageId(null) + return + } + + if (!selectedMessageId || !threadMessages.some((message) => message.id === selectedMessageId)) { + setSelectedMessageId(threadMessages.at(-1)?.id ?? null) + } + }, [selectedMessageId, threadMessages]) + + useEffect(() => { + setAliasDraft(selectedInbox?.customLocalPart ?? '') + }, [selectedInbox?.customLocalPart, selectedInbox?.id]) + + const createInboxMutation = useMutation( + orpc.inboxes.create.mutationOptions({ + onSuccess: async (createdInbox) => { + setActionNotice({ + text: `Created ${getPrimaryInboxAddress(createdInbox)}.`, + tone: 'success', + }) + setSelectedInboxId(createdInbox.id) + await queryClient.invalidateQueries({ + queryKey: orpc.inboxes.list.key(), + }) + }, + }), + ) + + const updateAliasMutation = useMutation( + orpc.inboxes.updateAlias.mutationOptions({ + onSuccess: async (updatedInbox) => { + setActionNotice({ + text: updatedInbox.customLocalPart + ? `Alias saved as ${updatedInbox.customLocalPart}@clankr.email.` + : 'Custom alias cleared.', + tone: 'success', + }) + await queryClient.invalidateQueries({ + queryKey: orpc.inboxes.list.key(), + }) + }, + onError: (error) => { + setActionNotice({ + text: getErrorMessage(error), + tone: 'error', + }) + }, + }), + ) + + const sendMessageMutation = useMutation( + orpc.messages.send.mutationOptions({ + onSuccess: async (result) => { + setComposeState(null) + setSelectedInboxId(result.inboxId) + setSelectedThreadId(result.threadId) + setSelectedMessageId(result.id) + setActionNotice({ + text: result.status === 'accepted' + ? 'Message accepted by the provider.' + : result.errorMessage ?? 'Message saved, but the provider rejected it.', + tone: result.status === 'accepted' ? 'success' : 'error', + }) + + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: orpc.threads.listByInbox.queryKey({ + input: { + inboxId: result.inboxId, + limit: 25, + }, + }), + }), + queryClient.invalidateQueries({ + queryKey: orpc.threads.listMessages.queryKey({ + input: { + limit: 100, + threadId: result.threadId, + }, + }), + }), + queryClient.invalidateQueries({ + queryKey: orpc.messages.get.queryKey({ + input: { + messageId: result.id, + }, + }), + }), + ]) + }, + }), + ) + if (isPending) { return ( -
-
+
+
+ + + +
) } @@ -20,30 +269,902 @@ function DashboardPage() { return } - const details = [ - ['Name', session.user.name], - ['Email', session.user.email], - ['User ID', session.user.id], - ['Email Verified', session.user.emailVerified ? 'Yes' : 'No'], - ] - - return ( -
-
-

Dashboard

-

- Signed-in user details. -

- -
- {details.map(([label, value]) => ( -
-
{label}
-
{value || '-'}
+ const composerInbox = composeState + ? inboxes.find((inbox) => inbox.id === composeState.inboxId) ?? null + : null + + return ( +
+
+
+
+
+
+
+ + End-to-end inbox workbench +
+
+

+ Run the inbox flow without leaving the dashboard. +

+

+ Create inboxes, move between live threads, read full message bodies, and send new + messages or threaded replies from one place. +

+
+
+ +
+ + + +
- ))} -
+ + {actionNotice ? ( +
+ {actionNotice.text} + +
+ ) : null} +
+ + +
+ + +
+ +
+
+

Threads

+

+ {selectedInbox + ? `Latest conversations for ${getPrimaryInboxAddress(selectedInbox)}.` + : 'Pick an inbox to browse its conversations.'} +

+
+ +
+ +
+ {threadsQuery.isLoading ? ( +
+ + + + +
+ ) : !selectedInbox ? ( + + ) : threads.length === 0 ? ( + + ) : ( + threads.map((thread) => { + const isSelected = thread.id === selectedThreadId + + return ( + + ) + }) + )} +
+
+
+ +
+ {composeState ? ( + { + setComposeState(null) + sendMessageMutation.reset() + }} + onChange={setComposeState} + onSubmit={(event) => { + event.preventDefault() + setActionNotice(null) + sendMessageMutation.mutate(buildSendMessagePayload(composeState)) + }} + replySource={selectedMessageSummary} + selectedInbox={composerInbox} + sendError={sendMessageMutation.isError ? getErrorMessage(sendMessageMutation.error) : null} + /> + ) : null} + + +
+
+

Conversation reader

+

+ {selectedThread + ? `Inspect ${selectedThread.subject || '(no subject)'} and open any message in the thread.` + : 'Select a thread to inspect the full conversation.'} +

+
+ +
+ + +
+
+ + {!selectedThread ? ( +
+ +
+ ) : ( +
+
+
+
+
+

Messages

+

+ {threadMessages.length} item{threadMessages.length === 1 ? '' : 's'} in order +

+
+ {messagesQuery.isFetching ? : null} +
+ + {messagesQuery.isLoading ? ( +
+ + + +
+ ) : threadMessages.length === 0 ? ( +
+ +
+ ) : ( + threadMessages.map((message) => { + const isSelected = message.id === selectedMessageId + + return ( + + ) + }) + )} +
+ +
+
+
+

Message detail

+

+ Read body content, routing metadata, and storage source. +

+
+ {messageDetailQuery.isFetching ? : null} +
+ + {messageDetailQuery.isLoading ? ( +
+ + + + +
+ ) : selectedMessage ? ( + + ) : ( +
+ +
+ )} +
+
+
+ )} +
+
+
) } + +function ComposePanel(props: { + composeState: ComposeState + inboxes: InboxRecord[] + isSubmitting: boolean + onCancel: () => void + onChange: (nextState: ComposeState) => void + onSubmit: (event: FormEvent) => void + replySource: MessageSummary | null + selectedInbox: InboxRecord | null + sendError: string | null +}) { + const { composeState, inboxes, isSubmitting, onCancel, onChange, onSubmit, replySource, selectedInbox, sendError } = props + const isReply = composeState.mode === 'reply' + + return ( + +
+
+

+ {isReply ? 'Reply in thread' : 'Compose message'} +

+

+ {isReply + ? 'The reply uses thread headers automatically so the conversation stays grouped.' + : 'Send a new outbound message from any active inbox.'} +

+
+
+ {selectedInbox ? getPrimaryInboxAddress(selectedInbox) : 'Choose inbox'} + +
+
+ +
+
+
+ + {isReply ? ( +
+ {selectedInbox ? getPrimaryInboxAddress(selectedInbox) : 'No inbox selected'} +
+ ) : ( + + )} +
+ +
+ + onChange({ ...composeState, subject: event.target.value })} + placeholder="Project update" + value={composeState.subject} + /> +
+
+ +
+ + onChange({ ...composeState, to: event.target.value })} + placeholder="name@example.com, ops@example.com" + value={composeState.to} + /> +

+ Separate addresses with commas, spaces, or new lines. +

+
+ +
+ Advanced fields +
+
+ + onChange({ ...composeState, cc: event.target.value })} + placeholder="team@example.com" + value={composeState.cc} + /> +
+
+ + onChange({ ...composeState, bcc: event.target.value })} + placeholder="audit@example.com" + value={composeState.bcc} + /> +
+
+ +