Elffuss BraidHub

kikocis/continue public

main · 9.0 KiBRawPermalink
1import {
2 ArrowDownIcon,
3 ArrowUpIcon,
4 XMarkIcon,
5} from "@heroicons/react/24/outline";
6import {
7 RefObject,
8 useCallback,
9 useEffect,
10 useMemo,
11 useRef,
12 useState,
13} from "react";
14import { HeaderButton, Input } from "..";
15import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
16import {
17 Rectangle,
18 SearchMatch,
19 searchWithinContainer,
20} from "./findWidgetSearch";
21import { useDebounceValue } from "./useDebounce";
22import { useElementSize } from "./useElementSize";
23
24interface HighlightOverlayProps {
25 rectangle: Rectangle;
26 isCurrent: boolean;
27}
28
29const HighlightOverlay = (props: HighlightOverlayProps) => {
30 const { top, left, width, height } = props.rectangle;
31 return (
32 <div
33 className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"}
34 key={`highlight-${top}-${left}`}
35 style={{
36 position: "absolute",
37 top,
38 left,
39 width,
40 height,
41 pointerEvents: "none", // To click through the overlay
42 zIndex: 10,
43 }}
44 />
45 );
46};
47
48type ScrollToMatchOption = "closest" | "first" | "none";
49
50/*
51 useFindWidget takes a container ref and returns
52 1. A widget that can be placed anywhere to search the contents of that container
53 2. Search results and state
54 3. Highlight components to be overlayed over the container
55
56 Container must have relative positioning
57*/
58export const useFindWidget = (
59 searchRef: RefObject<HTMLDivElement>,
60 headerRef: RefObject<HTMLDivElement>,
61 disabled: boolean,
62) => {
63 // Search input, debounced
64 const inputRef = useRef<HTMLInputElement>(null);
65 const [currentValue, setCurrentValue] = useState<string>("");
66 const searchTerm = useDebounceValue(currentValue, 300);
67
68 // Widget open/closed state
69 const [open, setOpen] = useState<boolean>(false);
70 const openWidget = useCallback(() => {
71 setOpen(true);
72 inputRef?.current?.select();
73 }, [inputRef]);
74
75 // Search settings and results
76 const [caseSensitive, setCaseSensitive] = useState<boolean>(false);
77 const [useRegex, setUseRegex] = useState<boolean>(false);
78
79 const [matches, setMatches] = useState<SearchMatch[]>([]);
80 const [currentMatch, setCurrentMatch] = useState<SearchMatch | undefined>(
81 undefined,
82 );
83
84 // Navigating between search results
85 // The "current" search result is highlighted a different color
86 const scrollToMatch = useCallback(
87 (match: SearchMatch) => {
88 setCurrentMatch(match);
89 searchRef?.current?.scrollTo({
90 top: match.overlayRectangle.top - searchRef.current.clientHeight / 2,
91 left: match.overlayRectangle.left - searchRef.current.clientWidth / 2,
92 behavior: "smooth",
93 });
94 },
95 [searchRef],
96 );
97
98 const nextMatch = useCallback(() => {
99 if (!currentMatch || matches.length === 0) return;
100 const newIndex = (currentMatch.index + 1) % matches.length;
101 const newMatch = matches[newIndex];
102 scrollToMatch(newMatch);
103 }, [scrollToMatch, currentMatch, matches]);
104
105 const previousMatch = useCallback(() => {
106 if (!currentMatch || matches.length === 0) return;
107 const newIndex =
108 currentMatch.index === 0 ? matches.length - 1 : currentMatch.index - 1;
109 const newMatch = matches[newIndex];
110 scrollToMatch(newMatch);
111 }, [scrollToMatch, currentMatch, matches]);
112
113 // Handle keyboard shortcuts for navigation
114 useEffect(() => {
115 const handleKeyDown = (event: KeyboardEvent) => {
116 if (event.metaKey && event.key.toLowerCase() === "f" && !event.shiftKey) {
117 event.preventDefault();
118 event.stopPropagation();
119 openWidget();
120 } else if (document.activeElement === inputRef.current) {
121 if (event.key === "Escape") {
122 event.preventDefault();
123 event.stopPropagation();
124 setOpen(false);
125 } else if (event.key === "Enter") {
126 event.preventDefault();
127 event.stopPropagation();
128 if (event.shiftKey) previousMatch();
129 else nextMatch();
130 }
131 }
132 };
133
134 document.addEventListener("keydown", handleKeyDown);
135 return () => {
136 document.removeEventListener("keydown", handleKeyDown);
137 };
138 }, [inputRef, matches, nextMatch]);
139
140 // Handle container resize changes - highlight positions must adjust
141 const { clientHeight: headerHeight, isResizing: headerResizing } =
142 useElementSize(headerRef);
143 const { isResizing: containerResizing } = useElementSize(searchRef);
144 const isResizing = useMemo(() => {
145 return containerResizing || headerResizing;
146 }, [containerResizing, headerResizing]);
147
148 // Main function for finding matches and generating highlight overlays
149 const refreshSearch = useCallback(
150 (scrollTo: ScrollToMatchOption = "none") => {
151 const { results, closestToMiddle } = searchWithinContainer(
152 searchRef,
153 searchTerm,
154 {
155 caseSensitive,
156 useRegex,
157 offsetHeight: headerHeight,
158 },
159 );
160 setMatches(results);
161 // Find match closest to the middle of the view
162 if (searchTerm.length > 1 && results.length) {
163 if (scrollTo === "first") {
164 scrollToMatch(results[0]);
165 }
166 if (scrollTo === "closest") {
167 if (closestToMiddle) {
168 scrollToMatch(closestToMiddle);
169 }
170 }
171 if (scrollTo === "none") {
172 if (closestToMiddle) {
173 setCurrentMatch(closestToMiddle);
174 } else {
175 setCurrentMatch(results[0]);
176 }
177 }
178 }
179 },
180 [
181 searchTerm,
182 caseSensitive,
183 useRegex,
184 searchRef,
185 headerHeight,
186 scrollToMatch,
187 ],
188 );
189
190 // Triggers that should cause immediate refresh of results to closest search value:
191 useEffect(() => {
192 if (disabled || isResizing || !open) {
193 setMatches([]);
194 } else {
195 refreshSearch("closest");
196 }
197 }, [refreshSearch, open, disabled, isResizing]);
198
199 // Clicks in search div can cause content changes that for some reason don't trigger resize
200 // Refresh clicking within container
201 useEffect(() => {
202 const searchContainer = searchRef.current;
203 if (!open || !searchContainer) return;
204 const handleSearchRefClick = () => {
205 setTimeout(() => {
206 refreshSearch("none");
207 }, 150);
208 };
209 searchContainer.addEventListener("click", handleSearchRefClick);
210 return () => {
211 searchContainer.removeEventListener("click", handleSearchRefClick);
212 };
213 }, [searchRef, refreshSearch, open]);
214
215 // Find widget component
216 const widget = (
217 <div
218 className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
219 >
220 <Input
221 disabled={disabled}
222 type="text"
223 ref={inputRef}
224 value={currentValue}
225 onChange={(e) => {
226 setCurrentValue(e.target.value);
227 }}
228 placeholder="Search..."
229 />
230 <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
231 {matches.length === 0
232 ? "No results"
233 : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
234 </p>
235 <div className="hidden flex-row gap-0.5 sm:flex">
236 <HeaderButtonWithToolTip
237 tooltipPlacement="top-end"
238 text={"Previous Match"}
239 onClick={(e) => {
240 e.stopPropagation();
241 previousMatch();
242 }}
243 className="h-4 w-4 focus:ring"
244 disabled={matches.length < 2 || disabled}
245 >
246 <ArrowUpIcon className="h-4 w-4" />
247 </HeaderButtonWithToolTip>
248 <HeaderButtonWithToolTip
249 tooltipPlacement="top-end"
250 text={"Next Match"}
251 onClick={(e) => {
252 e.stopPropagation();
253 nextMatch();
254 }}
255 className="h-4 w-4 focus:ring"
256 disabled={matches.length < 2 || disabled}
257 >
258 <ArrowDownIcon className="h-4 w-4" />
259 </HeaderButtonWithToolTip>
260 </div>
261 <HeaderButtonWithToolTip
262 disabled={disabled}
263 inverted={caseSensitive}
264 tooltipPlacement="top-end"
265 text={
266 caseSensitive
267 ? "Turn off case sensitivity"
268 : "Turn on case sensitivity"
269 }
270 onClick={(e) => {
271 e.stopPropagation();
272 setCaseSensitive((curr) => !curr);
273 }}
274 className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
275 >
276 Aa
277 </HeaderButtonWithToolTip>
278 {/* TODO - add useRegex functionality */}
279 <HeaderButton
280 inverted={false}
281 onClick={() => setOpen(false)}
282 className="focus:ring"
283 >
284 <XMarkIcon className="h-4 w-4" />
285 </HeaderButton>
286 </div>
287 );
288
289 // Generate the highlight overlay elements
290 const highlights = useMemo(() => {
291 return matches.map((match) => (
292 <HighlightOverlay
293 rectangle={match.overlayRectangle}
294 isCurrent={currentMatch?.index === match.index}
295 />
296 ));
297 }, [matches, currentMatch]);
298
299 return {
300 highlights,
301 widget,
302 };
303};