Elffuss BraidHub

kikocis/continue public

WIP: split find widget
Changeset6aa3615da72b410cfbcaf09b6ba9a2960f29d8edcec153e34ecfa12f2e167ffd
AuthorDallin Romney <dallinromney@gmail.com> · 2025-05-23 13:07 -07:00
CommitterDallin Romney <dallinromney@gmail.com> · 2025-05-23 13:07 -07:00
Parents04265f72aa42

Browse the files at this changeset

4 files changed

added gui/src/components/find/FindWidget.test.tsx +105 −0
@@ -0,0 +1,105 @@
1+import { act, fireEvent, render, screen } from "@testing-library/react";
2+import { useRef } from "react";
3+import { useFindWidget } from "./FindWidget";
4+
5+// Test component that uses the find widget
6+const TestComponent = () => {
7+ const searchRef = useRef<HTMLDivElement>(null);
8+ const headerRef = useRef<HTMLDivElement>(null);
9+
10+ const { widget, highlights, open, setOpen } = useFindWidget(
11+ searchRef,
12+ headerRef,
13+ [],
14+ false,
15+ );
16+
17+ return (
18+ <div>
19+ {widget}
20+ <div ref={headerRef} className="header">
21+ Header Content
22+ </div>
23+ <div
24+ ref={searchRef}
25+ className="relative"
26+ style={{ height: "400px", overflow: "auto" }}
27+ >
28+ <p>This is a test paragraph</p>
29+ <p>We can search for content here</p>
30+ <p>Multiple instances of test should work</p>
31+ {highlights}
32+ </div>
33+ <button onClick={() => setOpen(true)}>Open Search</button>
34+ </div>
35+ );
36+};
37+
38+describe("FindWidget", () => {
39+ beforeEach(() => {
40+ // Reset window size and scroll position
41+ window.innerHeight = 768;
42+ window.innerWidth = 1024;
43+ });
44+
45+ it("should open search widget and find matches", async () => {
46+ render(<TestComponent />);
47+
48+ // Open search widget
49+ const openButton = screen.getByText("Open Search");
50+ fireEvent.click(openButton);
51+
52+ // Find search input
53+ const searchInput = screen.getByPlaceholderText("Search...");
54+ expect(searchInput).toBeInTheDocument();
55+
56+ // Type search term
57+ await act(async () => {
58+ fireEvent.change(searchInput, { target: { value: "test" } });
59+ // Wait for debounce
60+ await new Promise((resolve) => setTimeout(resolve, 350));
61+ });
62+
63+ // Check if matches are found (should find 2 instances of "test")
64+ const matchCount = screen.getByText("1 of 2");
65+ expect(matchCount).toBeInTheDocument();
66+
67+ // Test case sensitivity toggle
68+ const caseSensitiveButton = screen.getByText("Aa");
69+ fireEvent.click(caseSensitiveButton);
70+
71+ // Check highlight elements
72+ const highlights = document.querySelectorAll(
73+ ".bg-findMatch\\/50, .bg-findMatch-selected\\/50",
74+ );
75+ expect(highlights.length).toBe(2);
76+ });
77+
78+ it("should navigate between matches", async () => {
79+ render(
80+ // <Provider store={store}>
81+ <TestComponent />,
82+ // </Provider>
83+ );
84+
85+ // Open search and type
86+ fireEvent.click(screen.getByText("Open Search"));
87+ const searchInput = screen.getByPlaceholderText("Search...");
88+
89+ await act(async () => {
90+ fireEvent.change(searchInput, { target: { value: "test" } });
91+ await new Promise((resolve) => setTimeout(resolve, 350));
92+ });
93+
94+ // Find navigation buttons
95+ const nextButton = screen.getByText("Next Match");
96+ const prevButton = screen.getByText("Previous Match");
97+
98+ // Navigate through matches
99+ fireEvent.click(nextButton);
100+ expect(screen.getByText("2 of 2")).toBeInTheDocument();
101+
102+ fireEvent.click(prevButton);
103+ expect(screen.getByText("1 of 2")).toBeInTheDocument();
104+ });
105+});
modified gui/src/components/find/FindWidget.tsx +9 −13
@@ -12,7 +12,6 @@
1212 useState,
1313 } from "react";
1414 import { HeaderButton, Input } from "..";
15-import { useAppSelector } from "../../redux/hooks";
1615 import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
1716
1817 interface SearchMatch {
@@ -67,7 +66,8 @@
6766 export const useFindWidget = (
6867 searchRef: RefObject<HTMLDivElement>,
6968 headerRef: RefObject<HTMLDivElement>,
70- dependencies: React.DependencyList,
69+ refreshDependencies: React.DependencyList,
70+ disabled: boolean,
7171 ) => {
7272 // Search input, debounced
7373 const [input, setInput] = useState<string>("");
@@ -329,7 +329,7 @@
329329 scrollToMatch,
330330 caseSensitive,
331331 useRegex,
332- ...dependencies,
332+ ...refreshDependencies,
333333 ],
334334 );
335335
@@ -369,14 +369,10 @@
369369 };
370370 }, [searchRef, refreshSearch, open]);
371371
372- // Triggers that should cause results to temporarily disappear and then reload
373- // Active = LLM is generating, etc.
374- const active = useAppSelector((state) => state.session.isStreaming);
375-
376372 useEffect(() => {
377- if (active || isResizing) setMatches([]);
373+ if (disabled || isResizing) setMatches([]);
378374 else setTimeout(() => refreshSearch("none"), 300); // this gives plenty of time for resizing to finish
379- }, [refreshSearch, active, isResizing]);
375+ }, [refreshSearch, disabled, isResizing]);
380376
381377 useEffect(() => {
382378 if (!open) setMatches([]);
@@ -394,7 +390,7 @@
394390 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`}
395391 >
396392 <Input
397- disabled={active}
393+ disabled={disabled}
398394 type="text"
399395 ref={inputRef}
400396 value={input}
@@ -417,7 +413,7 @@
417413 previousMatch();
418414 }}
419415 className="h-4 w-4 focus:ring"
420- disabled={matches.length < 2 || active}
416+ disabled={matches.length < 2 || disabled}
421417 >
422418 <ArrowUpIcon className="h-4 w-4" />
423419 </HeaderButtonWithToolTip>
@@ -429,13 +425,13 @@
429425 nextMatch();
430426 }}
431427 className="h-4 w-4 focus:ring"
432- disabled={matches.length < 2 || active}
428+ disabled={matches.length < 2 || disabled}
433429 >
434430 <ArrowDownIcon className="h-4 w-4" />
435431 </HeaderButtonWithToolTip>
436432 </div>
437433 <HeaderButtonWithToolTip
438- disabled={active}
434+ disabled={disabled}
439435 inverted={caseSensitive}
440436 tooltipPlacement="top-end"
441437 text={
added gui/src/components/find/findWidgetSearch.ts +158 −0
@@ -0,0 +1,158 @@
1+export interface SearchMatch {
2+ index: number;
3+ textNode: Text;
4+ overlayRectangle: Rectangle;
5+}
6+
7+
8+const refreshSearch = (scrollTo: ScrollToMatchOption = "none", clearFirst = false) => {
9+ if (clearFirst) setMatches([]);
10+
11+ const searchContainer = searchRef.current;
12+ const header = headerRef.current;
13+
14+ const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable
15+ if (!searchContainer || !_query) {
16+ setMatches([]);
17+ return;
18+ }
19+ const query = caseSensitive ? _query : _query.toLowerCase();
20+
21+ // First grab all text nodes
22+ // Skips any elements with the "find-widget-skip" class
23+ const textNodes: Text[] = [];
24+ const walker = document.createTreeWalker(
25+ searchRef.current,
26+ NodeFilter.SHOW_ALL,
27+ {
28+ acceptNode: (node) => {
29+ if (node.nodeType === Node.ELEMENT_NODE) {
30+ if ((node as Element).classList.contains("find-widget-skip"))
31+ return NodeFilter.FILTER_REJECT;
32+ return NodeFilter.FILTER_ACCEPT;
33+ } else if (node.nodeType === Node.TEXT_NODE) {
34+ if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
35+ const nodeValue = caseSensitive
36+ ? node.nodeValue
37+ : node.nodeValue.toLowerCase();
38+ if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
39+ }
40+ return NodeFilter.FILTER_REJECT;
41+ },
42+ },
43+ );
44+
45+ while (walker.nextNode()) {
46+ if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
47+ textNodes.push(walker.currentNode as Text);
48+ }
49+
50+ // Now walk through each node match and extract search results
51+ // One node can have several matches
52+ const newMatches: SearchMatch[] = [];
53+ textNodes.forEach((textNode, idx) => {
54+ // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
55+ const highlightFullLine =
56+ textNode.parentElement?.className.includes("hljs");
57+
58+ let nodeTextValue = caseSensitive
59+ ? textNode.nodeValue
60+ : textNode.nodeValue.toLowerCase();
61+ let startIndex = 0;
62+ while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
63+ // Create a range to measure the size and position of the match
64+ const range = document.createRange();
65+ range.setStart(textNode, startIndex);
66+ const endIndex = startIndex + query.length;
67+ range.setEnd(textNode, endIndex);
68+ const rect = range.getBoundingClientRect();
69+ range.detach();
70+ startIndex = endIndex;
71+
72+ const headerHeight = header?.clientHeight ?? 0;
73+
74+ const top =
75+ rect.top +
76+ searchContainer.clientTop +
77+ searchContainer.scrollTop -
78+ headerHeight;
79+ const left =
80+ rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
81+
82+ // Build a match result and push to matches
83+ const newMatch: SearchMatch = {
84+ index: 0, // will set later
85+ textNode,
86+ overlayRectangle: {
87+ top,
88+ left: highlightFullLine ? 2 : left,
89+ width: highlightFullLine
90+ ? searchContainer.clientWidth - 4
91+ : rect.width, // equivalent of adding 2 px x padding
92+ height: rect.height,
93+ },
94+ };
95+ newMatches.push(newMatch);
96+
97+ if (highlightFullLine) {
98+ break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
99+ }
100+ }
101+ });
102+
103+ // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
104+ // Filter them out by using the overlay rectangle as a hash key
105+ const matchHash = Object.fromEntries(
106+ newMatches.map((match) => [
107+ JSON.stringify(match.overlayRectangle),
108+ match,
109+ ]),
110+ );
111+ const filteredMatches = Object.values(matchHash).map((match, index) => ({
112+ ...match,
113+ index,
114+ }));
115+
116+ // Find match closest to the middle of the view
117+ const verticalMiddle =
118+ searchRef.current.scrollTop + searchRef.current.clientHeight / 2;
119+ let closestDist = Infinity;
120+ let closestMatchToMiddle: SearchMatch | null = null;
121+ filteredMatches.forEach((match) => {
122+ const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
123+ if (dist < closestDist) {
124+ closestDist = dist;
125+ closestMatchToMiddle = match;
126+ }
127+ });
128+
129+ // Update matches and scroll to the closest or first match
130+ setMatches(filteredMatches);
131+ if (query.length > 1 && filteredMatches.length) {
132+ if (scrollTo === "first") {
133+ scrollToMatch(filteredMatches[0]);
134+ }
135+ if (scrollTo === "closest") {
136+ if (closestMatchToMiddle) {
137+ scrollToMatch(closestMatchToMiddle);
138+ }
139+ }
140+ if (scrollTo === "none") {
141+ if (closestMatchToMiddle) {
142+ setCurrentMatch(closestMatchToMiddle);
143+ } else {
144+ setCurrentMatch(filteredMatches[0]);
145+ }
146+ }
147+ }
148+ },
149+ [
150+ headerRef,
151+ searchRef,
152+ debouncedInput,
153+ scrollToMatch,
154+ caseSensitive,
155+ useRegex,
156+ ...refreshDependencies,
157+ ],
158+}
No newline at the end of the file
modified gui/src/pages/gui/Chat.tsx +6 −1
@@ -153,7 +153,12 @@
153153 };
154154 }, [isStreaming, jetbrains]);
155155
156- const { widget, highlights } = useFindWidget(stepsDivRef, tabsRef, [history]);
156+ const { widget, highlights } = useFindWidget(
157+ stepsDivRef,
158+ tabsRef,
159+ [history],
160+ isStreaming,
161+ );
157162
158163 const currentToolCallApplyState = useAppSelector(
159164 selectCurrentToolCallApplyState,