From 979c2473c61747157e65e1dcd33fd73ccfe404ad Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 6 Nov 2024 20:35:29 -0800 Subject: [PATCH 01/20] feat: collapsed codeblock by default --- core/protocol/index.ts | 8 ++--- .../components/markdown/CodeBlockToolbar.tsx | 30 +++++++++++++++---- .../components/markdown/PreWithToolbar.tsx | 13 +++++++- 3 files changed, 40 insertions(+), 11 deletions(-) diff --git a/core/protocol/index.ts b/core/protocol/index.ts index 495c2fb90..522b52934 100644 --- a/core/protocol/index.ts +++ b/core/protocol/index.ts @@ -1,13 +1,13 @@ import { ToCoreFromWebviewProtocol, ToWebviewFromCoreProtocol, -} from "./coreWebview.js"; -import { ToWebviewOrCoreFromIdeProtocol } from "./ide.js"; -import { ToCoreFromIdeProtocol, ToIdeFromCoreProtocol } from "./ideCore.js"; +} from "./coreWebview"; +import { ToWebviewOrCoreFromIdeProtocol } from "./ide"; +import { ToCoreFromIdeProtocol, ToIdeFromCoreProtocol } from "./ideCore"; import { ToIdeFromWebviewProtocol, ToWebviewFromIdeProtocol, -} from "./ideWebview.js"; +} from "./ideWebview"; export type IProtocol = Record; diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index ac4c03bb2..74c8f46c0 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -5,6 +5,7 @@ import { CommandLineIcon, PlayIcon, XMarkIcon, + ChevronDownIcon, } from "@heroicons/react/24/outline"; import { getBasename } from "core/util"; import { useContext, useRef, useState } from "react"; @@ -87,6 +88,8 @@ interface CodeBlockToolBarProps { language: string | undefined; isNextCodeBlock: boolean; filepath?: string; + isExpanded: boolean; + onToggleExpand: () => void; } const terminalLanguages = ["bash", "sh"]; @@ -260,12 +263,27 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { return ( -
- - {getBasename(props.filepath)} +
+
+ +
+ + {props.filepath && ( +
+ + {getBasename(props.filepath)} +
+ )}
diff --git a/gui/src/components/markdown/PreWithToolbar.tsx b/gui/src/components/markdown/PreWithToolbar.tsx index ec9297d54..2f592ea9e 100644 --- a/gui/src/components/markdown/PreWithToolbar.tsx +++ b/gui/src/components/markdown/PreWithToolbar.tsx @@ -42,6 +42,7 @@ function PreWithToolbar(props: { const [hovering, setHovering] = useState(false); const [copyValue, setCopyValue] = useState(""); + const [isExpanded, setIsExpanded] = useState(false); const nextCodeBlockIndex = useSelector( (state: RootState) => state.uiState.nextCodeBlockToApplyIndex, @@ -76,6 +77,8 @@ function PreWithToolbar(props: { bottom={toolbarBottom} language={props.language} filepath={props.filepath} + isExpanded={isExpanded} + onToggleExpand={() => setIsExpanded(!isExpanded)} /> ) : ( hovering && ( @@ -84,11 +87,19 @@ function PreWithToolbar(props: { text={copyValue} bottom={toolbarBottom} language={props.language} + isExpanded={isExpanded} + onToggleExpand={() => setIsExpanded(!isExpanded)} /> ) )} - {props.children} +
+ {props.children} +
); } From 39337910f125a71414cf2c39b96250fc512777be Mon Sep 17 00:00:00 2001 From: Test Date: Fri, 8 Nov 2024 09:10:41 -0800 Subject: [PATCH 02/20] feat: update PreToolbar --- .../src/ContinueGUIWebviewViewProvider.ts | 17 - .../{markdown => gui}/CopyButton.tsx | 0 gui/src/components/gui/StepContainer.tsx | 26 +- .../components/markdown/CodeBlockToolbar.tsx | 372 ------------------ .../markdown/CodeSnippetPreview.tsx | 7 +- gui/src/components/markdown/FilenameLink.tsx | 6 +- .../StepContainerPreToolbar/ApplyButton.tsx | 52 +++ .../AutoApplyStatusIndicators.tsx | 46 +++ .../CodeBlockActions.tsx | 106 +++++ .../CodeBlockToolbar(OLD).tsx | 119 ++++++ .../StepContainerPreToolbar/FileInfo.tsx | 55 +++ .../PreWithToolbar_OLD.tsx} | 15 +- .../StepContainerPreToolbar/Spinner.tsx | 27 ++ .../StepContainerPreToolbar.tsx | 177 +++++++++ .../ToolbarButtonWithTooltip.tsx | 4 +- .../markdown/StepContainerPreToolbar/index.ts | 1 + .../markdown/StepContainerPreToolbar/utils.ts | 54 +++ .../markdown/StyledMarkdownPreview.tsx | 67 +++- .../markdown/SyntaxHighlightedPre.tsx | 30 +- .../components/markdown/VSCodeFileLink.tsx | 18 - .../pages/AddNewModel/ConfigureProvider.tsx | 10 +- gui/src/pages/stats.tsx | 2 +- gui/tailwind.config.cjs | 2 +- 23 files changed, 739 insertions(+), 474 deletions(-) rename gui/src/components/{markdown => gui}/CopyButton.tsx (100%) delete mode 100644 gui/src/components/markdown/CodeBlockToolbar.tsx create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/ApplyButton.tsx create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/AutoApplyStatusIndicators.tsx create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/CodeBlockActions.tsx create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/CodeBlockToolbar(OLD).tsx create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/FileInfo.tsx rename gui/src/components/markdown/{PreWithToolbar.tsx => StepContainerPreToolbar/PreWithToolbar_OLD.tsx} (86%) create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/Spinner.tsx create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx rename gui/src/components/markdown/{ => StepContainerPreToolbar}/ToolbarButtonWithTooltip.tsx (86%) create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/index.ts create mode 100644 gui/src/components/markdown/StepContainerPreToolbar/utils.ts delete mode 100644 gui/src/components/markdown/VSCodeFileLink.tsx diff --git a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts index a923ca422..9f3b0095c 100644 --- a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts +++ b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts @@ -182,23 +182,6 @@ export class ContinueGUIWebviewViewProvider
- - ${``} ${ inDevelopmentMode ? ``} - ${ - inDevelopmentMode - ? `` - : "" - } + : "" + } @@ -222,17 +220,16 @@ export class ContinueGUIWebviewViewProvider + vscode.workspace.workspaceFolders?.map( + (folder) => folder.uri.fsPath, + ) || [], + )} - ${ - edits - ? `` - : "" - } + ${edits + ? `` + : "" + } ${page ? `` : ""} `; diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 27b4f5202..0ab40cb03 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -228,7 +228,7 @@ const Layout = () => { message={dialogMessage} /> - + diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index a113c7ea0..36adc1f50 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -1,17 +1,19 @@ -import React, { useRef, useEffect, useState, RefObject, useCallback, useMemo } from 'react'; +import { useRef, useEffect, useState, RefObject, useCallback, useMemo } from 'react'; import { RootState } from '../../redux/store'; import { useSelector } from 'react-redux'; -import { Button, HeaderButton, Input } from '..'; +import { HeaderButton, Input } from '..'; import ButtonWithTooltip from '../ButtonWithTooltip'; import { ArrowDownIcon, ArrowUpIcon, XMarkIcon } from '@heroicons/react/24/outline'; interface SearchMatch { index: number; - textNode: Text + textNode: Text; overlayRectangle: Rectangle; } -const SEARCH_DEBOUNCE = 500 +type ScrollToMatchOption = 'closest' | 'first' | 'none' + +const SEARCH_DEBOUNCE = 300 const RESIZE_DEBOUNCE = 200 interface Rectangle { @@ -20,6 +22,8 @@ interface Rectangle { width: number; height: number; } + + interface HighlightOverlayProps extends Rectangle { isCurrent: boolean; } @@ -52,30 +56,10 @@ const HighlightOverlay = (props: HighlightOverlayProps) => { Container must have relative positioning */ export const useFindWidget = (searchRef: RefObject) => { - // Used to disable search when chat is loading - const active = useSelector((state: RootState) => state.state.active); - // Search input, debounced const [input, setInput] = useState(""); - const [debouncedInput, setDebouncedInput] = useState(""); - const inputRef = useRef(null) as RefObject; - const lastUpdateRef = useRef(0); - - useEffect(() => { - const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; - if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { - setDebouncedInput(input); - lastUpdateRef.current = Date.now(); - } else { - const handler = setTimeout(() => { - setDebouncedInput(input); - lastUpdateRef.current = Date.now(); - }, SEARCH_DEBOUNCE - timeSinceLastUpdate); - return () => { - clearTimeout(handler); - }; - } - }, [input]); + const debouncedInput = useRef("") + const inputRef = useRef(null) // Widget open/closed state const [open, setOpen] = useState(false); @@ -147,7 +131,9 @@ export const useFindWidget = (searchRef: RefObject) => { const [isResizing, setIsResizing] = useState(false); useEffect(() => { let timeoutId: NodeJS.Timeout | null = null; - const handleResize = () => { + if (!searchRef?.current) return; + + const resizeObserver = new ResizeObserver(entries => { if (timeoutId) { clearTimeout(timeoutId); } @@ -155,27 +141,30 @@ export const useFindWidget = (searchRef: RefObject) => { timeoutId = setTimeout(() => { setIsResizing(false) }, RESIZE_DEBOUNCE); - }; + }); - window.addEventListener('resize', handleResize); + resizeObserver.observe(searchRef.current); return () => { if (timeoutId) { clearTimeout(timeoutId); } - window.removeEventListener('resize', handleResize); + if (searchRef.current) resizeObserver.unobserve(searchRef.current); }; - }, []); + }, [searchRef.current]); - // The bread and butter: - // - const loadHighlights = useCallback((_query: string | undefined, scrollTo: 'first' | 'closest' | 'none' = 'none') => { + // Main function for finding matches and generating highlight overlays + const refreshSearch = useCallback((scrollTo: ScrollToMatchOption = 'none', clearFirst = false) => { + if (clearFirst) setMatches([]) + + const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable if (!searchRef.current || !_query) { setMatches([]); return; }; const query = caseSensitive ? _query : _query.toLowerCase() - // First grab all text nodes, skipping any elements with the 'find-widget-skip' class + // First grab all text nodes + // Skips any elements with the 'find-widget-skip' class const textNodes: Text[] = []; const walker = document.createTreeWalker( searchRef.current, @@ -200,71 +189,126 @@ export const useFindWidget = (searchRef: RefObject) => { textNodes.push(walker.currentNode as Text); } - // Keep track of the match closest to the middle of the screen + // Keep track of the match closest match to the middle of the view const verticalMiddle = searchRef.current.scrollTop + searchRef.current.clientHeight / 2 let closestDist = Infinity let closestMatchToMiddle: SearchMatch | null = null // Now walk through each node match and extract search results // One node can have several matches - let index = 0; const newMatches: SearchMatch[] = []; - textNodes.forEach(textNode => { + textNodes.forEach((textNode, idx) => { + // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail + const highlightFullLine = textNode.parentElement.className.includes('hljs') + 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 const range = document.createRange(); range.setStart(textNode, startIndex); - range.setEnd(textNode, startIndex + query.length); - + const endIndex = startIndex + query.length + range.setEnd(textNode, endIndex); const rect = range.getBoundingClientRect(); + range.detach(); + startIndex = endIndex; + const top = rect.top + searchRef.current.clientTop + searchRef.current.scrollTop const left = rect.left + searchRef.current.clientLeft + searchRef.current.scrollLeft; - // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail - const highlightFullLine = textNode.parentElement.className.includes('hljs') - + // Build a match result and push to matches const newMatch: SearchMatch = { - index, + index: 0, // will set later textNode, overlayRectangle: { top, left: highlightFullLine ? 2 : left, - width: highlightFullLine ? (searchRef.current.clientWidth - 4) : rect.width, + width: highlightFullLine ? (searchRef.current.clientWidth - 4) : rect.width, // equivalent of adding 2 px x padding height: rect.height, - } + }, } newMatches.push(newMatch); + // Keep track of the match closest match to the middle of the view const dist = Math.abs(verticalMiddle - top); if (dist < closestDist) { closestDist = dist; closestMatchToMiddle = newMatch } - index++; - startIndex += query.length; - range.detach(); + if (highlightFullLine) { + break; // Since highlighting full line no need for multiple overlays, will cause darker highlight + } } }); - setMatches(newMatches); - if (query.length > 1 && newMatches.length) { + // There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights) + // Filter them out by using the overlay rectangle as a hash key + const matchHash = Object.fromEntries(newMatches.map(match => [JSON.stringify(match.overlayRectangle), match])) + const filteredMatches = Object.values(matchHash).map((match, index) => ({ ...match, index })); + + // Update matches and scroll to the closest or first match + setMatches(filteredMatches); + if (query.length > 1 && filteredMatches.length) { + // console.log(scrollTo) if (scrollTo === 'first') { - scrollToMatch(newMatches[0]); + scrollToMatch(filteredMatches[0]); } if (scrollTo === 'closest' && closestMatchToMiddle) { scrollToMatch(closestMatchToMiddle) } } - }, [searchRef.current, caseSensitive, useRegex, scrollToMatch]) + }, [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex]) - // Trigger searches or clearing results on state changes + // Triggers that should cause immediate refresh of results to closest search value: + // Input change (debounced) and window click + const lastUpdateRef = useRef(0); useEffect(() => { - if (active || !open || isResizing) setMatches([]) - else loadHighlights(debouncedInput, 'closest'); - }, [debouncedInput, loadHighlights, active, open, isResizing]); + const debounce = () => { + debouncedInput.current = input + lastUpdateRef.current = Date.now(); + refreshSearch('closest'); + } + const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; + if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { + debounce() + } else { + const handler = setTimeout(() => { + debounce() + }, SEARCH_DEBOUNCE - timeSinceLastUpdate); + return () => { + clearTimeout(handler); + }; + } + }, [refreshSearch, input]); + + useEffect(() => { + if (!open) return + const handleWindowClick = () => { + refreshSearch('none'); + } + window.addEventListener('click', handleWindowClick) + return () => { + window.removeEventListener('click', handleWindowClick); + }; + }, [refreshSearch, open]); + + // Triggers that should cause results to temporarily disappear and then reload + // Active = LLM is generating, etc. + const active = useSelector((state: RootState) => state.state.active); + useEffect(() => { + if (active || isResizing) setMatches([]) + else refreshSearch('none') + }, [refreshSearch, active]); + + useEffect(() => { + if (!open) setMatches([]) + else refreshSearch('closest') + }, [refreshSearch, open]); + + useEffect(() => { + refreshSearch('closest') + }, [refreshSearch, caseSensitive, useRegex]) // Find widget component const widget = useMemo(() => { @@ -281,15 +325,19 @@ export const useFindWidget = (searchRef: RefObject) => { }} placeholder="Search..." /> -

+

{matches.length === 0 ? "No results" : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}

{ + e.stopPropagation() + // e.preventDefault() + previousMatch() + }} + className='h-4 w-4 focus:ring focus:ring-1' disabled={matches.length < 2} > @@ -297,8 +345,12 @@ export const useFindWidget = (searchRef: RefObject) => { { + e.stopPropagation() + // e.preventDefault() + nextMatch() + }} + className='h-4 w-4 focus:ring focus:ring-1' disabled={matches.length < 2} > @@ -308,8 +360,12 @@ export const useFindWidget = (searchRef: RefObject) => { inverted={caseSensitive} tooltipPlacement="top-end" text={caseSensitive ? "Turn off case sensitivity" : "Turn on case sensitivity"} - onClick={() => setCaseSensitive(curr => !curr)} - className='h-4 w-4 text-xs' + onClick={(e) => { + e.stopPropagation() + // e.preventDefault() + setCaseSensitive(curr => !curr) + }} + className='h-5 w-6 text-xs focus:ring focus:ring-1 rounded-full border focus:outline-none' > Aa @@ -317,6 +373,7 @@ export const useFindWidget = (searchRef: RefObject) => { setOpen(false)} + className='focus:ring focus:ring-1' > diff --git a/gui/src/components/markdown/CodeBlockToolbar.tsx b/gui/src/components/markdown/CodeBlockToolbar.tsx index c9eef3470..59e518093 100644 --- a/gui/src/components/markdown/CodeBlockToolbar.tsx +++ b/gui/src/components/markdown/CodeBlockToolbar.tsx @@ -262,7 +262,7 @@ function CodeBlockToolBar(props: CodeBlockToolBarProps) { return (
diff --git a/gui/src/components/markdown/CodeSnippetPreview.tsx b/gui/src/components/markdown/CodeSnippetPreview.tsx index 3c783c59a..1ad86df06 100644 --- a/gui/src/components/markdown/CodeSnippetPreview.tsx +++ b/gui/src/components/markdown/CodeSnippetPreview.tsx @@ -49,7 +49,7 @@ interface CodeSnippetPreviewProps { editing?: boolean; } -const StyledHeaderButtonWithText = styled(ButtonWithTooltip)<{ +const StyledHeaderButtonWithText = styled(ButtonWithTooltip) <{ color?: string; }>` ${(props) => props.color && `background-color: ${props.color};`} @@ -81,6 +81,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) { onMouseEnter={() => setHovered(true)} onMouseLeave={() => setHovered(false)} borderColor={props.borderColor} + className="find-widget-skip" >
- {collapsed ? ( - setCollapsed(false)} - /> - ) : ( - setCollapsed(true)} - /> - )} + setCollapsed(curr => !curr)} + style={{ + rotate: collapsed ? '' : '180deg' + }} + /> )} diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index a40268151..2cbee06db 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -163,7 +163,7 @@ export function Chat() { useEffect(() => { setTimeout(() => { smoothScrollToBottom(); - }, 250) + }, 400) }, [smoothScrollToBottom, state.sessionId]); useEffect(() => { @@ -196,11 +196,10 @@ export function Chat() { setIsAtBottom(atBottom); }; - const { widget, highlights, setOpen: setFindWidgetOpen } = useFindWidget(stepsDivRef) + const { widget, highlights } = useFindWidget(stepsDivRef) const sendInput = useCallback( (editorState: JSONContent, modifiers: InputModifiers) => { - setFindWidgetOpen(false) if (defaultModel?.provider === "free-trial") { const u = getLocalStorage("ftc"); if (u) { @@ -298,7 +297,6 @@ export function Chat() { defaultModel, state, streamResponse, - setFindWidgetOpen ], ); diff --git a/gui/src/pages/gui/index.tsx b/gui/src/pages/gui/index.tsx index 7dcb2e55e..31784a358 100644 --- a/gui/src/pages/gui/index.tsx +++ b/gui/src/pages/gui/index.tsx @@ -4,10 +4,10 @@ import { Chat } from "./Chat"; export default function GUI() { return (
-
From ad2ac1db667df3d76d5b17400f779e7c5d1279fc Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 10 Nov 2024 23:15:52 -0800 Subject: [PATCH 19/20] find widget behavior tweaks --- gui/src/components/find/FindWidget.tsx | 128 +++++++++++++------------ 1 file changed, 67 insertions(+), 61 deletions(-) diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index 36adc1f50..c3fb37ef9 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -1,9 +1,9 @@ -import { useRef, useEffect, useState, RefObject, useCallback, useMemo } from 'react'; -import { RootState } from '../../redux/store'; -import { useSelector } from 'react-redux'; -import { HeaderButton, Input } from '..'; -import ButtonWithTooltip from '../ButtonWithTooltip'; -import { ArrowDownIcon, ArrowUpIcon, XMarkIcon } from '@heroicons/react/24/outline'; +import { useRef, useEffect, useState, RefObject, useCallback, useMemo } from "react"; +import { RootState } from "../../redux/store"; +import { useSelector } from "react-redux"; +import { HeaderButton, Input } from ".."; +import ButtonWithTooltip from "../ButtonWithTooltip"; +import { ArrowDownIcon, ArrowUpIcon, XMarkIcon } from "@heroicons/react/24/outline"; interface SearchMatch { index: number; @@ -11,7 +11,7 @@ interface SearchMatch { overlayRectangle: Rectangle; } -type ScrollToMatchOption = 'closest' | 'first' | 'none' +type ScrollToMatchOption = "closest" | "first" | "none" const SEARCH_DEBOUNCE = 300 const RESIZE_DEBOUNCE = 200 @@ -23,7 +23,6 @@ interface Rectangle { height: number; } - interface HighlightOverlayProps extends Rectangle { isCurrent: boolean; } @@ -32,15 +31,15 @@ const HighlightOverlay = (props: HighlightOverlayProps) => { const { isCurrent, top, left, width, height } = props; return (
@@ -82,7 +81,7 @@ export const useFindWidget = (searchRef: RefObject) => { searchRef.current.scrollTo({ top: match.overlayRectangle.top - searchRef.current.clientHeight / 2, left: match.overlayRectangle.left - searchRef.current.clientWidth / 2, - behavior: 'smooth' + behavior: "smooth" }) }, [searchRef.current]) @@ -103,16 +102,16 @@ export const useFindWidget = (searchRef: RefObject) => { // Handle keyboard shortcuts for navigation useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { - if (event.metaKey && event.key.toLowerCase() === 'f') { + if (event.metaKey && event.key.toLowerCase() === "f") { event.preventDefault(); event.stopPropagation(); openWidget(); } else if (document.activeElement === inputRef.current) { - if (event.key === 'Escape') { + if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setOpen(false); - } else if (event.key === 'Enter') { + } else if (event.key === "Enter") { event.preventDefault(); event.stopPropagation(); if (event.shiftKey) previousMatch() @@ -121,9 +120,9 @@ export const useFindWidget = (searchRef: RefObject) => { } } - document.addEventListener('keydown', handleKeyDown); + document.addEventListener("keydown", handleKeyDown); return () => { - document.removeEventListener('keydown', handleKeyDown); + document.removeEventListener("keydown", handleKeyDown); }; }, [inputRef, matches, nextMatch]); @@ -153,7 +152,7 @@ export const useFindWidget = (searchRef: RefObject) => { }, [searchRef.current]); // Main function for finding matches and generating highlight overlays - const refreshSearch = useCallback((scrollTo: ScrollToMatchOption = 'none', clearFirst = false) => { + const refreshSearch = useCallback((scrollTo: ScrollToMatchOption = "none", clearFirst = false) => { if (clearFirst) setMatches([]) const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable @@ -164,7 +163,7 @@ export const useFindWidget = (searchRef: RefObject) => { const query = caseSensitive ? _query : _query.toLowerCase() // First grab all text nodes - // Skips any elements with the 'find-widget-skip' class + // Skips any elements with the "find-widget-skip" class const textNodes: Text[] = []; const walker = document.createTreeWalker( searchRef.current, @@ -172,7 +171,7 @@ export const useFindWidget = (searchRef: RefObject) => { { acceptNode: (node) => { if (node.nodeType === Node.ELEMENT_NODE) { - if ((node as Element).classList.contains('find-widget-skip')) return NodeFilter.FILTER_REJECT; + if ((node as Element).classList.contains("find-widget-skip")) return NodeFilter.FILTER_REJECT; return NodeFilter.FILTER_ACCEPT; } else if (node.nodeType === Node.TEXT_NODE) { if (!node.nodeValue) return NodeFilter.FILTER_REJECT; @@ -189,17 +188,12 @@ export const useFindWidget = (searchRef: RefObject) => { textNodes.push(walker.currentNode as Text); } - // Keep track of the match closest match to the middle of the view - const verticalMiddle = searchRef.current.scrollTop + searchRef.current.clientHeight / 2 - let closestDist = Infinity - let closestMatchToMiddle: SearchMatch | null = null - // Now walk through each node match and extract search results // One node can have several matches const newMatches: SearchMatch[] = []; textNodes.forEach((textNode, idx) => { // Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail - const highlightFullLine = textNode.parentElement.className.includes('hljs') + const highlightFullLine = textNode.parentElement.className.includes("hljs") let nodeTextValue = caseSensitive ? textNode.nodeValue : textNode.nodeValue.toLowerCase(); let startIndex = 0; @@ -229,13 +223,6 @@ export const useFindWidget = (searchRef: RefObject) => { } newMatches.push(newMatch); - // Keep track of the match closest match to the middle of the view - const dist = Math.abs(verticalMiddle - top); - if (dist < closestDist) { - closestDist = dist; - closestMatchToMiddle = newMatch - } - if (highlightFullLine) { break; // Since highlighting full line no need for multiple overlays, will cause darker highlight } @@ -247,16 +234,34 @@ export const useFindWidget = (searchRef: RefObject) => { const matchHash = Object.fromEntries(newMatches.map(match => [JSON.stringify(match.overlayRectangle), match])) const filteredMatches = Object.values(matchHash).map((match, index) => ({ ...match, index })); + // Find match closest to the middle of the view + const verticalMiddle = searchRef.current.scrollTop + searchRef.current.clientHeight / 2 + let closestDist = Infinity + let closestMatchToMiddle: SearchMatch | null = null + filteredMatches.forEach((match) => { + const dist = Math.abs(verticalMiddle - match.overlayRectangle.top); + if (dist < closestDist) { + closestDist = dist; + closestMatchToMiddle = match; + } + }) + // Update matches and scroll to the closest or first match setMatches(filteredMatches); if (query.length > 1 && filteredMatches.length) { - // console.log(scrollTo) - if (scrollTo === 'first') { + if (scrollTo === "first") { scrollToMatch(filteredMatches[0]); } - if (scrollTo === 'closest' && closestMatchToMiddle) { + if (scrollTo === "closest") { scrollToMatch(closestMatchToMiddle) } + if (scrollTo === "none") { + if (closestMatchToMiddle) { + setCurrentMatch(closestMatchToMiddle) + } else { + setCurrentMatch(filteredMatches[0]) + } + } } }, [searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex]) @@ -267,7 +272,7 @@ export const useFindWidget = (searchRef: RefObject) => { const debounce = () => { debouncedInput.current = input lastUpdateRef.current = Date.now(); - refreshSearch('closest'); + refreshSearch("closest"); } const timeSinceLastUpdate = Date.now() - lastUpdateRef.current; if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) { @@ -282,41 +287,44 @@ export const useFindWidget = (searchRef: RefObject) => { } }, [refreshSearch, input]); + // Could consider doing any window click but I only handled search div here + // Since usually only clicks in search div will cause content changes in search div useEffect(() => { - if (!open) return - const handleWindowClick = () => { - refreshSearch('none'); + if (!open || !searchRef.current) return + const handleSearchRefClick = () => { + refreshSearch("none"); } - window.addEventListener('click', handleWindowClick) + searchRef.current.addEventListener("click", handleSearchRefClick) return () => { - window.removeEventListener('click', handleWindowClick); + searchRef.current.removeEventListener("click", handleSearchRefClick); }; - }, [refreshSearch, open]); + }, [searchRef.current, refreshSearch, open]); // Triggers that should cause results to temporarily disappear and then reload // Active = LLM is generating, etc. const active = useSelector((state: RootState) => state.state.active); useEffect(() => { if (active || isResizing) setMatches([]) - else refreshSearch('none') + else refreshSearch("none") }, [refreshSearch, active]); useEffect(() => { if (!open) setMatches([]) - else refreshSearch('closest') + else refreshSearch("closest") }, [refreshSearch, open]); useEffect(() => { - refreshSearch('closest') + refreshSearch("closest") }, [refreshSearch, caseSensitive, useRegex]) // Find widget component const widget = useMemo(() => { return (
) => { }} placeholder="Search..." /> -

+

{matches.length === 0 ? "No results" : `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}

-
+
{ e.stopPropagation() - // e.preventDefault() previousMatch() }} - className='h-4 w-4 focus:ring focus:ring-1' - disabled={matches.length < 2} + className="h-4 w-4 focus:ring focus:ring-1" + disabled={matches.length < 2 || active} > - + { e.stopPropagation() - // e.preventDefault() nextMatch() }} - className='h-4 w-4 focus:ring focus:ring-1' - disabled={matches.length < 2} + className="h-4 w-4 focus:ring focus:ring-1" + disabled={matches.length < 2 || active} > - +
{ e.stopPropagation() - // e.preventDefault() setCaseSensitive(curr => !curr) }} - className='h-5 w-6 text-xs focus:ring focus:ring-1 rounded-full border focus:outline-none' + className="h-5 w-6 text-xs focus:ring focus:ring-1 rounded-full border focus:outline-none" > Aa @@ -373,9 +379,9 @@ export const useFindWidget = (searchRef: RefObject) => { setOpen(false)} - className='focus:ring focus:ring-1' + className="focus:ring focus:ring-1" > - +
) From c5276900f8236d71fd2555b0f750994170df6c28 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 11 Nov 2024 13:34:34 -0800 Subject: [PATCH 20/20] edit after merge conflict --- .../StepContainerPreToolbar.tsx | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx index 6b1ef1553..ac13c6d54 100644 --- a/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx +++ b/gui/src/components/markdown/StepContainerPreToolbar/StepContainerPreToolbar.tsx @@ -1,21 +1,20 @@ +import { ChevronDownIcon } from "@heroicons/react/24/outline"; import { debounce } from "lodash"; import { useContext, useEffect, useRef, useState } from "react"; -import { useWebviewListener } from "../../../hooks/useWebviewListener"; -import { updateApplyState } from "../../../redux/slices/uiStateSlice"; import { useDispatch, useSelector } from "react-redux"; -import { RootState } from "../../../redux/store"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { childrenToText } from "../utils"; +import styled, { keyframes } from "styled-components"; import { v4 as uuidv4 } from "uuid"; import { defaultBorderRadius, lightGray, vscEditorBackground } from "../.."; +import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { useWebviewListener } from "../../../hooks/useWebviewListener"; +import { updateApplyState } from "../../../redux/slices/uiStateSlice"; +import { RootState } from "../../../redux/store"; import { getFontSize } from "../../../util"; -import FileInfo from "./FileInfo"; -import styled, { keyframes } from "styled-components"; -import Spinner from "./Spinner"; -import ApplyActions from "./ApplyActions"; -import { ChevronDownIcon } from "@heroicons/react/24/outline"; -import CopyButton from "./CopyButton"; +import { childrenToText } from "../utils"; import { useApplyCodeBlock } from "../utils/useApplyCodeBlock"; +import ApplyActions from "./ApplyActions"; +import CopyButton from "./CopyButton"; +import FileInfo from "./FileInfo"; import GeneratingCodeLoader from "./GeneratingCodeLoader"; const fadeInAnimation = keyframes` @@ -170,7 +169,7 @@ export default function StepContainerPreToolbar( return ( - +