-
Notifications
You must be signed in to change notification settings - Fork 860
Add replace-with-answer button to selection tools #996
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
50b65a1
f39ab7e
70bf9c1
0fb4fd7
25fbd1e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { useEffect, useRef, useState } from 'react' | ||
| import { CheckIcon, ReplyIcon, XIcon } from '@primer/octicons-react' | ||
| import PropTypes from 'prop-types' | ||
| import { useTranslation } from 'react-i18next' | ||
|
|
||
| ReplaceButton.propTypes = { | ||
| onReplace: PropTypes.func.isRequired, | ||
| size: PropTypes.number.isRequired, | ||
| className: PropTypes.string, | ||
| } | ||
|
|
||
| function ReplaceButton({ className, onReplace, size }) { | ||
| const { t } = useTranslation() | ||
| const [status, setStatus] = useState('idle') | ||
| const timeoutRef = useRef(null) | ||
|
|
||
| useEffect(() => { | ||
| return () => { | ||
| if (timeoutRef.current) clearTimeout(timeoutRef.current) | ||
| } | ||
| }, []) | ||
|
|
||
| const onClick = () => { | ||
| setStatus(onReplace() ? 'replaced' : 'failed') | ||
| if (timeoutRef.current) clearTimeout(timeoutRef.current) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: If the component unmounts before the 800ms timeout fires, the callback runs and calls |
||
| timeoutRef.current = setTimeout(() => { | ||
| setStatus('idle') | ||
| timeoutRef.current = null | ||
| }, 800) | ||
| } | ||
|
Comment on lines
+15
to
+30
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add a const timeoutRef = useRef(null)
useEffect(() => {
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
}
}, [])
const onClick = () => {
setStatus(onReplace() ? 'replaced' : 'failed')
if (timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(() => {
setStatus('idle')
timeoutRef.current = null
}, 800)
}
qodo-code-review[bot] marked this conversation as resolved.
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| return ( | ||
| <span | ||
| title={status === 'failed' ? t('Replace Failed') : t('Replace Selection')} | ||
| className={`gpt-util-icon ${className ? className : ''}`} | ||
| onClick={onClick} | ||
| > | ||
|
Comment on lines
+33
to
+37
|
||
| {status === 'replaced' ? ( | ||
| <CheckIcon size={size} /> | ||
| ) : status === 'failed' ? ( | ||
| <XIcon size={size} /> | ||
| ) : ( | ||
| <ReplyIcon size={size} /> | ||
| )} | ||
| </span> | ||
| ) | ||
| } | ||
|
|
||
| export default ReplaceButton | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,6 +14,7 @@ import { | |
| setUserConfig, | ||
| } from '../config/index.mjs' | ||
| import { | ||
| captureEditableSelection, | ||
| createElementAtPosition, | ||
| cropText, | ||
| endsWithQuestionMark, | ||
|
|
@@ -236,12 +237,14 @@ const deleteToolbar = () => { | |
| } | ||
| } | ||
|
|
||
| const createSelectionTools = async (toolbarContainerElement, selection) => { | ||
| const createSelectionTools = async (toolbarContainerElement, selection, capturedSelection) => { | ||
| console.debug( | ||
| '[content] createSelectionTools called with selection:', | ||
| selection, | ||
| 'and container:', | ||
| 'container:', | ||
| toolbarContainerElement, | ||
| 'captured editable selection kind:', | ||
| capturedSelection?.kind, | ||
| ) | ||
|
qodo-code-review[bot] marked this conversation as resolved.
|
||
| try { | ||
| toolbarContainerElement.className = 'chatgptbox-toolbar-container' | ||
|
|
@@ -256,6 +259,7 @@ const createSelectionTools = async (toolbarContainerElement, selection) => { | |
| selection={selection} | ||
| container={toolbarContainerElement} | ||
| dockable={true} | ||
| capturedSelection={capturedSelection} | ||
| />, | ||
| toolbarContainerElement, | ||
| ) | ||
|
|
@@ -291,11 +295,17 @@ async function prepareForSelectionTools() { | |
| deleteToolbar() | ||
| setTimeout(async () => { | ||
| try { | ||
| const selection = window | ||
| .getSelection() | ||
| ?.toString() | ||
| .trim() | ||
| .replace(/^-+|-+$/g, '') | ||
| const capturedSelection = captureEditableSelection() | ||
| const selection = | ||
| window | ||
| .getSelection() | ||
| ?.toString() | ||
| .trim() | ||
| .replace(/^-+|-+$/g, '') || | ||
| // Firefox does not expose text field selections via window.getSelection() | ||
| (capturedSelection?.kind === 'text-field' | ||
| ? capturedSelection.text.trim().replace(/^-+|-+$/g, '') | ||
| : '') | ||
|
Comment on lines
+298
to
+308
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1. Firefox keydown closes toolbar The PR adds a Firefox fallback to derive selected text from captured text-field selection, but the keydown cleanup path still checks only window.getSelection(). In Firefox (where text-field selection isn’t exposed via window.getSelection), this can incorrectly delete the selection-tools toolbar even while a text-field selection still exists. Agent Prompt
|
||
| if (selection) { | ||
| console.debug('[content] Text selected. Length:', selection.length) | ||
| let position | ||
|
|
@@ -325,7 +335,7 @@ async function prepareForSelectionTools() { | |
| } | ||
| console.debug('[content] Toolbar position:', position) | ||
| toolbarContainer = createElementAtPosition(position.x, position.y) | ||
| await createSelectionTools(toolbarContainer, selection) | ||
| await createSelectionTools(toolbarContainer, selection, capturedSelection) | ||
| } else { | ||
| console.debug('[content] No text selected on mouseup.') | ||
| } | ||
|
|
@@ -403,16 +413,22 @@ async function prepareForSelectionToolsTouch() { | |
| deleteToolbar() | ||
| setTimeout(async () => { | ||
| try { | ||
| const selection = window | ||
| .getSelection() | ||
| ?.toString() | ||
| .trim() | ||
| .replace(/^-+|-+$/g, '') | ||
| const capturedSelection = captureEditableSelection() | ||
| const selection = | ||
| window | ||
| .getSelection() | ||
| ?.toString() | ||
| .trim() | ||
| .replace(/^-+|-+$/g, '') || | ||
| // Firefox does not expose text field selections via window.getSelection() | ||
| (capturedSelection?.kind === 'text-field' | ||
| ? capturedSelection.text.trim().replace(/^-+|-+$/g, '') | ||
| : '') | ||
| if (selection) { | ||
| console.debug('[content] Text selected via touch:', selection) | ||
| const touch = e.changedTouches[0] | ||
| toolbarContainer = createElementAtPosition(touch.pageX + 20, touch.pageY + 20) | ||
| await createSelectionTools(toolbarContainer, selection) | ||
| await createSelectionTools(toolbarContainer, selection, capturedSelection) | ||
| } else { | ||
| console.debug('[content] No text selected on touchend.') | ||
| } | ||
|
|
@@ -443,7 +459,7 @@ async function prepareForSelectionToolsTouch() { | |
| }) | ||
| } | ||
|
|
||
| let menuX, menuY | ||
| let menuX, menuY, menuCapturedSelection | ||
| let rightClickMenuInitialized = false | ||
|
|
||
| async function prepareForRightClickMenu() { | ||
|
qodo-code-review[bot] marked this conversation as resolved.
|
||
|
|
@@ -456,6 +472,9 @@ async function prepareForRightClickMenu() { | |
| document.addEventListener('contextmenu', (e) => { | ||
| menuX = e.clientX | ||
| menuY = e.clientY | ||
| // the menu click arrives asynchronously via the background script, so the | ||
| // editable selection has to be captured while it still exists | ||
| menuCapturedSelection = captureEditableSelection() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Memory Leak RiskThe global variable This prevents the DOM element, its owner document, and associated resources from being garbage collected, leading to a memory leak on long-lived pages. SuggestionClear menuCapturedSelection = captureEditableSelection()
setTimeout(() => {
if (menuCapturedSelection) {
menuCapturedSelection = null
}
}, 30000) |
||
| console.debug(`[content] Context menu opened at X: ${menuX}, Y: ${menuY}`) | ||
| }) | ||
|
|
||
|
|
@@ -465,6 +484,10 @@ async function prepareForRightClickMenu() { | |
| try { | ||
| const data = message.data | ||
| let prompt = '' | ||
| // only selection tools operate on the selected text; menu tools work | ||
| // on the whole page and must not offer replacing the selection | ||
| const capturedSelection = data.itemId in toolsConfig ? menuCapturedSelection : null | ||
| menuCapturedSelection = null | ||
| if (data.itemId in toolsConfig) { | ||
| console.debug('[content] Generating prompt from toolsConfig for item:', data.itemId) | ||
| prompt = await toolsConfig[data.itemId].genPrompt(data.selectionText) | ||
|
|
@@ -507,6 +530,7 @@ async function prepareForRightClickMenu() { | |
| triggered={true} | ||
| closeable={true} | ||
| prompt={prompt} | ||
| capturedSelection={capturedSelection} | ||
| />, | ||
| container, | ||
| ) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Robustness of Callback Return Value Check
Currently,
ReplaceButtonassumes thatonReplace()strictly returns a truthy value on success. However, in React, many callback functions do not return a value (i.e., they returnundefined). If another developer reusesReplaceButtonorConversationCardwith a standard void-returning function, the button will incorrectly show the "Replace Failed" state.Suggestion
Only treat the result as a failure if it explicitly returns
false.