Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(cmdk): shell-style message history for up/down keys

Greg Richardsonbf3b267bc946
diff --git a/packages/ui/src/components/Command/AiCommand.tsx b/packages/ui/src/components/Command/AiCommand.tsx
index 5e816dd7d53..fa0f8077811 100644
--- a/packages/ui/src/components/Command/AiCommand.tsx
+++ b/packages/ui/src/components/Command/AiCommand.tsx
@@ -343,6 +343,23 @@ const AiCommand = () => {
setIsLoading,
})
+ const inputRef = useRef<HTMLInputElement>(null)
+
+ // Message index (of role === 'user') when hitting up/down on the keyboard (shell style)
+ const [, setMessageSelectionIndex] = useState(0)
+
+ const userMessages = messages.filter(({ role }) => role === MessageRole.User)
+
+ useEffect(() => {
+ if (isResponding) {
+ return
+ }
+
+ // Note: intentionally setting index to 1 greater than array length
+ setMessageSelectionIndex(userMessages.length)
+ console.log('setting index to', userMessages.length)
+ }, [messages, isResponding])
+
const handleSubmit = useCallback(
(message: string) => {
setSearch('')
@@ -362,6 +379,19 @@ const AiCommand = () => {
}
}, [])
+ // Focus the input when typing from anywhere
+ useEffect(() => {
+ function onKeyDown() {
+ inputRef.current?.focus()
+ }
+
+ window.addEventListener('keydown', onKeyDown)
+
+ return () => {
+ window.removeEventListener('keydown', onKeyDown)
+ }
+ }, [])
+
return (
<div onClick={(e) => e.stopPropagation()}>
<div className={cn('relative mb-[62px] py-4 max-h-[720px] overflow-auto')}>
@@ -456,6 +486,7 @@ const AiCommand = () => {
<div className="absolute bottom-0 w-full bg-scale-200 py-3">
<Input
className="bg-scale-100 rounded mx-3"
+ inputRef={inputRef}
autoFocus
placeholder={
isLoading || isResponding ? 'Waiting on an answer...' : 'Ask Supabase AI a question...'
@@ -493,6 +524,20 @@ const AiCommand = () => {
}
handleSubmit(search)
return
+ case 'ArrowUp':
+ setMessageSelectionIndex((index) => {
+ const newIndex = Math.max(index - 1, 0)
+ setSearch(userMessages[newIndex]?.content ?? '')
+ return newIndex
+ })
+ return
+ case 'ArrowDown':
+ setMessageSelectionIndex((index) => {
+ const newIndex = Math.min(index + 1, userMessages.length)
+ setSearch(userMessages[newIndex]?.content ?? '')
+ return newIndex
+ })
+ return
default:
return
}