📏 fix: Scope Skill Command Query to Text Before the Caret (#14604)

This commit is contained in:
Danny Avila 2026-08-03 07:53:30 -04:00 • committed by GitHub
parent 664290c653
commit 6bbbee7a78
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 71 additions and 19 deletions

View file

@ -1,16 +1,18 @@
import { useCallback } from 'react';
/** Creates a callback ref that focuses the popover input, transfers the command text as a search prefix, and clears the textarea. */
/** Creates a callback ref that focuses the popover input and transfers command text into search. */
const useInitPopoverInput = ({
inputRef,
textAreaRef,
commandChar,
preserveTextAfterCursor = false,
setSearchValue,
setOpen,
}: {
inputRef: React.MutableRefObject<HTMLInputElement | null>;
textAreaRef: React.MutableRefObject<HTMLTextAreaElement | null>;
commandChar: string;
preserveTextAfterCursor?: boolean;
setSearchValue: (value: string) => void;
setOpen: (value: boolean) => void;
}) =>
@ -20,23 +22,26 @@ const useInitPopoverInput = ({
if (!node) {
return;
}
const textarea = textAreaRef.current;
const text = textarea?.value;
const selectionStart = textarea?.selectionStart;
node.focus();
setOpen(true);
const textarea = textAreaRef.current;
if (!textarea) {
if (!textarea || typeof text !== 'string' || typeof selectionStart !== 'number') {
return;
}
const text = textarea.value;
if (text.length > 0 && text[0] === commandChar) {
if (text.length > 1) {
setSearchValue(text.slice(1));
}
textarea.value = '';
textarea.setSelectionRange(0, 0);
textarea.dispatchEvent(new Event('input', { bubbles: true }));
if (!text.startsWith(commandChar) || selectionStart < commandChar.length) {
return;
}
const commandEnd = preserveTextAfterCursor ? selectionStart : text.length;
if (commandEnd > commandChar.length) {
setSearchValue(text.slice(commandChar.length, commandEnd));
}
textarea.value = preserveTextAfterCursor ? text.slice(selectionStart) : '';
textarea.setSelectionRange(0, 0);
textarea.dispatchEvent(new Event('input', { bubbles: true }));
},
[inputRef, textAreaRef, commandChar, setSearchValue, setOpen],
[inputRef, textAreaRef, commandChar, preserveTextAfterCursor, setSearchValue, setOpen],
);
export default useInitPopoverInput;