Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PreviewFindBar.tsx

139 lines4.8 KB

1import { useEffect, useRef, useState, type KeyboardEvent } from "react";
2import { ChevronDownIcon, ChevronUpIcon, XIcon } from "lucide-react";
3import { Button } from "../ui/button";
4import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
5import { cn } from "~/lib/utils";
6import { previewBridge } from "./previewBridge";
7​
8interface PreviewFindBarProps {
9 readonly tabId: string;
10 readonly focusRequestId: number;
11 readonly onClose: () => void;
13​
14export function PreviewFindBar({ tabId, focusRequestId, onClose }: PreviewFindBarProps) {
15 const inputRef = useRef<HTMLInputElement | null>(null);
16 const [query, setQuery] = useState("");
17 const [result, setResult] = useState<{ active: number; matches: number } | null>(null);
18​
19 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- focuses and selects the input DOM node when the bar opens or a find shortcut fires
20 useEffect(() => {
21 inputRef.current?.focus();
22 inputRef.current?.select();
23 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Each find shortcut bumps the request id, so an already-open bar refocuses and reselects its query.
24 }, [focusRequestId]);
25​
26 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to Chromium find results for this tab and stops the search on unmount
27 useEffect(() => {
28 if (!previewBridge) return;
29 const unsubscribe = previewBridge.onFindResult((event) => {
30 if (event.tabId !== tabId) return;
31 // Chromium reports -1 for a field an update leaves unchanged.
32 setResult((previous) => ({
33 active: event.activeMatchOrdinal >= 0 ? event.activeMatchOrdinal : (previous?.active ?? 0),
34 matches: event.matches >= 0 ? event.matches : (previous?.matches ?? 0),
35 }));
36 });
37 return () => {
38 unsubscribe();
39 void previewBridge?.stopFindInPage(tabId).catch(() => undefined);
40 };
41 }, [tabId]);
42​
43 const search = (text: string, options: { forward: boolean; newSession: boolean }) => {
44 if (!previewBridge) return;
45 void previewBridge.findInPage(tabId, text, options).catch(() => undefined);
46 };
47​
48 const handleQueryChange = (next: string) => {
49 setQuery(next);
50 if (next.length === 0) {
51 setResult(null);
52 void previewBridge?.stopFindInPage(tabId).catch(() => undefined);
53 return;
54 }
55 search(next, { forward: true, newSession: true });
56 };
57​
58 const step = (forward: boolean) => {
59 if (query.length === 0) return;
60 search(query, { forward, newSession: false });
61 };
62​
63 const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
64 if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;
65 if (event.key === "Enter") {
66 event.preventDefault();
67 event.stopPropagation();
68 step(!event.shiftKey);
69 } else if (event.key === "Escape") {
70 event.preventDefault();
71 event.stopPropagation();
72 onClose();
73 }
74 };
75​
76 const hasQuery = query.length > 0;
77 const noResults = hasQuery && result !== null && result.matches === 0;
78 const label =
79 hasQuery && result ? `${result.matches === 0 ? 0 : result.active}/${result.matches}` : "";
80 const navigationDisabled = !result || result.matches === 0;
81​
82 return (
83 <div className="absolute top-3 right-3 z-40 w-[min(22rem,calc(100%-1.5rem))]">
84 <InputGroup
85 variant="popover"
86 size="lg"
87 role="search"
88 aria-label="Find in page"
89 className="w-full"
90 >
91 <InputGroupInput
92 ref={inputRef}
93 type="search"
94 size="sm"
95 value={query}
96 aria-label="Find in page"
97 placeholder="Find in page"
98 maxLength={200}
99 spellCheck={false}
100 autoComplete="off"
101 onChange={(event) => handleQueryChange(event.target.value)}
102 onKeyDown={handleKeyDown}
103 />
104 <InputGroupAddon align="inline-end" inset="pill">
105 <span
106 aria-live="polite"
107 className={cn(
108 "min-w-10 text-center text-xs tabular-nums",
109 noResults ? "text-destructive" : "text-muted-foreground",
110 )}
111 >
112 {label}
113 </span>
114 <Button
115 size="icon-xs"
116 variant="ghost"
117 aria-label="Previous match"
118 disabled={navigationDisabled}
119 onClick={() => step(false)}
120 >
121 <ChevronUpIcon />
122 </Button>
123 <Button
124 size="icon-xs"
125 variant="ghost"
126 aria-label="Next match"
127 disabled={navigationDisabled}
128 onClick={() => step(true)}
129 >
130 <ChevronDownIcon />
131 </Button>
132 <Button size="icon-xs" variant="ghost" aria-label="Close find" onClick={onClose}>
133 <XIcon />
134 </Button>
135 </InputGroupAddon>
136 </InputGroup>
137 </div>
138 );