Skip to content

Commit

Permalink
Autofocus input (#63)
Browse files Browse the repository at this point in the history
* Implement custom AutoFocusPlugin

* Update comment
  • Loading branch information
kevin-on authored Oct 29, 2024
1 parent b2d7735 commit d6c7793
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/components/chat-view/chat-input/ChatUserInput.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin'
import {
InitialConfigType,
LexicalComposer,
Expand Down Expand Up @@ -34,6 +33,7 @@ import { MemoizedSyntaxHighlighterWrapper } from '../SyntaxHighlighterWrapper'

import MentionableBadge from './MentionableBadge'
import { ModelSelect } from './ModelSelect'
import AutoFocusPlugin from './plugins/auto-focus/AutoFocusPlugin'
import AutoLinkMentionPlugin from './plugins/mention/AutoLinkMentionPlugin'
import { MentionNode } from './plugins/mention/MentionNode'
import MentionPlugin from './plugins/mention/MentionPlugin'
Expand Down Expand Up @@ -318,7 +318,7 @@ const ChatUserInput = forwardRef<ChatUserInputRef, ChatUserInputProps>(
ErrorBoundary={LexicalErrorBoundary}
/>
<HistoryPlugin />
{autoFocus && <AutoFocusPlugin />}
{autoFocus && <AutoFocusPlugin defaultSelection="rootEnd" />}
<MentionPlugin searchResultByQuery={searchResultByQuery} />
<OnChangePlugin
onChange={(editorState) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { useEffect } from 'react'

export type AutoFocusPluginProps = {
defaultSelection?: 'rootStart' | 'rootEnd'
}

export default function AutoFocusPlugin({
defaultSelection,
}: AutoFocusPluginProps) {
const [editor] = useLexicalComposerContext()

useEffect(() => {
editor.focus(
() => {
const rootElement = editor.getRootElement()
if (rootElement) {
// requestAnimationFrame is required here for unknown reasons, possibly related to the Obsidian plugin environment.
requestAnimationFrame(() => {
rootElement.focus()
})
}
},
{ defaultSelection },
)
}, [defaultSelection, editor])

return null
}

0 comments on commit d6c7793

Please sign in to comment.