Skip to content

Commit

Permalink
positions cursor at end of input when editing
Browse files Browse the repository at this point in the history
When the user indicates they would like to edit a previous message, we will position the cursor at the end of their previous input.
  • Loading branch information
jonathansampson committed Oct 17, 2024
1 parent e2413e0 commit f13672a
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions components/ai_chat/resources/page/components/edit_input/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ interface Props {

function EditInput(props: Props) {
const [text, setText] = React.useState(props.text)
const textareaRef = React.useRef<HTMLTextAreaElement>(null)

React.useEffect(() => {
if (textareaRef.current) {
/**
* When editing, we want the cursor to be positioned
* at the end of the text. Typically we would also call
* focus() here, but that isn't necessary in this case
* because the textarea already has [autoFocus] set.
*/
const length = textareaRef.current.value.length
textareaRef.current.setSelectionRange(length, length)
}
}, [])

const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing &&
!props.isSubmitDisabled) {
Expand All @@ -38,6 +53,7 @@ function EditInput(props: Props) {
data-replicated-value={text}
>
<textarea
ref={textareaRef}
value={text}
onChange={(e) => setText(e.currentTarget.value)}
onKeyDown={handleKeyDown}
Expand Down

0 comments on commit f13672a

Please sign in to comment.