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

ApiRequestsPanel.tsx

256 lines8.6 KB

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