mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(ui): app-wide keyboard shortcuts with TUI keybind import
This commit is contained in:
1 parent
b18e4f13b3
commit
b06de60f6b
38 files changed
+2467
-440
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { ModelQuickSelect } from './ModelQuickSelect'
|
||||
import { buildModelSections } from '@/lib/modelSections'
|
||||
@@ -144,6 +144,17 @@ async function openSelector(user: ReturnType<typeof userEvent.setup>) {
|
||||
return screen.findByRole('dialog', { name: 'Select model' })
|
||||
}
|
||||
|
||||
function focusDetachedTextarea() {
|
||||
const textarea = document.createElement('textarea')
|
||||
document.body.appendChild(textarea)
|
||||
textarea.focus()
|
||||
return textarea
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.querySelectorAll('textarea').forEach((element) => element.remove())
|
||||
})
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
|
||||
configurable: true,
|
||||
@@ -371,3 +382,75 @@ describe('ModelQuickSelect more models', () => {
|
||||
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-sonnet-4'))
|
||||
})
|
||||
})
|
||||
|
||||
describe('ModelQuickSelect keyboard navigation', () => {
|
||||
it('moves the active quick row with ArrowDown and selects it with Enter', () => {
|
||||
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(false)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).toHaveBeenCalledWith(selection('opencode', 'zen-1'))
|
||||
})
|
||||
|
||||
it('clamps at the first quick row and jumps to the last with End', () => {
|
||||
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: 'Select model' })
|
||||
|
||||
fireEvent.keyDown(dialog, { key: 'ArrowUp' })
|
||||
fireEvent.keyDown(dialog, { key: 'Enter' })
|
||||
expect(setModel).toHaveBeenLastCalledWith(selection('opencode-go', 'go-1'))
|
||||
|
||||
setModel.mockClear()
|
||||
|
||||
fireEvent.keyDown(dialog, { key: 'End' })
|
||||
fireEvent.keyDown(dialog, { key: 'Enter' })
|
||||
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-sonnet-4'))
|
||||
})
|
||||
|
||||
it('navigates the search results with the arrow keys and Enter', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
const searchInput = screen.getByPlaceholderText('Search models...')
|
||||
await user.type(searchInput, '5')
|
||||
|
||||
await screen.findAllByText('Claude Opus 5.5')
|
||||
|
||||
expect(fireEvent.keyDown(searchInput, { key: 'ArrowDown' })).toBe(false)
|
||||
expect(fireEvent.keyDown(searchInput, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).toHaveBeenCalledWith(selection('openai', 'gpt-5'))
|
||||
})
|
||||
|
||||
it('does not select a model when Enter is pressed on a row button', () => {
|
||||
const { setModel } = setModelSelection({ favorite: [selection('anthropic', 'claude-sonnet-4')] })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const star = screen.getByRole('button', { name: /favorites/ })
|
||||
star.focus()
|
||||
|
||||
fireEvent.keyDown(star, { key: 'Enter' })
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not intercept arrow keys when the sheet is closed', () => {
|
||||
render(<ModelQuickSelect />)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -48,12 +48,13 @@ interface ProviderListItem {
|
||||
interface VirtualizedListProps<T> {
|
||||
items: T[]
|
||||
itemHeight: number
|
||||
renderItem: (item: T) => React.ReactNode
|
||||
renderItem: (item: T, index: number) => React.ReactNode
|
||||
getKey: (item: T) => string
|
||||
emptyLabel: string
|
||||
className?: string
|
||||
resetKey?: string
|
||||
overscan?: number
|
||||
activeIndex?: number
|
||||
}
|
||||
|
||||
const MODEL_OPTION_ROW_HEIGHT = 60
|
||||
@@ -76,6 +77,7 @@ function VirtualizedList<T>({
|
||||
className,
|
||||
resetKey,
|
||||
overscan = VIRTUAL_LIST_OVERSCAN,
|
||||
activeIndex,
|
||||
}: VirtualizedListProps<T>) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const [scrollTop, setScrollTop] = useState(0)
|
||||
@@ -104,6 +106,21 @@ function VirtualizedList<T>({
|
||||
setScrollTop(0)
|
||||
}, [resetKey])
|
||||
|
||||
useEffect(() => {
|
||||
if (activeIndex === undefined) return
|
||||
const element = scrollRef.current
|
||||
if (!element) return
|
||||
|
||||
const rowTop = activeIndex * itemHeight
|
||||
const rowBottom = rowTop + itemHeight
|
||||
if (rowTop < element.scrollTop) {
|
||||
element.scrollTop = rowTop
|
||||
} else if (rowBottom > element.scrollTop + element.clientHeight) {
|
||||
element.scrollTop = rowBottom - element.clientHeight
|
||||
}
|
||||
setScrollTop(element.scrollTop)
|
||||
}, [activeIndex, itemHeight])
|
||||
|
||||
const visibleRange = useMemo(() => {
|
||||
if (items.length === 0 || viewportHeight === 0) {
|
||||
return { start: 0, end: 0 }
|
||||
@@ -141,7 +158,7 @@ function VirtualizedList<T>({
|
||||
height: itemHeight,
|
||||
}}
|
||||
>
|
||||
{renderItem(item)}
|
||||
{renderItem(item, visibleRange.start + index)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -164,6 +181,8 @@ export function ModelQuickSelect({
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const deferredSearchQuery = useDeferredValue(searchQuery)
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string | null>(null)
|
||||
const [activeIndex, setActiveIndex] = useState(0)
|
||||
const quickListRef = useRef<HTMLDivElement>(null)
|
||||
const { model, modelString, info, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory, session)
|
||||
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(directory, session)
|
||||
|
||||
@@ -265,12 +284,100 @@ export function ModelQuickSelect({
|
||||
|
||||
const browseModels = selectedProviderId ? selectedProviderModels : browseData?.allModels ?? EMPTY_MODELS
|
||||
|
||||
const handleModelSelect = (providerID: string, modelID: string) => {
|
||||
const navigableItems = useMemo((): ModelListItem[] => {
|
||||
if (showAllModels) {
|
||||
return isSearching ? searchResults : browseModels
|
||||
}
|
||||
return quickSections.flatMap((section) => section.models)
|
||||
}, [showAllModels, isSearching, searchResults, browseModels, quickSections])
|
||||
|
||||
const quickSectionOffsets = useMemo(() => {
|
||||
const offsets = new Map<string, number>()
|
||||
let running = 0
|
||||
for (const section of quickSections) {
|
||||
offsets.set(section.title, running)
|
||||
running += section.models.length
|
||||
}
|
||||
return offsets
|
||||
}, [quickSections])
|
||||
|
||||
const activeResetKey = `${isOpen}|${showAllModels}|${isSearching ? deferredSearchQuery : ''}|${selectedProviderId ?? ''}`
|
||||
const navigableItemsRef = useRef(navigableItems)
|
||||
navigableItemsRef.current = navigableItems
|
||||
const modelStringRef = useRef(modelString)
|
||||
modelStringRef.current = modelString
|
||||
|
||||
useEffect(() => {
|
||||
const selectedIndex = navigableItemsRef.current.findIndex((item) => item.key === modelStringRef.current)
|
||||
setActiveIndex(selectedIndex >= 0 ? selectedIndex : 0)
|
||||
}, [activeResetKey])
|
||||
|
||||
useEffect(() => {
|
||||
setActiveIndex((current) => {
|
||||
if (navigableItems.length === 0) return 0
|
||||
return Math.min(current, navigableItems.length - 1)
|
||||
})
|
||||
}, [navigableItems.length])
|
||||
|
||||
useEffect(() => {
|
||||
if (showAllModels) return
|
||||
const container = quickListRef.current
|
||||
if (!container) return
|
||||
const element = container.querySelector<HTMLElement>(`[data-model-index="${activeIndex}"]`)
|
||||
if (element && typeof element.scrollIntoView === 'function') {
|
||||
element.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
}, [activeIndex, showAllModels])
|
||||
|
||||
const handleModelSelect = useCallback((providerID: string, modelID: string) => {
|
||||
setModel({ providerID, modelID })
|
||||
setShowAllModels(false)
|
||||
setSearchQuery('')
|
||||
setSelectedProviderId(null)
|
||||
}
|
||||
}, [setModel])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) return
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey) return
|
||||
|
||||
const target = event.target
|
||||
if (target instanceof HTMLElement && target.closest('[role="menu"]')) return
|
||||
|
||||
const isTextInput =
|
||||
target instanceof HTMLElement && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')
|
||||
|
||||
if (event.key === 'Enter') {
|
||||
if (target instanceof HTMLElement && target.closest('button')) return
|
||||
const item = navigableItems[activeIndex]
|
||||
if (!item) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
handleModelSelect(item.providerID, item.modelID)
|
||||
return
|
||||
}
|
||||
|
||||
let nextIndex: number | null = null
|
||||
if (event.key === 'ArrowDown') {
|
||||
nextIndex = Math.min(activeIndex + 1, navigableItems.length - 1)
|
||||
} else if (event.key === 'ArrowUp') {
|
||||
nextIndex = Math.max(activeIndex - 1, 0)
|
||||
} else if (event.key === 'Home' && !isTextInput) {
|
||||
nextIndex = 0
|
||||
} else if (event.key === 'End' && !isTextInput) {
|
||||
nextIndex = navigableItems.length - 1
|
||||
}
|
||||
|
||||
if (nextIndex === null || navigableItems.length === 0) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
setActiveIndex(nextIndex)
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown, true)
|
||||
return () => document.removeEventListener('keydown', handleKeyDown, true)
|
||||
}, [isOpen, activeIndex, navigableItems, handleModelSelect])
|
||||
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (open === undefined) {
|
||||
@@ -301,15 +408,19 @@ export function ModelQuickSelect({
|
||||
|
||||
const getPrimaryLabel = (item: ModelListItem) => item.displayName || item.modelID
|
||||
|
||||
const renderModelOption = (item: ModelListItem) => {
|
||||
const renderModelOption = (item: ModelListItem, index: number) => {
|
||||
const isSelected = modelString === item.key
|
||||
const isFavorite = favoriteKeySet.has(item.key)
|
||||
const isRecent = recentKeySet.has(item.key)
|
||||
const isActive = index === activeIndex
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.key}
|
||||
className={`group flex w-full items-center gap-2 rounded-xl py-2 text-left transition-colors hover:bg-accent ${isSelected ? 'bg-highlight/10' : ''}`}
|
||||
data-model-index={index}
|
||||
data-active={isActive ? 'true' : undefined}
|
||||
onMouseMove={() => setActiveIndex(index)}
|
||||
className={`group flex w-full items-center gap-2 rounded-xl py-2 text-left transition-colors hover:bg-accent ${isSelected ? 'bg-highlight/10' : ''} ${isActive ? 'bg-accent ring-1 ring-border' : ''}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@@ -521,11 +632,12 @@ export function ModelQuickSelect({
|
||||
<VirtualizedList
|
||||
items={searchResults}
|
||||
itemHeight={MODEL_OPTION_ROW_HEIGHT}
|
||||
renderItem={(item) => renderModelOption(item)}
|
||||
renderItem={(item, index) => renderModelOption(item, index)}
|
||||
getKey={(item) => item.key}
|
||||
emptyLabel="No models found"
|
||||
className="px-4 pb-4 pt-2"
|
||||
resetKey={`${selectedProviderId ?? 'all'}:${deferredSearchQuery}`}
|
||||
activeIndex={activeIndex}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
@@ -544,11 +656,12 @@ export function ModelQuickSelect({
|
||||
<VirtualizedList
|
||||
items={browseModels}
|
||||
itemHeight={MODEL_OPTION_ROW_HEIGHT}
|
||||
renderItem={(item) => renderModelOption(item)}
|
||||
renderItem={(item, index) => renderModelOption(item, index)}
|
||||
getKey={(item) => item.key}
|
||||
emptyLabel="No models found"
|
||||
className="px-4 pb-4 pt-2"
|
||||
resetKey={selectedProviderId ?? 'all'}
|
||||
activeIndex={activeIndex}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -558,7 +671,7 @@ export function ModelQuickSelect({
|
||||
<VirtualizedList
|
||||
items={selectedProviderModels}
|
||||
itemHeight={MODEL_OPTION_ROW_HEIGHT}
|
||||
renderItem={(item) => renderModelOption(item)}
|
||||
renderItem={(item, index) => renderModelOption(item, index)}
|
||||
getKey={(item) => item.key}
|
||||
emptyLabel="No models found"
|
||||
className="px-4 pb-4"
|
||||
@@ -580,7 +693,7 @@ export function ModelQuickSelect({
|
||||
)
|
||||
) : (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden pb-safe pt-0">
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
|
||||
<div ref={quickListRef} className="min-h-0 flex-1 space-y-4 overflow-y-auto px-4 pb-3">
|
||||
{quickSections.map(section => (
|
||||
<section key={section.title}>
|
||||
<h3 className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
|
||||
@@ -588,7 +701,7 @@ export function ModelQuickSelect({
|
||||
{section.title}
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
{section.models.map(item => renderModelOption(item))}
|
||||
{section.models.map((item, index) => renderModelOption(item, (quickSectionOffsets.get(section.title) ?? 0) + index))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
|
||||
Reference in new issue
Block a user