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