Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

ApiRequestsPanel.tsx

230 lines7.5 KB

1import { eq, useLiveQuery } from "@tanstack/react-db";
2import {
3 ChevronDownIcon,
4 ChevronRightIcon,
5 LoaderIcon,
6 Trash2Icon,
7} from "lucide-react";
8import { motion } from "motion/react";
9import { useState } from "react";
10import {
11 type ApiRequest,
12 apiRequestsCollection,
13} from "@/collections/apiRequests";
14import { userPreferencesCollection } from "@/collections/UserPreferences";
15import { cn } from "@/lib/utils";
16import { USER_PLACEHOLDER } from "@/utils/USER_PLACEHOLDER_CONSTANT";
17import { Badge } from "./ui/badge";
18import { Button } from "./ui/button";
19import {
20 Collapsible,
21 CollapsibleContent,
22 CollapsibleTrigger,
23} from "./ui/collapsible";
24import { ScrollArea } from "./ui/scroll-area";
25​
26const API_PANEL_WIDTH = "24rem";
27const PANEL_ANIMATION_DURATION = 0.15;
28​
29async function clearRequests() {
30 const ids = (await apiRequestsCollection.toArrayWhenReady()).map(
31 ({ id }) => id,
32 );
33 apiRequestsCollection.delete(ids);
35​
36function formatDuration(ms: number | null): string {
37 if (ms === null) {
38 return "...";
39 }
40 if (ms < 1000) {
41 return `${Math.round(ms)}ms`;
42 }
43 return `${(ms / 1000).toFixed(2)}s`;
45​
46function JsonViewer({ data, label }: { data: unknown; label: string }) {
47 const [isOpen, setIsOpen] = useState(false);
48​
49 if (data === undefined || data === null) {
50 return null;
51 }
52​
53 return (
54 <Collapsible open={isOpen} onOpenChange={setIsOpen}>
55 <CollapsibleTrigger className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors">
56 {isOpen ? (
57 <ChevronDownIcon className="h-3 w-3" />
58 ) : (
59 <ChevronRightIcon className="h-3 w-3" />
60 )}
61 {label}
62 </CollapsibleTrigger>
63 <CollapsibleContent>
64 <pre className="mt-1 whitespace-pre-wrap p-2 bg-muted/50 rounded text-xs overflow-x-auto max-h-40 overflow-y-auto">
65 {JSON.stringify(data, null, 2)}
66 </pre>
67 </CollapsibleContent>
68 </Collapsible>
69 );
71​
72function RequestItem({ request }: { request: ApiRequest }) {
73 const [isExpanded, setIsExpanded] = useState(false);
74 const isPending = request.status === "pending";
75​
76 return (
77 <div className="border-b border-border last:border-b-0">
78 <button
79 type="button"
80 onClick={() => setIsExpanded(!isExpanded)}
81 className="w-full p-3 hover:bg-muted/50 transition-colors text-left"
82 >
83 <div className="flex items-center gap-2">
84 <Badge
85 variant="outline"
86 className={cn(
87 `font-mono text-[10px] px-1.5 py-0`,
88 request.method === "GET"
89 ? "bg-blue-100 text-blue-700 border-blue-700/30 dark:bg-blue-500/20 dark:text-blue-400 dark:border-blue-500/30"
90 : request.method === "POST"
91 ? "bg-green-200 text-green-700 border-green-400 dark:bg-green-500/20 dark:text-green-400 dark:border-green-500/30"
92 : request.method === "PATCH"
93 ? "bg-yellow-200 text-yellow-700 border-yellow-700/30 dark:bg-yellow-500/20 dark:text-yellow-400 dark:border-yellow-500/30"
94 : request.method === "DELETE"
95 ? "bg-red-100 text-red-500 border-red-400 dark:bg-red-500/20 dark:text-red-400 dark:border-red-500/30"
96 : "bg-gray-200 text-gray-600 border-gray-400 dark:bg-gray-500/20 dark:text-gray-400 dark:border-gray-500/30",
97 )}
98 >
99 {request.method}
100 </Badge>
101 <span className="flex-1 font-mono text-xs truncate">
102 {request.pathname}
103 </span>
104 {isPending ? (
105 <LoaderIcon className="h-3 w-3 text-orange-400 animate-spin" />
106 ) : (
107 <span
108 className={cn(
109 "text-xs font-mono",
110 request.status === "pending"
111 ? "text-orange-400 dark:text-orange-300"
112 : request.status >= 200 && request.status < 300
113 ? "text-green-500 dark:text-green-300"
114 : request.status >= 400
115 ? "text-destructive"
116 : "text-yellow-500 dark:text-yellow-400",
117 )}
118 >
119 {request.status}
120 </span>
121 )}
122 <span className="text-xs text-muted-foreground font-mono">
123 {formatDuration(request.duration)}
124 </span>
125 {isExpanded ? (
126 <ChevronDownIcon className="h-3 w-3 text-muted-foreground" />
127 ) : (
128 <ChevronRightIcon className="h-3 w-3 text-muted-foreground" />
129 )}
130 </div>
131 </button>
132 {isExpanded && (
133 <div className="px-3 pb-3 space-y-2">
134 <div className="text-xs text-muted-foreground">
135 {new Date(request.timestamp).toLocaleTimeString()}
136 </div>
137 <JsonViewer data={request.requestBody} label="Request Body" />
138 {!isPending && (
139 <JsonViewer data={request.responseBody} label="Response Body" />
140 )}
141 </div>
142 )}
143 </div>
144 );
146​
147export function ApiRequestsPanel() {
148 const { data: requests } = useLiveQuery(
149 (q) =>
150 q
151 .from({
152 apiRequest: apiRequestsCollection,
153 })
154 .orderBy(({ apiRequest }) => apiRequest.timestamp, "desc"),
155 [],
156 );
157​
158 const { data: userPreferences } = useLiveQuery((q) =>
159 q
160 .from({
161 userPreferences: userPreferencesCollection,
162 })
163 .where(({ userPreferences }) =>
164 eq(userPreferences.id, USER_PLACEHOLDER.id),
165 )
166 .findOne(),
167 );
168​
169 const isApiPanelOpen = userPreferences?.networkPanel === "open";
170​
171 return (
172 <motion.div
173 initial={false}
174 animate={{
175 width: isApiPanelOpen ? API_PANEL_WIDTH : 0,
176 }}
177 className="shrink-0 h-full overflow-hidden border-l border-border"
178 transition={{
179 duration: PANEL_ANIMATION_DURATION,
180 delay: isApiPanelOpen ? 0 : PANEL_ANIMATION_DURATION,
181 }}
182 >
183 <motion.div
184 className="flex flex-col h-full max-h-full overflow-hidden bg-background"
185 animate={{ opacity: isApiPanelOpen ? 1 : 0 }}
186 transition={{
187 duration: PANEL_ANIMATION_DURATION,
188 delay: isApiPanelOpen ? PANEL_ANIMATION_DURATION : 0,
189 }}
190 >
191 {/* Header */}
192 <div className="shrink-0 flex items-center justify-between px-3 py-2 border-b bg-muted/30">
193 <div className="flex items-center gap-2">
194 <h2 className="text-sm font-medium">API Requests</h2>
195 <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
196 {requests.length}
197 </Badge>
198 </div>
199 <Button
200 variant="ghost"
201 size="icon"
202 onClick={clearRequests}
203 disabled={requests.length === 0}
204 >
205 <Trash2Icon />
206 <span className="sr-only">Clear requests</span>
207 </Button>
208 </div>
209​
210 {/* Request list */}
211 <ScrollArea className="flex-1 min-h-0">
212 {requests.length === 0 ? (
213 <div className="flex flex-col items-center justify-center h-full p-4 text-center">
214 <p className="text-sm text-muted-foreground">No requests yet</p>
215 <p className="text-xs text-muted-foreground mt-1">
216 API requests will appear here
217 </p>
218 </div>
219 ) : (
220 <div>
221 {requests.map((request) => (
222 <RequestItem key={request.id} request={request} />
223 ))}
224 </div>
225 )}
226 </ScrollArea>
227 </motion.div>
228 </motion.div>
229 );