diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts
index 80a183764..ad8dc0b3b 100644
--- a/extensions/vscode/src/commands.ts
+++ b/extensions/vscode/src/commands.ts
@@ -603,7 +603,6 @@ const commandsMap: (
vscode.ViewColumn.One,
{
retainContextWhenHidden: true,
- enableFindWidget: true
},
);
fullScreenPanel = panel;
diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx
index 0a18155c4..bc4f3f7ef 100644
--- a/gui/src/components/find/FindWidget.tsx
+++ b/gui/src/components/find/FindWidget.tsx
@@ -4,21 +4,119 @@ import { useSelector } from 'react-redux';
import { Button, HeaderButton, Input } from '..';
import useWindowSize from '../../hooks/useWindowSize';
import ButtonWithTooltip from '../ButtonWithTooltip';
-import { XMarkIcon } from '@heroicons/react/24/outline';
+import { ArrowDownIcon, ArrowUpIcon, XMarkIcon } from '@heroicons/react/24/outline';
interface SearchMatch {
- isCurrent: boolean;
+ index: number;
textNode: Text
- overlayNode: JSX.Element;
+ overlayRectangle: Rectangle;
+}
+
+const SEARCH_DEBOUNCE = 500
+
+interface Rectangle {
+ top: number;
+ left: number;
+ width: number;
+ height: number;
+}
+interface HighlightOverlayProps extends Rectangle {
+ isCurrent: boolean;
+}
+
+const HighlightOverlay = (props: HighlightOverlayProps) => {
+ const { isCurrent, top, left, width, height } = props;
+ return (
+
+ )
}
-const SEARCH_DEBOUNCE = 300
export const useFindWidget = (searchRef: RefObject) => {
// Search input
- // const [currentIndex, setCurrentIndex] = useState(0);
+ const [currentMatch, setCurrentMatch] = useState();
+
+
+
+
+ // Handle container resizing
+ const [isResizing, setIsResizing] = useState(false);
+ useEffect(() => {
+ let timeoutId: NodeJS.Timeout | null = null;
+ const handleResize = () => {
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+ setIsResizing(true);
+ timeoutId = setTimeout(() => {
+ setIsResizing(false)
+ }, 200);
+ };
+
+ window.addEventListener('resize', handleResize);
+ return () => {
+ if (timeoutId) {
+ clearTimeout(timeoutId);
+ }
+ window.removeEventListener('resize', handleResize);
+ };
+ }, [200]);
+
+ // useEffect(() => {
+ // if (!searchRef.current) return
+ // let timeoutId: NodeJS.Timeout | null = null;
+
+ // // const handleResize = () => {
+ // // if (timeoutId) {
+ // // clearTimeout(timeoutId);
+ // // }
+ // // setIsMutating(true);
+
+ // // timeoutId = setTimeout(() => {
+ // // setIsMutating(false)
+ // // }, 200);
+ // // };
+ // const observer = new MutationObserver(mutations => {
+ // if (timeoutId) {
+ // clearTimeout(timeoutId);
+ // }
+ // setIsMutating(true);
+
+ // timeoutId = setTimeout(() => {
+ // setIsMutating(false)
+ // }, 200);
+ // // mutations.forEach(mutation => {
+
+ // // });
+ // });
+ // observer.observe(searchRef.current, {
+ // // characterData: true,
+ // // childList: true,
+ // attributes: true
+ // })
+ // return () => {
+ // if (timeoutId) {
+ // clearTimeout(timeoutId);
+ // }
+ // observer.disconnect();
+ // };
+ // }, [searchRef.current]);
+
+
+
+
- const { isResizing } = useWindowSize(200)
- // console.log(isResizing)
const inputRef = useRef(null) as RefObject;
const [input, setInput] = useState("");
@@ -47,16 +145,26 @@ export const useFindWidget = (searchRef: RefObject) => {
const [caseSensitive, setCaseSensitive] = useState(false);
const [useRegex, setUseRegex] = useState(false);
-
const active = useSelector((state: RootState) => state.state.active);
const [matches, setMatches] = useState([]);
- const loadHighlights = useCallback((query: string | undefined) => {
- if (!searchRef.current || !query) {
+ const scrollToMatch = useCallback((match: SearchMatch) => {
+ setCurrentMatch(match)
+ searchRef.current.scrollTo({
+ top: match.overlayRectangle.top - searchRef.current.clientHeight / 2,
+ left: match.overlayRectangle.left - searchRef.current.clientWidth / 2,
+ behavior: 'smooth'
+ })
+ }, [searchRef.current])
+
+ const loadHighlights = useCallback((_query: string | undefined, scrollTo: 'first' | 'closest' | 'none' = 'none') => {
+ if (!searchRef.current || !_query) {
setMatches([]);
return;
};
+ const query = caseSensitive ? _query : _query.toLowerCase()
+
const textNodes: Text[] = [];
const start = Date.now()
const walker = document.createTreeWalker(
@@ -69,9 +177,10 @@ export const useFindWidget = (searchRef: RefObject) => {
return NodeFilter.FILTER_ACCEPT;
} else if (node.nodeType === Node.TEXT_NODE) {
if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
- if (node.nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
+ const nodeValue = caseSensitive ? node.nodeValue : node.nodeValue.toLowerCase()
+ if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
}
- else return NodeFilter.FILTER_REJECT
+ return NodeFilter.FILTER_REJECT
}
}
);
@@ -81,95 +190,111 @@ export const useFindWidget = (searchRef: RefObject) => {
textNodes.push(walker.currentNode as Text);
}
-
const newMatches: SearchMatch[] = [];
- let isFirst = true
- textNodes.forEach(textNode => {
- let nodeTextValue = textNode.nodeValue || '';
- let startIndex = 0;
+ let index = 0;
+ // For finding closest match
+ const verticalMiddle = searchRef.current.scrollTop + searchRef.current.clientHeight / 2
+ let closestDist = Infinity
+ let closestMatchToMiddle: SearchMatch | null = null
+
+ textNodes.forEach(textNode => {
+ let nodeTextValue = caseSensitive ? textNode.nodeValue : textNode.nodeValue.toLowerCase();
+ let startIndex = 0;
while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
// Create a range to measure the size and position of the match
- // if(textNode.)
const range = document.createRange();
range.setStart(textNode, startIndex);
range.setEnd(textNode, startIndex + query.length);
const rect = range.getBoundingClientRect();
+ const top = rect.top + searchRef.current.clientTop + searchRef.current.scrollTop
+ const left = rect.left + searchRef.current.clientLeft + searchRef.current.scrollLeft;
- const overlayNode =
+ // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
+ const highlightFullLine = textNode.parentElement.className.includes('hljs')
- // Create an overlay element
- newMatches.push({
- isCurrent: isFirst,
+ const newMatch: SearchMatch = {
+ index,
textNode,
- overlayNode
- });
- isFirst = false
+ overlayRectangle: {
+ top,
+ left: highlightFullLine ? 2 : left,
+ width: highlightFullLine ? (searchRef.current.clientWidth - 4) : rect.width,
+ height: rect.height,
+ }
+ }
+ newMatches.push(newMatch);
+ const dist = Math.abs(verticalMiddle - top);
+ if (dist < closestDist) {
+ closestDist = dist;
+ closestMatchToMiddle = newMatch
+ }
+
+ index++;
startIndex += query.length; // Move past this match
range.detach();
}
});
console.log(`Found ${textNodes.length} nodes in ${Date.now() - start}ms`);
setMatches(newMatches);
- }, [searchRef.current, setMatches])
+ if (query.length > 1 && newMatches.length) {
+ if (scrollTo === 'first') {
+ scrollToMatch(newMatches[0]);
+ }
+ if (scrollTo === 'closest' && closestMatchToMiddle) {
+ scrollToMatch(closestMatchToMiddle)
+ }
+ }
+ }, [searchRef.current, caseSensitive, useRegex, scrollToMatch])
useEffect(() => {
if (active || !open || isResizing) setMatches([])
- else loadHighlights(debouncedInput);
- }, [debouncedInput, loadHighlights, active, open, useRegex, caseSensitive, isResizing]);
+ else loadHighlights(debouncedInput, 'closest');
+ }, [debouncedInput, loadHighlights, active, open, isResizing]);
- // const selectMatch = (index: number) => {
- // if (!highlightedNodes.length) return;
- // highlightedNodes[currentIndex].className = 'find-highlight';
-
- // const newIndex = (index + highlightedNodes.length) % highlightedNodes.length;
- // setCurrentIndex(newIndex);
-
- // const currentNode = highlightedNodes[newIndex];
- // if (currentNode) {
- // currentNode.className = 'find-highlight-selected';
- // currentNode.scrollIntoView({ behavior: 'smooth', block: 'center' });
- // }
- // }
-
- // const nextMatch = () => selectMatch(currentIndex + 1);
- // const previousMatch = () => selectMatch(currentIndex - 1);
-
// Widget settings
// Manage widget opened/close state
const openWidget = useCallback(() => {
setOpen(true);
- inputRef?.current.focus()
+ inputRef?.current.select()
}, [setOpen, inputRef])
+ const nextMatch = useCallback(() => {
+ if (matches.length === 0) return
+ const newIndex = (currentMatch.index + 1) % matches.length;
+ const newMatch = matches[newIndex]
+ scrollToMatch(newMatch)
+ }, [scrollToMatch, currentMatch, matches])
+
+ const previousMatch = useCallback(() => {
+ if (matches.length === 0) return
+ const newIndex = currentMatch.index === 0 ? matches.length - 1 : currentMatch.index - 1
+ const newMatch = matches[newIndex]
+ scrollToMatch(newMatch)
+ }, [scrollToMatch, currentMatch, matches])
+
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.metaKey && event.key.toLowerCase() === 'f') {
event.preventDefault();
event.stopPropagation();
openWidget();
- } else if (event.key === 'Escape') {
- event.preventDefault();
- event.stopPropagation();
- setOpen(false);
+ } else if (document.activeElement === inputRef.current) {
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ event.stopPropagation();
+ setOpen(false);
+ } else if (event.key === 'Enter') {
+ event.preventDefault();
+ event.stopPropagation();
+ if (event.shiftKey) previousMatch()
+ else nextMatch()
+ }
}
}
@@ -177,11 +302,11 @@ export const useFindWidget = (searchRef: RefObject) => {
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
- }, []);
+ }, [inputRef, matches, nextMatch]);
const widget = (
) => {
}}
placeholder="Search..."
/>
-
- {/*
-
*/}
+
+ {matches.length === 0 ? "No results" : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
+
+
setCaseSensitive(curr => !curr)}
- className='h-5 w-5'
+ className='h-4 w-4 text-xs'
>
Aa
- {/* */}
-
+ */}
setOpen(false)}
- // className='h-5 w-5'
>
- {/* */}
)
+ const highlights = matches.map(match => )
+
return {
matches,
- highlights: matches.map(match => match.overlayNode),
+ highlights,
inputRef,
input: debouncedInput,
setInput,
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx
index 0ba3a2af0..a40268151 100644
--- a/gui/src/pages/gui/Chat.tsx
+++ b/gui/src/pages/gui/Chat.tsx
@@ -196,9 +196,11 @@ export function Chat() {
setIsAtBottom(atBottom);
};
+ const { widget, highlights, setOpen: setFindWidgetOpen } = useFindWidget(stepsDivRef)
const sendInput = useCallback(
(editorState: JSONContent, modifiers: InputModifiers) => {
+ setFindWidgetOpen(false)
if (defaultModel?.provider === "free-trial") {
const u = getLocalStorage("ftc");
if (u) {
@@ -296,6 +298,7 @@ export function Chat() {
defaultModel,
state,
streamResponse,
+ setFindWidgetOpen
],
);
@@ -317,19 +320,17 @@ export function Chat() {
[state.history],
);
- // const { widget, highlights } = useFindWidget(stepsDivRef)
-
const showScrollbar = state.config.ui?.showChatScrollbar || false
return (
<>
- {/* {widget} */}
+ {widget}
0 ? "h-full" : ""}`}
onScroll={handleScroll}
>
- {/* {highlights} */}
+ {highlights}
{state.history.map((item, index: number) => (