| 1 | import { |
| 2 | ArrowDownIcon, |
| 3 | ArrowUpIcon, |
| 4 | XMarkIcon, |
| 5 | } from "@heroicons/react/24/outline"; |
| 6 | import { |
| 7 | RefObject, |
| 8 | useCallback, |
| 9 | useEffect, |
| 10 | useMemo, |
| 11 | useRef, |
| 12 | useState, |
| 13 | } from "react"; |
| 14 | import { HeaderButton, Input } from ".."; |
| 15 | import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; |
| 16 | import { useAppSelector } from "../../redux/hooks"; |
| 17 | |
| 18 | interface SearchMatch { |
| 19 | index: number; |
| 20 | textNode: Text; |
| 21 | overlayRectangle: Rectangle; |
| 22 | } |
| 23 | |
| 24 | type ScrollToMatchOption = "closest" | "first" | "none"; |
| 25 | |
| 26 | const SEARCH_DEBOUNCE = 300; |
| 27 | const RESIZE_DEBOUNCE = 200; |
| 28 | |
| 29 | interface Rectangle { |
| 30 | top: number; |
| 31 | left: number; |
| 32 | width: number; |
| 33 | height: number; |
| 34 | } |
| 35 | |
| 36 | interface HighlightOverlayProps extends Rectangle { |
| 37 | isCurrent: boolean; |
| 38 | } |
| 39 | |
| 40 | const HighlightOverlay = (props: HighlightOverlayProps) => { |
| 41 | const { isCurrent, top, left, width, height } = props; |
| 42 | return ( |
| 43 | <div |
| 44 | className={isCurrent ? "bg-find-match-selected" : "bg-blue-200/30"} // bg-vsc-find-match can"t get to work |
| 45 | key={`highlight-${top}-${left}`} |
| 46 | style={{ |
| 47 | position: "absolute", |
| 48 | top, |
| 49 | left, |
| 50 | width, |
| 51 | height, |
| 52 | pointerEvents: "none", // To click through the overlay |
| 53 | zIndex: 10, |
| 54 | }} |
| 55 | /> |
| 56 | ); |
| 57 | }; |
| 58 | |
| 59 | /* |
| 60 | useFindWidget takes a container ref and returns |
| 61 | 1. A widget that can be placed anywhere to search the contents of that container |
| 62 | 2. Search results and state |
| 63 | 3. Highlight components to be overlayed over the container |
| 64 | |
| 65 | Container must have relative positioning |
| 66 | */ |
| 67 | export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => { |
| 68 | // Search input, debounced |
| 69 | const [input, setInput] = useState<string>(""); |
| 70 | const debouncedInput = useRef<string>(""); |
| 71 | const inputRef = useRef<HTMLInputElement>(null); |
| 72 | |
| 73 | // Widget open/closed state |
| 74 | const [open, setOpen] = useState<boolean>(false); |
| 75 | const openWidget = useCallback(() => { |
| 76 | setOpen(true); |
| 77 | inputRef?.current?.select(); |
| 78 | }, [setOpen, inputRef]); |
| 79 | |
| 80 | // Search settings and results |
| 81 | const [caseSensitive, setCaseSensitive] = useState<boolean>(false); |
| 82 | const [useRegex, setUseRegex] = useState<boolean>(false); |
| 83 | |
| 84 | const [matches, setMatches] = useState<SearchMatch[]>([]); |
| 85 | const [currentMatch, setCurrentMatch] = useState<SearchMatch | undefined>( |
| 86 | undefined, |
| 87 | ); |
| 88 | |
| 89 | // Navigating between search results |
| 90 | // The "current" search result is highlighted a different color |
| 91 | const scrollToMatch = useCallback( |
| 92 | (match: SearchMatch) => { |
| 93 | setCurrentMatch(match); |
| 94 | searchRef?.current?.scrollTo({ |
| 95 | top: match.overlayRectangle.top - searchRef.current.clientHeight / 2, |
| 96 | left: match.overlayRectangle.left - searchRef.current.clientWidth / 2, |
| 97 | behavior: "smooth", |
| 98 | }); |
| 99 | }, |
| 100 | [searchRef.current], |
| 101 | ); |
| 102 | |
| 103 | const nextMatch = useCallback(() => { |
| 104 | if (!currentMatch || matches.length === 0) return; |
| 105 | const newIndex = (currentMatch.index + 1) % matches.length; |
| 106 | const newMatch = matches[newIndex]; |
| 107 | scrollToMatch(newMatch); |
| 108 | }, [scrollToMatch, currentMatch, matches]); |
| 109 | |
| 110 | const previousMatch = useCallback(() => { |
| 111 | if (!currentMatch || matches.length === 0) return; |
| 112 | const newIndex = |
| 113 | currentMatch.index === 0 ? matches.length - 1 : currentMatch.index - 1; |
| 114 | const newMatch = matches[newIndex]; |
| 115 | scrollToMatch(newMatch); |
| 116 | }, [scrollToMatch, currentMatch, matches]); |
| 117 | |
| 118 | // Handle keyboard shortcuts for navigation |
| 119 | useEffect(() => { |
| 120 | const handleKeyDown = (event: KeyboardEvent) => { |
| 121 | if (event.metaKey && event.key.toLowerCase() === "f" && !event.shiftKey) { |
| 122 | event.preventDefault(); |
| 123 | event.stopPropagation(); |
| 124 | openWidget(); |
| 125 | } else if (document.activeElement === inputRef.current) { |
| 126 | if (event.key === "Escape") { |
| 127 | event.preventDefault(); |
| 128 | event.stopPropagation(); |
| 129 | setOpen(false); |
| 130 | } else if (event.key === "Enter") { |
| 131 | event.preventDefault(); |
| 132 | event.stopPropagation(); |
| 133 | if (event.shiftKey) previousMatch(); |
| 134 | else nextMatch(); |
| 135 | } |
| 136 | } |
| 137 | }; |
| 138 | |
| 139 | document.addEventListener("keydown", handleKeyDown); |
| 140 | return () => { |
| 141 | document.removeEventListener("keydown", handleKeyDown); |
| 142 | }; |
| 143 | }, [inputRef, matches, nextMatch]); |
| 144 | |
| 145 | // Handle container resize changes - highlight positions must adjust |
| 146 | const [isResizing, setIsResizing] = useState(false); |
| 147 | useEffect(() => { |
| 148 | let timeoutId: NodeJS.Timeout | null = null; |
| 149 | if (!searchRef?.current) return; |
| 150 | |
| 151 | const resizeObserver = new ResizeObserver((entries) => { |
| 152 | if (timeoutId) { |
| 153 | clearTimeout(timeoutId); |
| 154 | } |
| 155 | setIsResizing(true); |
| 156 | timeoutId = setTimeout(() => { |
| 157 | setIsResizing(false); |
| 158 | }, RESIZE_DEBOUNCE); |
| 159 | }); |
| 160 | |
| 161 | resizeObserver.observe(searchRef.current); |
| 162 | return () => { |
| 163 | if (timeoutId) { |
| 164 | clearTimeout(timeoutId); |
| 165 | } |
| 166 | if (searchRef.current) resizeObserver.unobserve(searchRef.current); |
| 167 | }; |
| 168 | }, [searchRef.current]); |
| 169 | |
| 170 | // Main function for finding matches and generating highlight overlays |
| 171 | const refreshSearch = useCallback( |
| 172 | (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => { |
| 173 | if (clearFirst) setMatches([]); |
| 174 | |
| 175 | const searchContainer = searchRef.current; |
| 176 | |
| 177 | const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable |
| 178 | if (!searchContainer || !_query) { |
| 179 | setMatches([]); |
| 180 | return; |
| 181 | } |
| 182 | const query = caseSensitive ? _query : _query.toLowerCase(); |
| 183 | |
| 184 | // First grab all text nodes |
| 185 | // Skips any elements with the "find-widget-skip" class |
| 186 | const textNodes: Text[] = []; |
| 187 | const walker = document.createTreeWalker( |
| 188 | searchRef.current, |
| 189 | NodeFilter.SHOW_ALL, |
| 190 | { |
| 191 | acceptNode: (node) => { |
| 192 | if (node.nodeType === Node.ELEMENT_NODE) { |
| 193 | if ((node as Element).classList.contains("find-widget-skip")) |
| 194 | return NodeFilter.FILTER_REJECT; |
| 195 | return NodeFilter.FILTER_ACCEPT; |
| 196 | } else if (node.nodeType === Node.TEXT_NODE) { |
| 197 | if (!node.nodeValue) return NodeFilter.FILTER_REJECT; |
| 198 | const nodeValue = caseSensitive |
| 199 | ? node.nodeValue |
| 200 | : node.nodeValue.toLowerCase(); |
| 201 | if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT; |
| 202 | } |
| 203 | return NodeFilter.FILTER_REJECT; |
| 204 | }, |
| 205 | }, |
| 206 | ); |
| 207 | |
| 208 | while (walker.nextNode()) { |
| 209 | if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue; |
| 210 | textNodes.push(walker.currentNode as Text); |
| 211 | } |
| 212 | |
| 213 | // Now walk through each node match and extract search results |
| 214 | // One node can have several matches |
| 215 | const newMatches: SearchMatch[] = []; |
| 216 | textNodes.forEach((textNode, idx) => { |
| 217 | // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail |
| 218 | const highlightFullLine = |
| 219 | textNode.parentElement?.className.includes("hljs"); |
| 220 | |
| 221 | let nodeTextValue = caseSensitive |
| 222 | ? textNode.nodeValue |
| 223 | : textNode.nodeValue.toLowerCase(); |
| 224 | let startIndex = 0; |
| 225 | while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) { |
| 226 | // Create a range to measure the size and position of the match |
| 227 | const range = document.createRange(); |
| 228 | range.setStart(textNode, startIndex); |
| 229 | const endIndex = startIndex + query.length; |
| 230 | range.setEnd(textNode, endIndex); |
| 231 | const rect = range.getBoundingClientRect(); |
| 232 | range.detach(); |
| 233 | startIndex = endIndex; |
| 234 | |
| 235 | const top = |
| 236 | rect.top + searchContainer.clientTop + searchContainer.scrollTop; |
| 237 | const left = |
| 238 | rect.left + searchContainer.clientLeft + searchContainer.scrollLeft; |
| 239 | |
| 240 | // Build a match result and push to matches |
| 241 | const newMatch: SearchMatch = { |
| 242 | index: 0, // will set later |
| 243 | textNode, |
| 244 | overlayRectangle: { |
| 245 | top, |
| 246 | left: highlightFullLine ? 2 : left, |
| 247 | width: highlightFullLine |
| 248 | ? searchContainer.clientWidth - 4 |
| 249 | : rect.width, // equivalent of adding 2 px x padding |
| 250 | height: rect.height, |
| 251 | }, |
| 252 | }; |
| 253 | newMatches.push(newMatch); |
| 254 | |
| 255 | if (highlightFullLine) { |
| 256 | break; // Since highlighting full line no need for multiple overlays, will cause darker highlight |
| 257 | } |
| 258 | } |
| 259 | }); |
| 260 | |
| 261 | // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) |
| 262 | // Filter them out by using the overlay rectangle as a hash key |
| 263 | const matchHash = Object.fromEntries( |
| 264 | newMatches.map((match) => [ |
| 265 | JSON.stringify(match.overlayRectangle), |
| 266 | match, |
| 267 | ]), |
| 268 | ); |
| 269 | const filteredMatches = Object.values(matchHash).map((match, index) => ({ |
| 270 | ...match, |
| 271 | index, |
| 272 | })); |
| 273 | |
| 274 | // Find match closest to the middle of the view |
| 275 | const verticalMiddle = |
| 276 | searchRef.current.scrollTop + searchRef.current.clientHeight / 2; |
| 277 | let closestDist = Infinity; |
| 278 | let closestMatchToMiddle: SearchMatch | null = null; |
| 279 | filteredMatches.forEach((match) => { |
| 280 | const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); |
| 281 | if (dist < closestDist) { |
| 282 | closestDist = dist; |
| 283 | closestMatchToMiddle = match; |
| 284 | } |
| 285 | }); |
| 286 | |
| 287 | // Update matches and scroll to the closest or first match |
| 288 | setMatches(filteredMatches); |
| 289 | if (query.length > 1 && filteredMatches.length) { |
| 290 | if (scrollTo === "first") { |
| 291 | scrollToMatch(filteredMatches[0]); |
| 292 | } |
| 293 | if (scrollTo === "closest") { |
| 294 | if (closestMatchToMiddle) { |
| 295 | scrollToMatch(closestMatchToMiddle); |
| 296 | } |
| 297 | } |
| 298 | if (scrollTo === "none") { |
| 299 | if (closestMatchToMiddle) { |
| 300 | setCurrentMatch(closestMatchToMiddle); |
| 301 | } else { |
| 302 | setCurrentMatch(filteredMatches[0]); |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | }, |
| 307 | [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex], |
| 308 | ); |
| 309 | |
| 310 | // Triggers that should cause immediate refresh of results to closest search value: |
| 311 | // Input change (debounced) and window click |
| 312 | const lastUpdateRef = useRef(0); |
| 313 | useEffect(() => { |
| 314 | const debounce = () => { |
| 315 | debouncedInput.current = input; |
| 316 | lastUpdateRef.current = Date.now(); |
| 317 | refreshSearch("closest"); |
| 318 | }; |
| 319 | const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; |
| 320 | if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { |
| 321 | debounce(); |
| 322 | } else { |
| 323 | const handler = setTimeout(() => { |
| 324 | debounce(); |
| 325 | }, SEARCH_DEBOUNCE - timeSinceLastUpdate); |
| 326 | return () => { |
| 327 | clearTimeout(handler); |
| 328 | }; |
| 329 | } |
| 330 | }, [refreshSearch, input]); |
| 331 | |
| 332 | // Could consider doing any window click but I only handled search div here |
| 333 | // Since usually only clicks in search div will cause content changes in search div |
| 334 | useEffect(() => { |
| 335 | const searchContainer = searchRef.current; |
| 336 | if (!open || !searchContainer) return; |
| 337 | const handleSearchRefClick = () => { |
| 338 | refreshSearch("none"); |
| 339 | }; |
| 340 | searchContainer.addEventListener("click", handleSearchRefClick); |
| 341 | return () => { |
| 342 | searchContainer.removeEventListener("click", handleSearchRefClick); |
| 343 | }; |
| 344 | }, [searchRef.current, refreshSearch, open]); |
| 345 | |
| 346 | // Triggers that should cause results to temporarily disappear and then reload |
| 347 | // Active = LLM is generating, etc. |
| 348 | const active = useAppSelector((state) => state.session.isStreaming); |
| 349 | |
| 350 | useEffect(() => { |
| 351 | if (active || isResizing) setMatches([]); |
| 352 | else refreshSearch("none"); |
| 353 | }, [refreshSearch, active]); |
| 354 | |
| 355 | useEffect(() => { |
| 356 | if (!open) setMatches([]); |
| 357 | else refreshSearch("closest"); |
| 358 | }, [refreshSearch, open]); |
| 359 | |
| 360 | useEffect(() => { |
| 361 | refreshSearch("closest"); |
| 362 | }, [refreshSearch, caseSensitive, useRegex]); |
| 363 | |
| 364 | // Find widget component |
| 365 | const widget = useMemo(() => { |
| 366 | return ( |
| 367 | <div |
| 368 | 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`} |
| 369 | > |
| 370 | <Input |
| 371 | disabled={active} |
| 372 | type="text" |
| 373 | ref={inputRef} |
| 374 | value={input} |
| 375 | onChange={(e) => { |
| 376 | setInput(e.target.value); |
| 377 | }} |
| 378 | placeholder="Search..." |
| 379 | /> |
| 380 | <p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs"> |
| 381 | {matches.length === 0 |
| 382 | ? "No results" |
| 383 | : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`} |
| 384 | </p> |
| 385 | <div className="hidden flex-row gap-0.5 sm:flex"> |
| 386 | <HeaderButtonWithToolTip |
| 387 | tooltipPlacement="top-end" |
| 388 | text={"Previous Match"} |
| 389 | onClick={(e) => { |
| 390 | e.stopPropagation(); |
| 391 | previousMatch(); |
| 392 | }} |
| 393 | className="h-4 w-4 focus:ring" |
| 394 | disabled={matches.length < 2 || active} |
| 395 | > |
| 396 | <ArrowUpIcon className="h-4 w-4" /> |
| 397 | </HeaderButtonWithToolTip> |
| 398 | <HeaderButtonWithToolTip |
| 399 | tooltipPlacement="top-end" |
| 400 | text={"Next Match"} |
| 401 | onClick={(e) => { |
| 402 | e.stopPropagation(); |
| 403 | nextMatch(); |
| 404 | }} |
| 405 | className="h-4 w-4 focus:ring" |
| 406 | disabled={matches.length < 2 || active} |
| 407 | > |
| 408 | <ArrowDownIcon className="h-4 w-4" /> |
| 409 | </HeaderButtonWithToolTip> |
| 410 | </div> |
| 411 | <HeaderButtonWithToolTip |
| 412 | disabled={active} |
| 413 | inverted={caseSensitive} |
| 414 | tooltipPlacement="top-end" |
| 415 | text={ |
| 416 | caseSensitive |
| 417 | ? "Turn off case sensitivity" |
| 418 | : "Turn on case sensitivity" |
| 419 | } |
| 420 | onClick={(e) => { |
| 421 | e.stopPropagation(); |
| 422 | setCaseSensitive((curr) => !curr); |
| 423 | }} |
| 424 | className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring" |
| 425 | > |
| 426 | Aa |
| 427 | </HeaderButtonWithToolTip> |
| 428 | {/* TODO - add useRegex functionality */} |
| 429 | <HeaderButton |
| 430 | inverted={false} |
| 431 | onClick={() => setOpen(false)} |
| 432 | className="focus:ring" |
| 433 | > |
| 434 | <XMarkIcon className="h-4 w-4" /> |
| 435 | </HeaderButton> |
| 436 | </div> |
| 437 | ); |
| 438 | }, [ |
| 439 | open, |
| 440 | input, |
| 441 | inputRef, |
| 442 | caseSensitive, |
| 443 | matches, |
| 444 | currentMatch, |
| 445 | previousMatch, |
| 446 | nextMatch, |
| 447 | ]); |
| 448 | |
| 449 | // Generate the highlight overlay elements |
| 450 | const highlights = useMemo(() => { |
| 451 | return matches.map((match) => ( |
| 452 | <HighlightOverlay |
| 453 | {...match.overlayRectangle} |
| 454 | isCurrent={currentMatch?.index === match.index} |
| 455 | /> |
| 456 | )); |
| 457 | }, [matches, currentMatch]); |
| 458 | |
| 459 | return { |
| 460 | matches, |
| 461 | highlights, |
| 462 | inputRef, |
| 463 | input: debouncedInput, |
| 464 | setInput, |
| 465 | open, |
| 466 | setOpen, |
| 467 | widget, |
| 468 | }; |
| 469 | }; |