Open History to see the last commit
1import { ArrowDownUp, ChevronRight, LoaderCircle, Zap } from "lucide-react";
2import { useEffect, useId, useState } from "react";
3
4import { Switch } from "@/components/ui/switch";
5import { Toggle } from "@/components/ui/toggle";
6import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
7import { setNetworkConfig, useNetworkConfig } from "@/api/network-config";
8import { useRequestLog } from "@/api/request-log";
9import type { RequestLogEntry } from "@/api/request-log";
10import { reportAction } from "@/lib/app-actions";
11import { cn } from "@/lib/utils";
12
13import { LATENCY_PRESETS, formatDuration, formatLatency } from "./latency";
14
15/*
16 * Latency and failure controls for the fake API (`api/network-config.ts`),
17 * and the request inspector's list (`api/request-log.ts`). Shared by the
18 * desktop browser toolbar and drawer, and by the app sheet's Network view
19 * on phones.
20 */
21
22export function setLatency(latencyMs: number) {
23 setNetworkConfig({ latencyMs });
24 reportAction({ type: "network.latency-set", latencyMs });
25}
26
27export function setFailNextRequest(failNext: boolean) {
28 setNetworkConfig({ failNextRequest: failNext });
29 reportAction({ type: "network.fail-next-set", failNext });
30}
31
32export function LatencyControl({
33 className,
34 size = "sm",
35}: {
36 className?: string;
37 size?: "sm" | "default";
38}) {
39 const { latencyMs } = useNetworkConfig();
40 return (
41 <ToggleGroup
42 type="single"
43 variant="outline"
44 size={size}
45 spacing={0}
46 value={String(latencyMs)}
47 // Picking the selected preset again would clear it; keep it instead.
48 onValueChange={(value) => value && setLatency(Number(value))}
49 aria-label="API latency"
50 className={className}
51 >
52 {LATENCY_PRESETS.map((ms) => (
53 <ToggleGroupItem
54 key={ms}
55 value={String(ms)}
56 aria-label={`${formatLatency(ms)} latency`}
57 className="flex-auto tabular-nums group-data-[spacing=0]/toggle-group:px-2.5 data-[state=on]:bg-foreground data-[state=on]:text-background"
58 >
59 {formatLatency(ms)}
60 </ToggleGroupItem>
61 ))}
62 </ToggleGroup>
63 );
64}
65
66/** A labelled switch (the app sheet's Network view). */
67export function FailNextRequestControl({ className }: { className?: string }) {
68 const id = useId();
69 const descriptionId = useId();
70 const { failNextRequest } = useNetworkConfig();
71 return (
72 <div className={cn("flex items-center justify-between gap-3", className)}>
73 <div>
74 <label htmlFor={id} className="text-sm">
75 Fail the next request
76 </label>
77 <p id={descriptionId} className="text-[12px] text-muted-foreground">
78 The next request the app sends gets a 500. Ones already on their way don't.
79 </p>
80 </div>
81 <Switch
82 id={id}
83 aria-describedby={descriptionId}
84 checked={failNextRequest}
85 onCheckedChange={setFailNextRequest}
86 className="data-checked:bg-red-600"
87 />
88 </div>
89 );
90}
91
92/** A compact toggle button (the desktop browser toolbar). */
93export function FailNextRequestToggle({ className }: { className?: string }) {
94 const { failNextRequest } = useNetworkConfig();
95 return (
96 <Toggle
97 variant="outline"
98 size="sm"
99 pressed={failNextRequest}
100 onPressedChange={setFailNextRequest}
101 title="The next request the app sends gets a 500. Ones already on their way don't."
102 className={cn(
103 "gap-1.5 data-[state=on]:border-red-600/40 data-[state=on]:bg-red-600/10 data-[state=on]:text-red-700 dark:data-[state=on]:text-red-400",
104 className,
105 )}
106 >
107 <Zap aria-hidden />
108 Fail next
109 </Toggle>
110 );
111}
112
113/** The current time, ticking while `active` (for pending requests' elapsed time). */
114function useNow(active: boolean, intervalMs = 100): number {
115 const [now, setNow] = useState(() => Date.now());
116 useEffect(() => {
117 if (!active) return;
118 setNow(Date.now());
119 const timer = window.setInterval(() => setNow(Date.now()), intervalMs);
120 return () => window.clearInterval(timer);
121 }, [active, intervalMs]);
122 return now;
123}
124
125const COLUMNS = "grid grid-cols-[1rem_3.25rem_minmax(0,1fr)_3.5rem_4rem] items-center gap-2";
126
127/**
128 * The request inspector's list: every call to the fake API, newest first,
129 * live. A pending request counts up until it settles; expanding a row shows
130 * what was sent and what came back.
131 */
132export function RequestLog({ className }: { className?: string }) {
133 const entries = useRequestLog();
134 const now = useNow(entries.some((entry) => entry.state === "pending"));
135
136 return (
137 <div className={cn("flex min-h-0 flex-col", className)}>
138 <div
139 aria-hidden
140 className={cn(
141 COLUMNS,
142 "border-b px-3 py-2 text-[11px] font-medium tracking-wide text-muted-foreground uppercase",
143 )}
144 >
145 <span />
146 <span>Method</span>
147 <span>URL</span>
148 <span className="text-right">Status</span>
149 <span className="text-right">Time</span>
150 </div>
151 {entries.length === 0 ? (
152 <div className="flex min-h-40 flex-1 flex-col items-center justify-center gap-1 px-6 pb-8 text-center">
153 <ArrowDownUp className="mb-1 size-5 text-muted-foreground" aria-hidden />
154 <p className="text-sm font-medium">No requests yet</p>
155 <p className="max-w-64 text-[13px] text-muted-foreground">
156 Every call the app makes to the fake API will show up here, with its status and timing.
157 </p>
158 </div>
159 ) : (
160 <ol aria-label="Requests, newest first" className="divide-y">
161 {[...entries].reverse().map((entry) => (
162 <RequestRow key={entry.id} entry={entry} now={now} />
163 ))}
164 </ol>
165 )}
166 </div>
167 );
168}
169
170function RequestRow({ entry, now }: { entry: RequestLogEntry; now: number }) {
171 const [expanded, setExpanded] = useState(false);
172 const detailsId = useId();
173 const pending = entry.state === "pending";
174 const elapsed = entry.durationMs ?? Math.max(0, now - entry.startedAt);
175
176 return (
177 <li data-state={entry.state} className="relative">
178 <button
179 type="button"
180 aria-expanded={expanded}
181 aria-controls={detailsId}
182 onClick={() => setExpanded(!expanded)}
183 className={cn(
184 COLUMNS,
185 "w-full px-3 py-1.5 text-left text-[12px] transition-colors outline-none hover:bg-muted/60 focus-visible:bg-muted",
186 )}
187 >
188 <ChevronRight
189 aria-hidden
190 className={cn(
191 "size-3.5 text-muted-foreground transition-transform motion-reduce:transition-none",
192 expanded && "rotate-90",
193 )}
194 />
195 <MethodBadge method={entry.method} />
196 <span className="truncate font-mono text-[11.5px]" title={entry.url}>
197 {entry.url}
198 </span>
199 <StatusCell entry={entry} />
200 <span
201 className={cn(
202 "text-right font-mono text-[11.5px] tabular-nums",
203 pending ? "text-foreground" : "text-muted-foreground",
204 )}
205 >
206 {formatDuration(elapsed)}
207 </span>
208 </button>
209 {pending && entry.latencyMs > 0 && (
210 <span
211 aria-hidden
212 className="absolute inset-x-0 bottom-0 h-0.5 origin-left bg-guide-accent"
213 style={{ transform: `scaleX(${Math.min(1, elapsed / entry.latencyMs)})` }}
214 />
215 )}
216 <div id={detailsId} hidden={!expanded} className="space-y-2 bg-muted/40 px-3 pt-1 pb-3">
217 <p className="text-[11.5px] text-muted-foreground">
218 {entry.injectedFailure
219 ? "Failed on purpose (fail next request). "
220 : entry.state === "aborted"
221 ? "Cancelled before the server answered. "
222 : ""}
223 Latency {formatLatency(entry.latencyMs)}
224 {entry.durationMs !== null && `, took ${formatDuration(entry.durationMs)}`}.
225 </p>
226 <Body title="Request body" value={entry.requestBody} empty="No body" />
227 <Body
228 title="Response body"
229 value={entry.responseBody}
230 empty={pending ? "Waiting for the server…" : "No body"}
231 />
232 </div>
233 </li>
234 );
235}
236
237function MethodBadge({ method }: { method: string }) {
238 return (
239 <span
240 className={cn(
241 "w-fit rounded px-1 font-mono text-[10.5px] font-semibold",
242 method === "GET" && "bg-sky-500/15 text-sky-700 dark:text-sky-300",
243 method === "POST" && "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300",
244 method === "PATCH" && "bg-amber-500/15 text-amber-700 dark:text-amber-300",
245 method === "PUT" && "bg-amber-500/15 text-amber-700 dark:text-amber-300",
246 method === "DELETE" && "bg-red-500/15 text-red-700 dark:text-red-300",
247 )}
248 >
249 {method}
250 </span>
251 );
252}
253
254function StatusCell({ entry }: { entry: RequestLogEntry }) {
255 if (entry.state === "pending") {
256 return (
257 <span className="flex items-center justify-end gap-1 text-[11.5px] text-guide-accent">
258 <LoaderCircle className="size-3 animate-spin motion-reduce:animate-none" aria-hidden />
259 <span className="sr-only">Pending</span>
260 <span aria-hidden>…</span>
261 </span>
262 );
263 }
264 if (entry.state === "aborted" || entry.status === null) {
265 return <span className="text-right text-[11.5px] text-muted-foreground">Aborted</span>;
266 }
267 const ok = entry.status < 400;
268 return (
269 <span
270 className={cn(
271 "text-right font-mono text-[11.5px] font-semibold tabular-nums",
272 ok ? "text-emerald-700 dark:text-emerald-400" : "text-red-600 dark:text-red-400",
273 )}
274 >
275 {entry.status}
276 </span>
277 );
278}
279
280function Body({ title, value, empty }: { title: string; value: unknown; empty: string }) {
281 return (
282 <div>
283 <p className="mb-0.5 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">
284 {title}
285 </p>
286 {value === undefined || value === null ? (
287 <p className="text-[12px] text-muted-foreground italic">{empty}</p>
288 ) : (
289 <pre className="max-h-48 overflow-auto rounded-md border bg-background p-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap">
290 {JSON.stringify(value, null, 2)}
291 </pre>
292 )}
293 </div>
294 );
295}
296
297/** How many requests are in flight right now. */
298export function usePendingRequestCount(): number {
299 return useRequestLog().filter((entry) => entry.state === "pending").length;
300}