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

ApiLatencyConfigurator.tsx

86 lines3.0 KB

1import { GlobeIcon } from "lucide-react";
2import { useEffect, useState } from "react";
3import { cn } from "@/lib/utils";
4import {
5 API_LATENCY_LOCALSTORAGE_KEY,
6 type ApiLatency,
7 type ApiLatencyOption,
8 apiLatencyInMsSchema,
9 apiLatencyOptions,
10} from "@/utils/apiLatency";
11import { HighlightWrapper } from "@/utils/highlight-collection-related-info";
12import { Button } from "./ui/button";
13import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
14import { Separator } from "./ui/separator";
15​
16export function ApiLatencyConfigurator() {
17 const [isOpen, setIsOpen] = useState(false);
18 const [selectedLatency, setSelectedLatency] = useState<ApiLatency>(1_000);
19​
20 function handleSelectLatency(option: ApiLatencyOption) {
21 localStorage.setItem(API_LATENCY_LOCALSTORAGE_KEY, option.value.toString());
22 setSelectedLatency(option.value);
23 setIsOpen(false);
24 }
25​
26 useEffect(() => {
27 // get the saved latency from localStorage
28 const savedLatency = localStorage.getItem(API_LATENCY_LOCALSTORAGE_KEY);
29 const latency = apiLatencyInMsSchema.parse(savedLatency);
30​
31 setSelectedLatency(latency);
32 }, []);
33​
34 return (
35 <HighlightWrapper highlightId="apiLatencyConfigurator">
36 <Popover open={isOpen} onOpenChange={setIsOpen}>
37 <PopoverTrigger asChild>
38 <Button variant="outline" size="icon">
39 <GlobeIcon
40 className={cn(
41 selectedLatency === 0
42 ? "text-green-500 dark:text-green-300"
43 : selectedLatency === 2000
44 ? "text-orange-400 dark:text-orange-300"
45 : selectedLatency === 5000
46 ? "text-destructive dark:text-destructive"
47 : "text-foreground",
48 )}
49 />
50 </Button>
51 </PopoverTrigger>
52 <PopoverContent className="w-fit max-w-80 flex flex-col gap-2">
53 <p className="text-sm text-foreground font-bold">
54 Select the API latency you want to emulate.
55 </p>
56 <p className="text-xs text-muted-foreground">
57 Note that requests won't show up in the Network tab of the DevTools
58 until they are completed (no PENDING state).
59 </p>
60 <p className="text-xs text-muted-foreground">
61 This is because currently they are handled locally by a service
62 worker and this implementation comes with this limitation.
63 </p>
64 <Separator orientation="horizontal" />
65 {apiLatencyOptions.map((option) => (
66 <div key={option.value} className="">
67 <Button
68 key={option.value}
69 variant={
70 selectedLatency === option.value ? "secondary" : "ghost"
71 }
72 size="sm"
73 onClick={() => {
74 handleSelectLatency(option);
75 }}
76 className="w-full"
77 >
78 {option.label}
79 </Button>
80 </div>
81 ))}
82 </PopoverContent>
83 </Popover>
84 </HighlightWrapper>
85 );