mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(shortcuts): rework shortcut bindings, focus restore, and input guards
Resolve effective bindings from stored prefs plus defaults with leader/direct collision handling and default leader Ctrl+X; let direct actions pass through in terminals and suppress abort while an overlay is open. Add half-page scroll disengage, verified overlay focus restore, and consolidate prompt reset.
This commit is contained in:
1 parent
7e8443f54f
commit
994a8b82e8
33 files changed
+784
-195
No files matched your search
@@ -12,7 +12,7 @@ import {
|
||||
fileExists,
|
||||
ensureDirectoryExists,
|
||||
} from './file-operations'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, OpenCodeConfigSchema, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@opencode-manager/shared/schemas'
|
||||
import { MANAGER_COLOR_THEME_ID, OPENCODE_THEMES } from '@opencode-manager/shared/themes'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantModePath, getReposPath } from '@opencode-manager/shared/config/env'
|
||||
@@ -699,6 +699,18 @@ Partial object with any of the allowed keys.
|
||||
**Response:**
|
||||
Returns the updated settings object with the same structure as GET.
|
||||
|
||||
### Keyboard Shortcut Preferences
|
||||
|
||||
\`keyboardShortcuts\`, \`leaderKey\`, and \`directShortcuts\` control keyboard bindings.
|
||||
|
||||
**Actions:** ${Object.keys(DEFAULT_KEYBOARD_SHORTCUTS).join(', ')}
|
||||
|
||||
**Key format:** modifiers joined with \`+\`, using \`Ctrl\`, \`Cmd\`, \`Alt\`, and \`Shift\` (for example \`Ctrl+Alt+U\` or \`Shift+Tab\`). \`Cmd\` is the Command key on macOS and Ctrl on other platforms. An empty string unbinds the action.
|
||||
|
||||
**Leader vs direct:** by default a binding is a leader binding, pressed after the \`leaderKey\` (default \`${DEFAULT_LEADER_KEY}\`). List an action in \`directShortcuts\` to fire it without the leader key.
|
||||
|
||||
**Sending changes:** \`keyboardShortcuts\` and \`directShortcuts\` are replaced wholesale. Read the current \`keyboardShortcuts\` (and \`directShortcuts\` when changing binding kinds) from GET /settings, modify only the actions you need, and send the complete map or list back; actions absent from the stored map use their built-in defaults.
|
||||
|
||||
### POST /assistant/reload
|
||||
|
||||
Reload the OpenCode configuration without restarting the server, rebuilding every loaded location. OpenCode re-reads \`opencode.json\`/\`opencode.jsonc\`, agents, commands, skills, plugins, and \`AGENTS.md\`; running sessions, including this one, keep running. Use this after editing \`.opencode/agents/assistant.md\` or other workspace files so changes take effect on the next message. Returns \`400\` with \`validationIssues\` when the OpenCode configuration is invalid.
|
||||
|
||||
@@ -446,6 +446,23 @@ describe('PromptInput command submission', () => {
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clears attachments and exits bash mode on Escape while idle', async () => {
|
||||
const { container } = renderComponent()
|
||||
|
||||
const input = await screen.findByPlaceholderText('Send a message...')
|
||||
fireEvent.change(input, { target: { value: '!' } })
|
||||
expect(screen.getByTestId('composer-mode-badge')).toHaveTextContent('BASH')
|
||||
|
||||
await attachImage(container)
|
||||
expect(screen.getByText('pic.png')).toBeInTheDocument()
|
||||
|
||||
fireEvent.keyDown(input, { key: 'Escape' })
|
||||
|
||||
expect(input).toHaveValue('')
|
||||
expect(screen.queryByTestId('composer-mode-badge')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('pic.png')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps attachments and clears only the text when a built-in command is submitted', async () => {
|
||||
const { container } = renderComponent()
|
||||
|
||||
|
||||
@@ -988,8 +988,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (isBashMode && e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
setIsBashMode(false)
|
||||
setPrompt('')
|
||||
resetPrompt()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1070,12 +1069,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
}
|
||||
handleSubmit()
|
||||
} else if (e.key === 'Escape' && !isSessionActive) {
|
||||
closeSuggestions()
|
||||
setPrompt('')
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
resetVoiceGestureState()
|
||||
clearSTT()
|
||||
resetPrompt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1109,6 +1103,21 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
setMentionRange(null)
|
||||
}, [])
|
||||
|
||||
const resetPrompt = useCallback(() => {
|
||||
setPrompt('')
|
||||
setAttachedFiles(new Map())
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
closeSuggestions()
|
||||
setIsBashMode(false)
|
||||
resetVoiceGestureState()
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
} else {
|
||||
clearSTT()
|
||||
}
|
||||
}, [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, closeSuggestions])
|
||||
|
||||
const updateSuggestionTriggers = (value: string, cursorPosition: number) => {
|
||||
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
|
||||
|
||||
@@ -1272,18 +1281,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
clearPrompt: () => {
|
||||
setPrompt('')
|
||||
setAttachedFiles(new Map())
|
||||
revokeBlobUrls(imageAttachments)
|
||||
setImageAttachments([])
|
||||
closeSuggestions()
|
||||
setIsBashMode(false)
|
||||
resetVoiceGestureState()
|
||||
if (isRecording) {
|
||||
abortRecording()
|
||||
} else {
|
||||
clearSTT()
|
||||
}
|
||||
resetPrompt()
|
||||
textareaRef.current?.focus()
|
||||
},
|
||||
triggerFileUpload: openFilePicker,
|
||||
@@ -1292,7 +1290,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
},
|
||||
cycleAgent: handleCycleAgent,
|
||||
cycleVariant: handleCycleVariant,
|
||||
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, closeSuggestions, openFilePicker, handleCycleAgent, handleCycleVariant])
|
||||
}), [resetPrompt, openFilePicker, handleCycleAgent, handleCycleVariant])
|
||||
|
||||
const commandActionsWithPrompt = useMemo<CommandActions>(
|
||||
() => ({
|
||||
|
||||
@@ -9,8 +9,17 @@ import type { Provider } from '@/api/providers'
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useModelSelection: vi.fn(),
|
||||
useModelSections: vi.fn(),
|
||||
deferredSearchValue: { current: null as string | null },
|
||||
}))
|
||||
|
||||
vi.mock('react', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react')>()
|
||||
return {
|
||||
...actual,
|
||||
useDeferredValue: (value: string) => mocks.deferredSearchValue.current ?? value,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useModelSelection', () => ({
|
||||
useModelSelection: mocks.useModelSelection,
|
||||
}))
|
||||
@@ -151,8 +160,23 @@ function focusDetachedTextarea() {
|
||||
return textarea
|
||||
}
|
||||
|
||||
const originalInnerWidth = window.innerWidth
|
||||
|
||||
function setViewportWidth(width: number) {
|
||||
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width })
|
||||
}
|
||||
|
||||
function mobileModelList() {
|
||||
const lists = Array.from(document.querySelectorAll<HTMLElement>('.overflow-y-auto.px-4.pb-4'))
|
||||
const list = lists.find((element) => !element.classList.contains('pt-2'))
|
||||
if (!list) throw new Error('No mobile model list found')
|
||||
return list
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
document.querySelectorAll('textarea').forEach((element) => element.remove())
|
||||
setViewportWidth(originalInnerWidth)
|
||||
mocks.deferredSearchValue.current = null
|
||||
})
|
||||
|
||||
beforeAll(() => {
|
||||
@@ -453,4 +477,89 @@ describe('ModelQuickSelect keyboard navigation', () => {
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores keyboard navigation when the mobile provider list hides the models', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
setViewportWidth(500)
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(true)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(true)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('navigates the provider models that are visible on mobile', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { setModel } = setModelSelection()
|
||||
setViewportWidth(500)
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown' })).toBe(false)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).toHaveBeenCalledWith(selection('anthropic', 'claude-opus-5-5-fast'))
|
||||
})
|
||||
|
||||
it('ignores keydown events while an IME composition is active', () => {
|
||||
const { setModel } = setModelSelection({ model: selection('opencode-go', 'go-1') })
|
||||
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: 'ArrowDown', isComposing: true })).toBe(true)
|
||||
expect(fireEvent.keyDown(textarea, { key: 'Enter', isComposing: true })).toBe(true)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not select while the deferred search query is still catching up', 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...')
|
||||
mocks.deferredSearchValue.current = ''
|
||||
await user.type(searchInput, '5')
|
||||
|
||||
expect(fireEvent.keyDown(searchInput, { key: 'Enter' })).toBe(false)
|
||||
|
||||
expect(setModel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('scrolls the mobile provider model list to follow the active row', async () => {
|
||||
const user = userEvent.setup()
|
||||
const clientHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'clientHeight')
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientHeight', { configurable: true, get: () => 60 })
|
||||
setViewportWidth(500)
|
||||
|
||||
try {
|
||||
render(<ModelQuickSelect open />)
|
||||
await user.click(screen.getByRole('button', { name: /More models/ }))
|
||||
await user.click(screen.getAllByRole('button', { name: /Anthropic 2 models/ })[0])
|
||||
|
||||
const list = mobileModelList()
|
||||
expect(list.scrollTop).toBe(0)
|
||||
|
||||
const textarea = focusDetachedTextarea()
|
||||
fireEvent.keyDown(textarea, { key: 'ArrowDown' })
|
||||
|
||||
expect(list.scrollTop).toBe(60)
|
||||
} finally {
|
||||
Object.defineProperty(HTMLElement.prototype, 'clientHeight', clientHeight!)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Check, ChevronDown, ChevronLeft, ChevronRight, Search, Star, Trash2, X, type LucideIcon } from 'lucide-react'
|
||||
import { useModelSelection, type ModelSelectionSession } from '@/hooks/useModelSelection'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useModelSections } from '@/hooks/useModelSections'
|
||||
import { useVariants } from '@/hooks/useVariants'
|
||||
import { modelSelectionRef, type Model } from '@/api/providers'
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { buildModelSections, filterModelSections, type ModelOption } from '@/lib/modelSections'
|
||||
import { isTextEntryElement } from '@/lib/domTargets'
|
||||
|
||||
interface ModelQuickSelectProps {
|
||||
directory?: string
|
||||
@@ -183,6 +185,7 @@ export function ModelQuickSelect({
|
||||
const [selectedProviderId, setSelectedProviderId] = useState<string | null>(null)
|
||||
const [activeIndex, setActiveIndex] = useState(0)
|
||||
const quickListRef = useRef<HTMLDivElement>(null)
|
||||
const isMobile = useMobile()
|
||||
const { model, modelString, info, recentModels, favoriteModels, setModel, toggleFavorite, removeRecentModel } = useModelSelection(directory, session)
|
||||
const { availableVariants, currentVariant, setVariant, clearVariant, hasVariants } = useVariants(directory, session)
|
||||
|
||||
@@ -286,10 +289,12 @@ export function ModelQuickSelect({
|
||||
|
||||
const navigableItems = useMemo((): ModelListItem[] => {
|
||||
if (showAllModels) {
|
||||
return isSearching ? searchResults : browseModels
|
||||
if (isSearching) return searchResults
|
||||
if (isMobile && !selectedProviderId) return EMPTY_MODELS
|
||||
return browseModels
|
||||
}
|
||||
return quickSections.flatMap((section) => section.models)
|
||||
}, [showAllModels, isSearching, searchResults, browseModels, quickSections])
|
||||
}, [showAllModels, isSearching, isMobile, selectedProviderId, searchResults, browseModels, quickSections])
|
||||
|
||||
const quickSectionOffsets = useMemo(() => {
|
||||
const offsets = new Map<string, number>()
|
||||
@@ -306,6 +311,10 @@ export function ModelQuickSelect({
|
||||
navigableItemsRef.current = navigableItems
|
||||
const modelStringRef = useRef(modelString)
|
||||
modelStringRef.current = modelString
|
||||
const searchQueryRef = useRef(searchQuery)
|
||||
searchQueryRef.current = searchQuery
|
||||
const deferredSearchQueryRef = useRef(deferredSearchQuery)
|
||||
deferredSearchQueryRef.current = deferredSearchQuery
|
||||
|
||||
useEffect(() => {
|
||||
const selectedIndex = navigableItemsRef.current.findIndex((item) => item.key === modelStringRef.current)
|
||||
@@ -341,15 +350,20 @@ export function ModelQuickSelect({
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey || event.metaKey || event.altKey) return
|
||||
if (event.isComposing) 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')
|
||||
const isTextInput = target instanceof Element && isTextEntryElement(target)
|
||||
|
||||
if (event.key === 'Enter') {
|
||||
if (target instanceof HTMLElement && target.closest('button')) return
|
||||
if (searchQueryRef.current !== deferredSearchQueryRef.current) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
const item = navigableItems[activeIndex]
|
||||
if (!item) return
|
||||
event.preventDefault()
|
||||
@@ -676,6 +690,7 @@ export function ModelQuickSelect({
|
||||
emptyLabel="No models found"
|
||||
className="px-4 pb-4"
|
||||
resetKey={selectedProviderId}
|
||||
activeIndex={activeIndex}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full overflow-y-auto px-4 pb-4">
|
||||
|
||||
@@ -16,7 +16,7 @@ import { RepoActionsContent } from '@/components/repo/RepoActionsDialog'
|
||||
import { RepoSkillsContent } from '@/components/repo/RepoSkillsDialog'
|
||||
import { RepoSchedulesContent } from '@/components/schedules/RepoSchedulesContent'
|
||||
import type { SkillFileInfo } from '@opencode-manager/shared'
|
||||
import { buildToolItems, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
|
||||
import { buildToolItems, toolKeyOf, type MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
|
||||
import { isPanelTool, type ToolPanelState, type PanelTool } from '@/hooks/useToolPanel'
|
||||
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
@@ -108,7 +108,7 @@ export function ToolSidePanel({
|
||||
const panelTools: Array<{ item: MoreDrawerItem; tool: PanelTool }> = []
|
||||
const actionItems: MoreDrawerItem[] = []
|
||||
for (const item of buildToolItems(location.pathname)) {
|
||||
const tool = item.panelTool ?? item.dialog ?? null
|
||||
const tool = toolKeyOf(item)
|
||||
if (isPanelTool(tool)) panelTools.push({ item, tool })
|
||||
else actionItems.push(item)
|
||||
}
|
||||
|
||||
@@ -60,6 +60,11 @@ export function buildToolItems(pathname: string): MoreDrawerItem[] {
|
||||
return buildNavModel(pathname).items.filter((item) => !NON_TOOL_ITEM_KEYS.has(item.key))
|
||||
}
|
||||
|
||||
/** The `?panel=`/`?dialog=` tool identifier an item targets, preferring its panel tool. */
|
||||
export function toolKeyOf(item: MoreDrawerItem): string | null {
|
||||
return item.panelTool ?? item.dialog ?? null
|
||||
}
|
||||
|
||||
function buildRouteNavModel(pathname: string): NavModel {
|
||||
const baseItems = getBaseItems()
|
||||
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { render as renderRaw, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { ReactElement } from 'react'
|
||||
import type { FormInfo } from '@opencode-manager/shared/opencode'
|
||||
import { KeyboardShortcutsProvider, useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { FormPrompt } from './FormPrompt'
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: () => ({ preferences: undefined }),
|
||||
}))
|
||||
|
||||
function render(ui: ReactElement) {
|
||||
return renderRaw(ui, { wrapper: KeyboardShortcutsProvider })
|
||||
}
|
||||
|
||||
function AbortLayer({ onAbort }: { onAbort: () => void }) {
|
||||
useShortcutActions({ abort: onAbort })
|
||||
return null
|
||||
}
|
||||
|
||||
const selectForm: FormInfo = {
|
||||
id: 'form-1',
|
||||
sessionID: 'session-1',
|
||||
@@ -612,4 +627,22 @@ describe('FormPrompt', () => {
|
||||
expect(screen.queryByRole('link', { name: /Approve access/ })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('keyboard shortcuts', () => {
|
||||
it('minimizes once on Escape while expanded without triggering a registered session abort', async () => {
|
||||
const sessionAbort = vi.fn()
|
||||
const onMinimize = vi.fn()
|
||||
render(
|
||||
<>
|
||||
<AbortLayer onAbort={sessionAbort} />
|
||||
<FormPrompt form={selectForm} onReply={vi.fn()} onCancel={vi.fn()} onMinimize={onMinimize} />
|
||||
</>
|
||||
)
|
||||
|
||||
await userEvent.keyboard('{Escape}')
|
||||
|
||||
expect(onMinimize).toHaveBeenCalledTimes(1)
|
||||
expect(sessionAbort).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,7 @@ import type { FormAnswer, FormField, FormInfo } from '@opencode-manager/shared/o
|
||||
import { buildAnswer, hasMissingAnswers, visibleFields } from '@/lib/formFields'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
|
||||
|
||||
type AnswerableFormField = Exclude<FormField, { type: 'external' }>
|
||||
|
||||
@@ -136,6 +137,10 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize }: FormPromptPr
|
||||
onMinimize?.()
|
||||
}
|
||||
|
||||
useShortcutActions({
|
||||
abort: !isMinimized && !expandedCustom ? handleMinimize : undefined,
|
||||
})
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!canSubmit) return
|
||||
setIsSubmitting(true)
|
||||
@@ -161,6 +166,7 @@ export function FormPrompt({ form, onReply, onCancel, onMinimize }: FormPromptPr
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.defaultPrevented) return
|
||||
if (e.key === 'Escape' && !isMinimized && !expandedCustom) {
|
||||
setIsMinimized(true)
|
||||
onMinimize?.()
|
||||
|
||||
@@ -75,7 +75,7 @@ describe('KeyboardShortcuts layout', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /Ctrl\+T/ }))
|
||||
const input = screen.getByPlaceholderText('Press keys...')
|
||||
|
||||
fireEvent.keyDown(input, { key: 'o', ctrlKey: true })
|
||||
fireEvent.keyDown(input, { key: 'x', ctrlKey: true })
|
||||
expect(updateSettings).not.toHaveBeenCalled()
|
||||
expect(input).toHaveValue(`${DEFAULT_LEADER_KEY} → `)
|
||||
|
||||
|
||||
@@ -3,8 +3,7 @@ import { useSettings } from '@/hooks/useSettings'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { Loader2, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
|
||||
import { formatEventModifiers, formatShortcutEvent, isModifierOnlyEvent, normalizeShortcut, resolveDirectShortcuts } from '@/lib/keyboardShortcuts'
|
||||
import { formatEventModifiers, formatShortcutEvent, isModifierOnlyEvent, normalizeShortcut, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
|
||||
import { applyTuiKeybindImport, parseTuiKeybindConfig } from '@/lib/tuiKeybindImport'
|
||||
import { showToast } from '@/lib/toast'
|
||||
|
||||
@@ -131,14 +130,14 @@ export function KeyboardShortcuts() {
|
||||
const [tempLeaderKey, setTempLeaderKey] = useState<string | null>(null)
|
||||
const [currentKeys, setCurrentKeys] = useState<string>('')
|
||||
|
||||
const leaderKey = tempLeaderKey ?? preferences?.leaderKey ?? DEFAULT_LEADER_KEY
|
||||
const directShortcuts = resolveDirectShortcuts(preferences?.directShortcuts, preferences?.keyboardShortcuts)
|
||||
const bindings = useMemo(() => resolveShortcutBindings(preferences), [preferences])
|
||||
const leaderKey = tempLeaderKey ?? bindings.leaderKey
|
||||
const directShortcuts = bindings.directShortcuts
|
||||
|
||||
const shortcuts = useMemo<Record<string, string>>(() => ({
|
||||
...DEFAULT_KEYBOARD_SHORTCUTS,
|
||||
...preferences?.keyboardShortcuts,
|
||||
...bindings.shortcuts,
|
||||
...tempShortcuts
|
||||
}), [preferences?.keyboardShortcuts, tempShortcuts])
|
||||
}), [bindings.shortcuts, tempShortcuts])
|
||||
|
||||
const shortcutGroups = useMemo(() => buildShortcutGroups(shortcuts), [shortcuts])
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { useState } from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from './bottom-sheet'
|
||||
@@ -23,6 +24,18 @@ function renderSheet(isOpen: boolean) {
|
||||
)
|
||||
}
|
||||
|
||||
function AutoFocusSheetHost() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open sheet</button>
|
||||
<BottomSheet isOpen={open} onClose={() => setOpen(false)} ariaLabel="Auto focus sheet">
|
||||
<input aria-label="sheet input" autoFocus />
|
||||
</BottomSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
@@ -200,6 +213,49 @@ describe('BottomSheet', () => {
|
||||
|
||||
expect(screen.getByLabelText('prompt')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('restores focus to the opener when an autoFocus child takes focus on open', async () => {
|
||||
stubMatchMedia(true)
|
||||
render(<AutoFocusSheetHost />)
|
||||
const opener = screen.getByRole('button', { name: 'open sheet' })
|
||||
opener.focus()
|
||||
|
||||
fireEvent.click(opener)
|
||||
expect(screen.getByLabelText('sheet input')).toHaveFocus()
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
|
||||
await waitFor(() => expect(opener).toHaveFocus())
|
||||
})
|
||||
|
||||
it('captures the opener when mounted already open and restores it on close', () => {
|
||||
stubMatchMedia(true)
|
||||
const { rerender } = render(
|
||||
<button type="button">opener</button>,
|
||||
)
|
||||
const opener = screen.getByRole('button', { name: 'opener' })
|
||||
opener.focus()
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<button type="button">opener</button>
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Mounted open sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
|
||||
rerender(
|
||||
<>
|
||||
<button type="button">opener</button>
|
||||
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Mounted open sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>
|
||||
</>,
|
||||
)
|
||||
|
||||
expect(opener).toHaveFocus()
|
||||
})
|
||||
})
|
||||
|
||||
describe('BottomSheetHeader', () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { useSwipeDismiss } from '@/hooks/useMobile'
|
||||
import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
|
||||
import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
|
||||
|
||||
export interface BottomSheetProps {
|
||||
isOpen: boolean
|
||||
@@ -24,8 +24,8 @@ export function BottomSheet({
|
||||
}: BottomSheetProps) {
|
||||
const [shouldRender, setShouldRender] = useState(false)
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const returnFocusRef = useRef<HTMLElement | null>(null)
|
||||
const wasOpenRef = useRef(isOpen)
|
||||
|
||||
useRestoreFocusOnClose(isOpen, panelRef)
|
||||
|
||||
const { bind, swipeStyles } = useSwipeDismiss(onClose, {
|
||||
enabled: isOpen,
|
||||
@@ -45,15 +45,6 @@ export function BottomSheet({
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
returnFocusRef.current = getFocusedElement()
|
||||
} else if (wasOpenRef.current) {
|
||||
restoreOverlayFocus(returnFocusRef.current, panelRef.current)
|
||||
}
|
||||
wasOpenRef.current = isOpen
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && isOpen) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import { useState } from 'react'
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { SideDrawer, SideDrawerHeader, SideDrawerContent } from './side-drawer'
|
||||
@@ -14,6 +15,18 @@ function renderDrawer(isOpen: boolean) {
|
||||
)
|
||||
}
|
||||
|
||||
function AutoFocusDrawerHost() {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open drawer</button>
|
||||
<SideDrawer isOpen={open} onClose={() => setOpen(false)} ariaLabel="Auto focus drawer">
|
||||
<input aria-label="drawer input" autoFocus />
|
||||
</SideDrawer>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
@@ -121,6 +134,20 @@ describe('SideDrawer', () => {
|
||||
|
||||
expect(screen.getByLabelText('prompt')).toHaveFocus()
|
||||
})
|
||||
|
||||
it('restores focus to the opener when an autoFocus child takes focus on open', async () => {
|
||||
stubMatchMedia(true)
|
||||
render(<AutoFocusDrawerHost />)
|
||||
const opener = screen.getByRole('button', { name: 'open drawer' })
|
||||
opener.focus()
|
||||
|
||||
fireEvent.click(opener)
|
||||
expect(screen.getByLabelText('drawer input')).toHaveFocus()
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
|
||||
await waitFor(() => expect(opener).toHaveFocus())
|
||||
})
|
||||
})
|
||||
|
||||
describe('SideDrawerHeader', () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { X } from 'lucide-react'
|
||||
import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
|
||||
import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
|
||||
|
||||
const openDrawerStack: symbol[] = []
|
||||
|
||||
@@ -27,8 +27,8 @@ export function SideDrawer({
|
||||
}: SideDrawerProps) {
|
||||
const [shouldRender, setShouldRender] = useState(false)
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const returnFocusRef = useRef<HTMLElement | null>(null)
|
||||
const wasOpenRef = useRef(isOpen)
|
||||
|
||||
useRestoreFocusOnClose(isOpen, panelRef)
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
@@ -39,15 +39,6 @@ export function SideDrawer({
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
returnFocusRef.current = getFocusedElement()
|
||||
} else if (wasOpenRef.current) {
|
||||
restoreOverlayFocus(returnFocusRef.current, panelRef.current)
|
||||
}
|
||||
wasOpenRef.current = isOpen
|
||||
}, [isOpen])
|
||||
|
||||
const onCloseRef = useRef(onClose)
|
||||
useEffect(() => {
|
||||
onCloseRef.current = onClose
|
||||
|
||||
@@ -5,7 +5,7 @@ import { KeyboardShortcutsProvider, useShortcutActions, type ShortcutActions } f
|
||||
|
||||
const { preferences } = vi.hoisted(() => ({
|
||||
preferences: {
|
||||
leaderKey: 'Ctrl+O',
|
||||
leaderKey: 'Ctrl+X',
|
||||
keyboardShortcuts: { submit: 'Ctrl+Enter', abort: 'Escape', newSession: 'N' } as Record<string, string>,
|
||||
directShortcuts: ['submit', 'abort'],
|
||||
},
|
||||
@@ -66,21 +66,21 @@ describe('KeyboardShortcutsProvider', () => {
|
||||
renderProvider(<ActionLayer actions={{ newSession }} />)
|
||||
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
|
||||
|
||||
expect(pressKey(prompt, { key: 'o', ctrlKey: true }).defaultPrevented).toBe(true)
|
||||
expect(pressKey(prompt, { key: 'x', ctrlKey: true }).defaultPrevented).toBe(true)
|
||||
const followUp = pressKey(prompt, { key: 'n' })
|
||||
|
||||
expect(newSession).toHaveBeenCalledTimes(1)
|
||||
expect(followUp.defaultPrevented).toBe(true)
|
||||
})
|
||||
|
||||
it('applies new default actions as direct shortcuts for users with legacy stored preferences', () => {
|
||||
const toggleTerminal = vi.fn()
|
||||
renderProvider(<ActionLayer actions={{ toggleTerminal }} />)
|
||||
it('applies new default direct actions for users with stored preferences that predate them', () => {
|
||||
const variantCycle = vi.fn()
|
||||
renderProvider(<ActionLayer actions={{ variantCycle }} />)
|
||||
const input = mountElement('textarea')
|
||||
|
||||
pressKey(input, { key: '`', ctrlKey: true })
|
||||
pressKey(input, { key: 't', ctrlKey: true })
|
||||
|
||||
expect(toggleTerminal).toHaveBeenCalledTimes(1)
|
||||
expect(variantCycle).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('leaves submit to the focused input and only interrupts from the prompt', () => {
|
||||
@@ -198,6 +198,38 @@ describe('KeyboardShortcutsProvider', () => {
|
||||
expect(halfPageDown).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('runs a direct half-page-up shortcut with Ctrl+U from the body and the prompt, never from another text field', () => {
|
||||
const halfPageUp = vi.fn()
|
||||
renderProvider(<ActionLayer actions={{ halfPageUp }} />)
|
||||
const prompt = mountElement('textarea', { 'data-prompt-input': '' })
|
||||
const otherInput = mountElement('input')
|
||||
|
||||
expect(pressKey(otherInput, { key: 'u', ctrlKey: true }).defaultPrevented).toBe(false)
|
||||
expect(halfPageUp).not.toHaveBeenCalled()
|
||||
|
||||
expect(pressKey(document.body, { key: 'u', ctrlKey: true }).defaultPrevented).toBe(true)
|
||||
expect(pressKey(prompt, { key: 'u', ctrlKey: true }).defaultPrevented).toBe(true)
|
||||
expect(halfPageUp).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('does not abort while a dialog overlay is open, leaving Escape to the overlay', () => {
|
||||
const abort = vi.fn()
|
||||
renderProvider(<ActionLayer actions={{ abort }} />)
|
||||
mountElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
|
||||
expect(pressKey(document.body, { key: 'Escape' }).defaultPrevented).toBe(false)
|
||||
expect(abort).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('aborts with Escape when no dialog overlay is open', () => {
|
||||
const abort = vi.fn()
|
||||
renderProvider(<ActionLayer actions={{ abort }} />)
|
||||
mountElement('div', { role: 'dialog', 'data-state': 'closed' })
|
||||
|
||||
expect(pressKey(document.body, { key: 'Escape' }).defaultPrevented).toBe(true)
|
||||
expect(abort).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('runs leader and direct shortcuts from a terminal before it consumes the keys, passing other keys through', () => {
|
||||
const newSession = vi.fn()
|
||||
const toggleTerminal = vi.fn()
|
||||
@@ -210,9 +242,10 @@ describe('KeyboardShortcutsProvider', () => {
|
||||
event.preventDefault()
|
||||
})
|
||||
|
||||
pressKey(terminalInput, { key: 'o', ctrlKey: true })
|
||||
pressKey(terminalInput, { key: 'x', ctrlKey: true })
|
||||
pressKey(terminalInput, { key: 'n' })
|
||||
pressKey(terminalInput, { key: '`', ctrlKey: true })
|
||||
pressKey(terminalInput, { key: 'x', ctrlKey: true })
|
||||
pressKey(terminalInput, { key: 't' })
|
||||
pressKey(terminalInput, { key: 'l' })
|
||||
|
||||
expect(newSession).toHaveBeenCalledTimes(1)
|
||||
@@ -220,6 +253,24 @@ describe('KeyboardShortcutsProvider', () => {
|
||||
expect(shellInput.mock.calls).toEqual([['l']])
|
||||
})
|
||||
|
||||
it('passes direct shortcuts through in a terminal while keeping the leader and toggleTerminal', () => {
|
||||
const variantCycle = vi.fn()
|
||||
const halfPageUp = vi.fn()
|
||||
const toggleTerminal = vi.fn()
|
||||
renderProvider(<ActionLayer actions={{ variantCycle, halfPageUp, toggleTerminal }} />)
|
||||
const terminal = mountElement('div', { 'data-terminal-id': 'pty-2' })
|
||||
const terminalInput = terminal.appendChild(document.createElement('textarea'))
|
||||
|
||||
expect(pressKey(terminalInput, { key: 't', ctrlKey: true }).defaultPrevented).toBe(false)
|
||||
expect(pressKey(terminalInput, { key: 'u', ctrlKey: true }).defaultPrevented).toBe(false)
|
||||
expect(variantCycle).not.toHaveBeenCalled()
|
||||
expect(halfPageUp).not.toHaveBeenCalled()
|
||||
|
||||
pressKey(terminalInput, { key: 'x', ctrlKey: true })
|
||||
expect(pressKey(terminalInput, { key: 't' }).defaultPrevented).toBe(true)
|
||||
expect(toggleTerminal).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('ignores key events a component already handled', () => {
|
||||
const abort = vi.fn()
|
||||
renderProvider(<ActionLayer actions={{ abort }} />)
|
||||
@@ -296,7 +347,7 @@ describe('KeyboardShortcutsProvider', () => {
|
||||
const newSession = vi.fn()
|
||||
renderProvider(<ActionLayer actions={{ newSession }} />)
|
||||
|
||||
pressKey(document.body, { key: 'o', ctrlKey: true })
|
||||
pressKey(document.body, { key: 'x', ctrlKey: true })
|
||||
expect(screen.getByText('Waiting for shortcut key...')).toBeInTheDocument()
|
||||
|
||||
pressKey(document.body, { key: 'n' })
|
||||
|
||||
@@ -3,6 +3,8 @@ import { createContext, useCallback, useContext, useEffect, useRef, useState, ty
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import type { KeyboardShortcutAction } from '@/api/types/settings'
|
||||
import { findShortcutAction, formatShortcutEvent, hasCommandModifier, resolveShortcutBindings } from '@/lib/keyboardShortcuts'
|
||||
import { isPromptInput, isTextEntryElement } from '@/lib/domTargets'
|
||||
import { hasOpenOverlay } from '@/lib/overlayFocus'
|
||||
|
||||
const LEADER_TIMEOUT = 2000
|
||||
|
||||
@@ -19,15 +21,9 @@ interface ShortcutRegistry {
|
||||
|
||||
const KeyboardShortcutsRegistryContext = createContext<ShortcutRegistry | null>(null)
|
||||
|
||||
function isTextInput(target: HTMLElement): boolean {
|
||||
return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable
|
||||
}
|
||||
|
||||
const PROMPT_ONLY_DIRECT_ACTIONS: ReadonlySet<string> = new Set(['toggleMode', 'clearPrompt'])
|
||||
|
||||
function isPromptInput(target: HTMLElement): boolean {
|
||||
return target.hasAttribute('data-prompt-input')
|
||||
}
|
||||
const HALF_PAGE_DIRECT_ACTIONS: ReadonlySet<string> = new Set(['halfPageUp', 'halfPageDown'])
|
||||
|
||||
function typesCharacter(shortcut: string): boolean {
|
||||
return !hasCommandModifier(shortcut) && /(^|\+).$/.test(shortcut)
|
||||
@@ -36,13 +32,15 @@ function typesCharacter(shortcut: string): boolean {
|
||||
/**
|
||||
* Whether a direct shortcut may run for this focus target. Prompt-only actions (agent cycling, prompt clearing) run only
|
||||
* from the prompt and never on a key that types a character. `submit` runs only from the prompt, so a submit bound to
|
||||
* plain Enter sends the prompt without hijacking Enter on buttons or other fields; `abort` runs from the prompt or with
|
||||
* no text field focused; other text inputs only accept modified shortcuts.
|
||||
* plain Enter sends the prompt without hijacking Enter on buttons or other fields. Half-page scrolling runs only from the
|
||||
* prompt or a non-text target, so it never hijacks Ctrl+U/Ctrl+D inside another text field. `abort` runs from the prompt
|
||||
* or with no text field focused; other text inputs only accept modified shortcuts.
|
||||
*/
|
||||
function isDirectActionAllowed(action: string, shortcut: string, target: HTMLElement): boolean {
|
||||
if (PROMPT_ONLY_DIRECT_ACTIONS.has(action)) return isPromptInput(target) && !typesCharacter(shortcut)
|
||||
if (action === 'submit') return isPromptInput(target)
|
||||
if (!isTextInput(target)) return true
|
||||
if (HALF_PAGE_DIRECT_ACTIONS.has(action)) return isPromptInput(target) || !isTextEntryElement(target)
|
||||
if (!isTextEntryElement(target)) return true
|
||||
if (action === 'abort') return isPromptInput(target)
|
||||
return hasCommandModifier(shortcut)
|
||||
}
|
||||
@@ -89,6 +87,7 @@ export function KeyboardShortcutsProvider({ children }: { children: ReactNode })
|
||||
|
||||
const runAction = useCallback((action: string | undefined, e: KeyboardEvent): boolean => {
|
||||
if (!action) return false
|
||||
if (action === 'abort' && hasOpenOverlay()) return false
|
||||
const handler = findHandler(registryRef.current, action)
|
||||
if (!handler) return false
|
||||
e.preventDefault()
|
||||
@@ -112,7 +111,7 @@ export function KeyboardShortcutsProvider({ children }: { children: ReactNode })
|
||||
return runAction(findShortcutAction(bindings, shortcut, false), e)
|
||||
}
|
||||
|
||||
if (shortcut === bindings.leaderKey && (!isTextInput(target) || hasCommandModifier(shortcut))) {
|
||||
if (shortcut === bindings.leaderKey && (!isTextEntryElement(target) || hasCommandModifier(shortcut))) {
|
||||
e.preventDefault()
|
||||
setLeader(true)
|
||||
return true
|
||||
@@ -120,6 +119,7 @@ export function KeyboardShortcutsProvider({ children }: { children: ReactNode })
|
||||
|
||||
const directAction = findShortcutAction(bindings, shortcut, true)
|
||||
if (!directAction) return false
|
||||
if (isTerminalTarget(e.target) && directAction !== 'toggleTerminal') return false
|
||||
if (!isDirectActionAllowed(directAction, shortcut, target)) return false
|
||||
return runAction(directAction, e)
|
||||
}
|
||||
|
||||
@@ -30,6 +30,13 @@ function createScrollContainer() {
|
||||
},
|
||||
})
|
||||
|
||||
Object.defineProperty(div, 'scrollBy', {
|
||||
configurable: true,
|
||||
value: (options?: ScrollToOptions) => {
|
||||
div.scrollTop = scrollTopValue + (options?.top ?? 0)
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
div,
|
||||
setScrollHeight: (value: number) => {
|
||||
@@ -367,6 +374,45 @@ describe('useAutoScroll', () => {
|
||||
expect(containerHarness.getScrollTop()).toBe(100)
|
||||
})
|
||||
|
||||
it('does not scroll to bottom on content update after a half-page scroll up', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(100)
|
||||
})
|
||||
|
||||
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
|
||||
expect(containerHarness.getScrollTop()).toBe(bottomPosition)
|
||||
|
||||
act(() => {
|
||||
renderResult.result.current.scrollByUser(-containerHarness.div.clientHeight / 2)
|
||||
})
|
||||
|
||||
const halfPagePosition = containerHarness.getScrollTop()
|
||||
expect(halfPagePosition).toBe(bottomPosition - containerHarness.div.clientHeight / 2)
|
||||
expect(onScrollStateChange).toHaveBeenCalledWith(true)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(400)
|
||||
})
|
||||
|
||||
containerHarness.setScrollHeight(containerHarness.div.scrollHeight + 200)
|
||||
|
||||
act(() => {
|
||||
renderResult.rerender({
|
||||
containerRef: { current: containerHarness.div },
|
||||
messages,
|
||||
sessionId: 'session-1',
|
||||
contentVersion: messages.length + 1,
|
||||
onScrollStateChange,
|
||||
})
|
||||
vi.advanceTimersByTime(100)
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(halfPagePosition)
|
||||
})
|
||||
|
||||
it('shows scroll button when streaming growth carries disengaged user past threshold', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
@@ -16,6 +16,7 @@ interface UseAutoScrollOptions {
|
||||
|
||||
interface UseAutoScrollReturn {
|
||||
scrollToBottom: () => void
|
||||
scrollByUser: (delta: number) => void
|
||||
}
|
||||
|
||||
export function useAutoScroll({
|
||||
@@ -62,6 +63,28 @@ export function useAutoScroll({
|
||||
onScrollStateChangeRef.current?.(false)
|
||||
}, [containerRef])
|
||||
|
||||
const markDisengaged = useCallback(() => {
|
||||
const container = containerRef?.current
|
||||
if (!container) return
|
||||
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight
|
||||
userScrolledAtRef.current = Date.now()
|
||||
scrollRequestIdRef.current += 1
|
||||
if (!isScrollButtonVisibleRef.current && distanceFromBottom > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
|
||||
isScrollButtonVisibleRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
userDisengagedRef.current = true
|
||||
}, [containerRef])
|
||||
|
||||
const scrollByUser = useCallback((delta: number) => {
|
||||
const container = containerRef?.current
|
||||
if (!container) return
|
||||
if (delta < 0) {
|
||||
markDisengaged()
|
||||
}
|
||||
container.scrollBy({ top: delta })
|
||||
}, [containerRef, markDisengaged])
|
||||
|
||||
useEffect(() => {
|
||||
lastMessageCountRef.current = 0
|
||||
lastMessageIdRef.current = undefined
|
||||
@@ -76,19 +99,6 @@ export function useAutoScroll({
|
||||
const container = containerRef?.current
|
||||
if (!container) return
|
||||
|
||||
const markDisengaged = () => {
|
||||
const container = containerRef?.current
|
||||
if (!container) return
|
||||
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight
|
||||
userScrolledAtRef.current = Date.now()
|
||||
scrollRequestIdRef.current += 1
|
||||
if (!isScrollButtonVisibleRef.current && distanceFromBottom > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
|
||||
isScrollButtonVisibleRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
userDisengagedRef.current = true
|
||||
}
|
||||
|
||||
const updateScrollButtonVisibility = () => {
|
||||
const container = containerRef?.current
|
||||
if (!container || !userDisengagedRef.current || isScrollButtonVisibleRef.current) return
|
||||
@@ -196,7 +206,7 @@ export function useAutoScroll({
|
||||
container.removeEventListener('keydown', handleKeyDown)
|
||||
container.removeEventListener('scroll', handleScroll)
|
||||
}
|
||||
}, [containerRef, sessionId, messages])
|
||||
}, [containerRef, sessionId, messages, markDisengaged])
|
||||
|
||||
useEffect(() => {
|
||||
if (!containerRef?.current || !messages) return
|
||||
@@ -243,5 +253,5 @@ export function useAutoScroll({
|
||||
scrollToBottom()
|
||||
}, [messages, containerRef, scrollToBottom, contentVersion])
|
||||
|
||||
return { scrollToBottom }
|
||||
return { scrollToBottom, scrollByUser }
|
||||
}
|
||||
@@ -20,14 +20,25 @@ export function dialogSearch(name: string, extraParams?: Record<string, string>)
|
||||
return `?${params.toString()}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a dialog in an existing param set: sets `dialog` to `name`, applies `extraParams`, and clears `mobileTab`.
|
||||
*/
|
||||
export function openDialogParams(
|
||||
params: URLSearchParams,
|
||||
name: string,
|
||||
extraParams?: Record<string, string>,
|
||||
): void {
|
||||
setDialogParams(params, name, extraParams)
|
||||
params.delete('mobileTab')
|
||||
}
|
||||
|
||||
export function openDialogParam(
|
||||
updateParams: ReturnType<typeof useUrlParams>['updateParams'],
|
||||
name: string,
|
||||
extraParams?: Record<string, string>,
|
||||
): void {
|
||||
updateParams((p) => {
|
||||
setDialogParams(p, name, extraParams)
|
||||
p.delete('mobileTab')
|
||||
openDialogParams(p, name, extraParams)
|
||||
}, 'push')
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +47,11 @@ function pressKey(init: KeyboardEventInit) {
|
||||
return event
|
||||
}
|
||||
|
||||
function pressLeaderFollowUp(key: string) {
|
||||
pressKey({ key: 'o', ctrlKey: true })
|
||||
pressKey({ key })
|
||||
}
|
||||
|
||||
describe('useGlobalShortcutActions', () => {
|
||||
let queryClient: QueryClient
|
||||
|
||||
@@ -81,7 +86,7 @@ describe('useGlobalShortcutActions', () => {
|
||||
it('opens the terminal dialog on the assistant host from the root route', async () => {
|
||||
const { location } = renderHarness('/')
|
||||
|
||||
pressKey({ key: '`', ctrlKey: true })
|
||||
pressLeaderFollowUp('t')
|
||||
|
||||
await waitFor(() => expect(location()).toBe('/assistant?dialog=terminal'))
|
||||
})
|
||||
@@ -89,7 +94,7 @@ describe('useGlobalShortcutActions', () => {
|
||||
it('navigates to the nearest repo host from a repo sub-route without the tool', async () => {
|
||||
const { location } = renderHarness('/repos/5/schedules')
|
||||
|
||||
pressKey({ key: '`', ctrlKey: true })
|
||||
pressLeaderFollowUp('t')
|
||||
|
||||
await waitFor(() => expect(location()).toBe('/repos/5?dialog=terminal'))
|
||||
})
|
||||
@@ -97,10 +102,10 @@ describe('useGlobalShortcutActions', () => {
|
||||
it('toggles the docked panel on and off when the route hosts the tool', async () => {
|
||||
const { location } = renderHarness('/repos/5')
|
||||
|
||||
pressKey({ key: '`', ctrlKey: true })
|
||||
pressLeaderFollowUp('t')
|
||||
await waitFor(() => expect(location()).toBe('/repos/5?panel=terminal'))
|
||||
|
||||
pressKey({ key: '`', ctrlKey: true })
|
||||
pressLeaderFollowUp('t')
|
||||
await waitFor(() => expect(location()).toBe('/repos/5'))
|
||||
})
|
||||
|
||||
@@ -108,7 +113,7 @@ describe('useGlobalShortcutActions', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
const { location } = renderHarness('/repos/5')
|
||||
|
||||
pressKey({ key: '`', ctrlKey: true })
|
||||
pressLeaderFollowUp('t')
|
||||
|
||||
await waitFor(() => expect(location()).toBe('/repos/5?dialog=terminal'))
|
||||
})
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useCallback, useMemo } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { ASSISTANT_REPO_ID } from '@opencode-manager/shared/utils'
|
||||
import { getRepo } from '@/api/repos'
|
||||
import { buildToolItems } from '@/components/navigation/moreDrawerItems'
|
||||
import { buildToolItems, toolKeyOf } from '@/components/navigation/moreDrawerItems'
|
||||
import { useShortcutActions } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { dialogSearch } from '@/hooks/useDialogParam'
|
||||
import { useCreateSession } from '@/hooks/useOpenCode'
|
||||
@@ -37,10 +37,11 @@ export function useGlobalShortcutActions(): void {
|
||||
navigate(getSessionPath(repoId, session.id))
|
||||
})
|
||||
|
||||
const hasFilesTool = buildToolItems(pathname).some((item) => (item.panelTool ?? item.dialog) === 'files')
|
||||
const toolItems = useMemo(() => buildToolItems(pathname), [pathname])
|
||||
const hasFilesTool = toolItems.some((item) => toolKeyOf(item) === 'files')
|
||||
|
||||
const toggleRouteTool = useCallback((tool: PanelTool) => {
|
||||
if (buildToolItems(pathname).some((item) => (item.panelTool ?? item.dialog) === tool)) {
|
||||
if (toolItems.some((item) => toolKeyOf(item) === tool)) {
|
||||
updateParams((params) => {
|
||||
if (isMobile) toggleToolDialogParams(params, tool)
|
||||
else toggleToolPanelParams(params, tool)
|
||||
@@ -50,7 +51,7 @@ export function useGlobalShortcutActions(): void {
|
||||
if (tool === 'files') return
|
||||
const host = repoId !== null ? getRepoPath(repoId) : getAssistantPath()
|
||||
navigate(`${host}${dialogSearch(tool)}`)
|
||||
}, [pathname, isMobile, updateParams, navigate, repoId])
|
||||
}, [toolItems, isMobile, updateParams, navigate, repoId])
|
||||
|
||||
const newSession = repoId !== null && repo?.fullPath && !createSession.isPending
|
||||
? () => createSession.mutate({})
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useEffect, useRef, type RefObject } from 'react'
|
||||
import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
|
||||
|
||||
/**
|
||||
* Captures the focused element when an overlay opens and restores focus to it when the overlay closes.
|
||||
*
|
||||
* The opener is captured during render on the closed-to-open transition, before children with
|
||||
* `autoFocus` claim focus during commit, and is idempotent across StrictMode's double render.
|
||||
*/
|
||||
export function useRestoreFocusOnClose(
|
||||
isOpen: boolean,
|
||||
containerRef: RefObject<HTMLElement | null>,
|
||||
): void {
|
||||
const returnFocusRef = useRef<HTMLElement | null>(null)
|
||||
const wasOpenRef = useRef(false)
|
||||
|
||||
if (isOpen && !wasOpenRef.current) {
|
||||
returnFocusRef.current = getFocusedElement()
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen && wasOpenRef.current) {
|
||||
restoreOverlayFocus(returnFocusRef.current, containerRef.current)
|
||||
}
|
||||
wasOpenRef.current = isOpen
|
||||
}, [isOpen, containerRef])
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect } from 'react'
|
||||
import { openDialogParams } from './useDialogParam'
|
||||
import { useUrlParams } from './useUrlParams'
|
||||
|
||||
const PANEL_PARAM = 'panel'
|
||||
@@ -42,8 +43,7 @@ export function toggleToolDialogParams(params: URLSearchParams, tool: PanelTool)
|
||||
clearToolParams(params)
|
||||
return
|
||||
}
|
||||
params.set('dialog', tool)
|
||||
params.delete('mobileTab')
|
||||
openDialogParams(params, tool)
|
||||
clearToolParams(params, tool)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
const CONTENT_EDITABLE_VALUES = new Set(['', 'true', 'plaintext-only'])
|
||||
|
||||
/**
|
||||
* Returns true for free-text entry targets: `<input>`, `<textarea>`, and any content-editable
|
||||
* element (`contenteditable=""`, `"true"`, or `"plaintext-only"`).
|
||||
*/
|
||||
export function isTextEntryElement(element: Element): boolean {
|
||||
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) return true
|
||||
if (!(element instanceof HTMLElement)) return false
|
||||
if (element.isContentEditable) return true
|
||||
const contentEditable = element.getAttribute('contenteditable')
|
||||
return contentEditable !== null && CONTENT_EDITABLE_VALUES.has(contentEditable.toLowerCase())
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when the element carries the `data-prompt-input` attribute that marks the chat prompt.
|
||||
*/
|
||||
export function isPromptInput(element: Element): boolean {
|
||||
return element.hasAttribute('data-prompt-input')
|
||||
}
|
||||
|
||||
/**
|
||||
* Selector matching the chat prompt input.
|
||||
*/
|
||||
export const PROMPT_INPUT_SELECTOR = 'textarea[data-prompt-input]'
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { DEFAULT_DIRECT_SHORTCUTS } from '@/api/types/settings'
|
||||
import { formatShortcutEvent, normalizeShortcut, resolveDirectShortcuts } from './keyboardShortcuts'
|
||||
import { DEFAULT_DIRECT_SHORTCUTS, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_LEADER_KEY } from '@/api/types/settings'
|
||||
import { formatShortcutEvent, getDefaultKeyboardShortcuts, normalizeShortcut, resolveDirectShortcuts, resolveShortcutBindings } from './keyboardShortcuts'
|
||||
|
||||
describe('keyboardShortcuts', () => {
|
||||
it('normalizes key aliases, modifier order and bare symbol keys', () => {
|
||||
@@ -16,9 +16,12 @@ describe('keyboardShortcuts', () => {
|
||||
expect(formatShortcutEvent(new KeyboardEvent('keydown', { key: 'Shift', shiftKey: true }))).toBeNull()
|
||||
})
|
||||
|
||||
it('upgrades only the untouched legacy direct-shortcut list', () => {
|
||||
expect(resolveDirectShortcuts(['abort', 'submit'])).toBe(DEFAULT_DIRECT_SHORTCUTS)
|
||||
expect(resolveDirectShortcuts(['submit'])).toEqual(['submit'])
|
||||
it('returns the shared defaults with the key set', () => {
|
||||
expect(Object.keys(getDefaultKeyboardShortcuts())).toEqual(Object.keys(DEFAULT_KEYBOARD_SHORTCUTS))
|
||||
})
|
||||
|
||||
it('never rewrites a stored direct-shortcut list', () => {
|
||||
expect(resolveDirectShortcuts(['abort', 'submit'])).toEqual(['abort', 'submit'])
|
||||
expect(resolveDirectShortcuts(undefined)).toBe(DEFAULT_DIRECT_SHORTCUTS)
|
||||
})
|
||||
|
||||
@@ -27,6 +30,48 @@ describe('keyboardShortcuts', () => {
|
||||
expect(resolveDirectShortcuts(['submit'], { submit: 'Return', abort: 'Escape' })).toEqual(
|
||||
DEFAULT_DIRECT_SHORTCUTS.filter((action) => action !== 'abort'),
|
||||
)
|
||||
expect(resolveDirectShortcuts(['abort', 'submit'], { abort: 'Escape', submit: 'Return' })).toBe(DEFAULT_DIRECT_SHORTCUTS)
|
||||
expect(resolveDirectShortcuts(['abort', 'submit'], { abort: 'Escape', submit: 'Return' })).toEqual([
|
||||
'abort',
|
||||
'submit',
|
||||
...DEFAULT_DIRECT_SHORTCUTS.filter((action) => action !== 'abort' && action !== 'submit'),
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves the built-in bindings for a user with no stored preferences', () => {
|
||||
const bindings = resolveShortcutBindings(undefined)
|
||||
expect(bindings.leaderKey).toBe(DEFAULT_LEADER_KEY)
|
||||
expect(bindings.shortcuts.submit).toBe(DEFAULT_KEYBOARD_SHORTCUTS.submit)
|
||||
expect(bindings.shortcuts.toggleMode).toBe('Shift+Tab')
|
||||
expect(bindings.shortcuts.toggleTerminal).toBe('T')
|
||||
expect(bindings.shortcuts.halfPageDown).toBe('Ctrl+D')
|
||||
expect(bindings.directShortcuts).toBe(DEFAULT_DIRECT_SHORTCUTS)
|
||||
})
|
||||
|
||||
it('keeps stored bindings and fills the rest from the defaults', () => {
|
||||
const bindings = resolveShortcutBindings({
|
||||
keyboardShortcuts: { submit: 'Return', newSession: 'K' },
|
||||
directShortcuts: ['submit'],
|
||||
})
|
||||
expect(bindings.shortcuts.submit).toBe('Return')
|
||||
expect(bindings.shortcuts.newSession).toBe('K')
|
||||
expect(bindings.shortcuts.toggleMode).toBe('Shift+Tab')
|
||||
})
|
||||
|
||||
it('drops a new default that would collide with a stored binding of the same kind', () => {
|
||||
const bindings = resolveShortcutBindings({
|
||||
keyboardShortcuts: { toggleMode: 'T' },
|
||||
directShortcuts: ['submit', 'abort'],
|
||||
})
|
||||
expect(bindings.shortcuts.toggleMode).toBe('T')
|
||||
expect(bindings.shortcuts.toggleTerminal).toBe('')
|
||||
})
|
||||
|
||||
it('keeps a new default whose kind differs from the stored binding on the same key', () => {
|
||||
const bindings = resolveShortcutBindings({
|
||||
keyboardShortcuts: { toggleMode: 'T' },
|
||||
directShortcuts: ['submit', 'abort', 'toggleMode'],
|
||||
})
|
||||
expect(bindings.shortcuts.toggleMode).toBe('T')
|
||||
expect(bindings.shortcuts.toggleTerminal).toBe('T')
|
||||
})
|
||||
})
|
||||
@@ -18,8 +18,6 @@ const KEY_ALIASES: Record<string, string> = {
|
||||
Escape: 'Esc',
|
||||
}
|
||||
|
||||
const LEGACY_DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
|
||||
|
||||
interface ShortcutPreferences {
|
||||
leaderKey?: string
|
||||
directShortcuts?: string[]
|
||||
@@ -82,27 +80,61 @@ export function hasCommandModifier(shortcut: string): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* The direct-shortcut list, upgrading the untouched legacy default and adding any default direct action that the stored
|
||||
* shortcut map does not yet know about, so newly added direct defaults reach users who customized their list. When
|
||||
* `storedShortcuts` is omitted the list is returned unchanged apart from the legacy upgrade.
|
||||
* The built-in shortcut defaults for the current platform: the shared table plus the macOS-only clear-prompt binding,
|
||||
* which shared cannot express because it must contain no platform detection.
|
||||
*/
|
||||
export function getDefaultKeyboardShortcuts(): Record<string, string> {
|
||||
return {
|
||||
...DEFAULT_KEYBOARD_SHORTCUTS,
|
||||
clearPrompt: isMac ? 'Ctrl+C' : '',
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The direct-shortcut list, adding any default direct action that the stored shortcut map does not yet know about, so
|
||||
* newly added direct defaults reach users who customized their list. A default direct action that is already a key of
|
||||
* the stored map is treated as stored, never re-added. When `storedShortcuts` is omitted the list is returned unchanged.
|
||||
*/
|
||||
export function resolveDirectShortcuts(directShortcuts: string[] | undefined, storedShortcuts?: Record<string, string>): string[] {
|
||||
if (!directShortcuts) return DEFAULT_DIRECT_SHORTCUTS
|
||||
const isLegacyDefault = directShortcuts.length === LEGACY_DEFAULT_DIRECT_SHORTCUTS.length
|
||||
&& LEGACY_DEFAULT_DIRECT_SHORTCUTS.every((action) => directShortcuts.includes(action))
|
||||
const resolved = isLegacyDefault ? DEFAULT_DIRECT_SHORTCUTS : directShortcuts
|
||||
if (!storedShortcuts) return resolved
|
||||
if (!storedShortcuts) return directShortcuts
|
||||
const additions = DEFAULT_DIRECT_SHORTCUTS.filter(
|
||||
(action) => !(action in storedShortcuts) && !resolved.includes(action),
|
||||
(action) => !(action in storedShortcuts) && !directShortcuts.includes(action),
|
||||
)
|
||||
return additions.length > 0 ? [...resolved, ...additions] : resolved
|
||||
return additions.length > 0 ? [...directShortcuts, ...additions] : directShortcuts
|
||||
}
|
||||
|
||||
function bindingSignature(action: string, keys: string, directShortcuts: string[]): string {
|
||||
const kind = directShortcuts.includes(action) ? 'direct' : 'leader'
|
||||
return `${kind}:${normalizeShortcut(keys)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The effective shortcut map: stored bindings always win, defaults fill the actions the user never stored, and a default
|
||||
* for an action outside the stored map is dropped to unbound when its normalized key and leader/direct kind would
|
||||
* collide with a binding that is stored.
|
||||
*/
|
||||
function resolveShortcutMap(stored: Record<string, string>, directShortcuts: string[]): Record<string, string> {
|
||||
const resolved: Record<string, string> = { ...stored }
|
||||
const storedBindings = new Set(
|
||||
Object.entries(stored)
|
||||
.filter(([, keys]) => Boolean(keys))
|
||||
.map(([action, keys]) => bindingSignature(action, keys, directShortcuts)),
|
||||
)
|
||||
for (const [action, defaultKeys] of Object.entries(getDefaultKeyboardShortcuts())) {
|
||||
if (action in stored) continue
|
||||
const collides = Boolean(defaultKeys) && storedBindings.has(bindingSignature(action, defaultKeys, directShortcuts))
|
||||
resolved[action] = collides ? '' : defaultKeys
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
export function resolveShortcutBindings(preferences: ShortcutPreferences | undefined): ShortcutBindings {
|
||||
const directShortcuts = resolveDirectShortcuts(preferences?.directShortcuts, preferences?.keyboardShortcuts)
|
||||
return {
|
||||
leaderKey: normalizeShortcut(preferences?.leaderKey || DEFAULT_LEADER_KEY),
|
||||
shortcuts: { ...DEFAULT_KEYBOARD_SHORTCUTS, ...preferences?.keyboardShortcuts },
|
||||
directShortcuts: resolveDirectShortcuts(preferences?.directShortcuts, preferences?.keyboardShortcuts),
|
||||
shortcuts: resolveShortcutMap(preferences?.keyboardShortcuts ?? {}, directShortcuts),
|
||||
directShortcuts,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { getFocusedElement, restoreOverlayFocus } from './overlayFocus'
|
||||
import { getFocusedElement, hasOpenOverlay, restoreOverlayFocus } from './overlayFocus'
|
||||
import { PROMPT_INPUT_SELECTOR, isPromptInput, isTextEntryElement } from './domTargets'
|
||||
|
||||
function createElement<K extends keyof HTMLElementTagNameMap>(
|
||||
tag: K,
|
||||
@@ -107,4 +108,100 @@ describe('restoreOverlayFocus', () => {
|
||||
expect(moved).toBe(true)
|
||||
expect(document.activeElement).toBe(button)
|
||||
})
|
||||
|
||||
it('returns false for a disabled button inside another open overlay', () => {
|
||||
stubMatchMedia(true)
|
||||
const overlay = createElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
const disabled = createElement('button')
|
||||
disabled.disabled = true
|
||||
overlay.appendChild(disabled)
|
||||
|
||||
const moved = restoreOverlayFocus(disabled, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(disabled)
|
||||
})
|
||||
|
||||
it('returns false for a disabled input inside another open overlay', () => {
|
||||
stubMatchMedia(true)
|
||||
const overlay = createElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
const disabled = createElement('input')
|
||||
disabled.disabled = true
|
||||
overlay.appendChild(disabled)
|
||||
|
||||
const moved = restoreOverlayFocus(disabled, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(disabled)
|
||||
})
|
||||
|
||||
it('returns false for a disabled button when no prompt exists', () => {
|
||||
stubMatchMedia(true)
|
||||
const disabled = createElement('button')
|
||||
disabled.disabled = true
|
||||
|
||||
const moved = restoreOverlayFocus(disabled, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(disabled)
|
||||
})
|
||||
|
||||
it('returns false for a disabled input when no prompt exists', () => {
|
||||
stubMatchMedia(true)
|
||||
const disabled = createElement('input')
|
||||
disabled.disabled = true
|
||||
|
||||
const moved = restoreOverlayFocus(disabled, null)
|
||||
|
||||
expect(moved).toBe(false)
|
||||
expect(document.activeElement).not.toBe(disabled)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasOpenOverlay', () => {
|
||||
it('returns false when no overlay is open', () => {
|
||||
expect(hasOpenOverlay()).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when a dialog is open', () => {
|
||||
createElement('div', { role: 'dialog', 'data-state': 'open' })
|
||||
expect(hasOpenOverlay()).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true when an alertdialog is open', () => {
|
||||
createElement('div', { role: 'alertdialog', 'data-state': 'open' })
|
||||
expect(hasOpenOverlay()).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores closed overlays', () => {
|
||||
createElement('div', { role: 'dialog', 'data-state': 'closed' })
|
||||
expect(hasOpenOverlay()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('domTargets', () => {
|
||||
it('treats inputs and textareas as text entry', () => {
|
||||
expect(isTextEntryElement(createElement('input'))).toBe(true)
|
||||
expect(isTextEntryElement(createElement('textarea'))).toBe(true)
|
||||
})
|
||||
|
||||
it('treats contenteditable variants as text entry', () => {
|
||||
expect(isTextEntryElement(createElement('div', { contenteditable: '' }))).toBe(true)
|
||||
expect(isTextEntryElement(createElement('div', { contenteditable: 'true' }))).toBe(true)
|
||||
expect(isTextEntryElement(createElement('div', { contenteditable: 'plaintext-only' }))).toBe(true)
|
||||
})
|
||||
|
||||
it('does not treat contenteditable=false or plain elements as text entry', () => {
|
||||
expect(isTextEntryElement(createElement('div', { contenteditable: 'false' }))).toBe(false)
|
||||
expect(isTextEntryElement(createElement('button'))).toBe(false)
|
||||
})
|
||||
|
||||
it('detects the prompt input by its data attribute', () => {
|
||||
expect(isPromptInput(createElement('textarea', { 'data-prompt-input': '' }))).toBe(true)
|
||||
expect(isPromptInput(createElement('textarea'))).toBe(false)
|
||||
})
|
||||
|
||||
it('exposes the prompt input selector', () => {
|
||||
expect(PROMPT_INPUT_SELECTOR).toBe('textarea[data-prompt-input]')
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,6 @@
|
||||
import { FINE_POINTER_MEDIA_QUERY } from '@/hooks/useMediaQuery'
|
||||
import { PROMPT_INPUT_SELECTOR, isPromptInput, isTextEntryElement } from '@/lib/domTargets'
|
||||
|
||||
const TEXT_FIELD_SELECTOR = 'input, textarea, [contenteditable="true"]'
|
||||
const PROMPT_INPUT_SELECTOR = 'textarea[data-prompt-input]'
|
||||
const OPEN_OVERLAY_SELECTOR = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]'
|
||||
|
||||
/**
|
||||
@@ -21,12 +20,9 @@ function isFinePointer(): boolean {
|
||||
)
|
||||
}
|
||||
|
||||
function isTextField(element: Element): boolean {
|
||||
return element.matches(TEXT_FIELD_SELECTOR)
|
||||
}
|
||||
|
||||
function isDisabledTextField(element: HTMLElement): boolean {
|
||||
return (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) && element.disabled
|
||||
function focusElement(el: HTMLElement): boolean {
|
||||
el.focus({ preventScroll: true })
|
||||
return document.activeElement === el
|
||||
}
|
||||
|
||||
function isInside(element: Element, container: Element | null): boolean {
|
||||
@@ -46,6 +42,14 @@ function findPromptInput(): HTMLTextAreaElement | null {
|
||||
return prompt && prompt.isConnected && !prompt.disabled ? prompt : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether any dialog or alertdialog overlay is currently open.
|
||||
*/
|
||||
export function hasOpenOverlay(): boolean {
|
||||
if (typeof document === 'undefined') return false
|
||||
return document.querySelector(OPEN_OVERLAY_SELECTOR) !== null
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves focus after an overlay closes, preferring the chat prompt on desktop while leaving
|
||||
* touch devices untouched so the on-screen keyboard stays closed.
|
||||
@@ -59,40 +63,38 @@ export function restoreOverlayFocus(returnFocus: HTMLElement | null, closing: El
|
||||
const openOverlays = findOpenOverlays(closing)
|
||||
|
||||
if (openOverlays.length > 0) {
|
||||
if (!returnFocus?.isConnected) return false
|
||||
if (!openOverlays.some((overlay) => overlay.contains(returnFocus))) return false
|
||||
if (isTextField(returnFocus) && !isDesktop) return false
|
||||
returnFocus.focus({ preventScroll: true })
|
||||
return true
|
||||
const target = returnFocus
|
||||
return Boolean(
|
||||
target?.isConnected &&
|
||||
openOverlays.some((overlay) => overlay.contains(target)) &&
|
||||
(isDesktop || !isTextEntryElement(target)) &&
|
||||
focusElement(target),
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
isDesktop &&
|
||||
returnFocus?.isConnected &&
|
||||
isTextField(returnFocus) &&
|
||||
!returnFocus.matches(PROMPT_INPUT_SELECTOR) &&
|
||||
!isDisabledTextField(returnFocus) &&
|
||||
!isInside(returnFocus, closing)
|
||||
isTextEntryElement(returnFocus) &&
|
||||
!isPromptInput(returnFocus) &&
|
||||
!isInside(returnFocus, closing) &&
|
||||
focusElement(returnFocus)
|
||||
) {
|
||||
returnFocus.focus({ preventScroll: true })
|
||||
return true
|
||||
}
|
||||
|
||||
if (isDesktop) {
|
||||
const prompt = findPromptInput()
|
||||
if (prompt) {
|
||||
prompt.focus({ preventScroll: true })
|
||||
return true
|
||||
}
|
||||
if (prompt && focusElement(prompt)) return true
|
||||
}
|
||||
|
||||
if (
|
||||
returnFocus?.isConnected &&
|
||||
returnFocus !== document.body &&
|
||||
!isInside(returnFocus, closing) &&
|
||||
!(isTextField(returnFocus) && !isDesktop)
|
||||
!(isTextEntryElement(returnFocus) && !isDesktop) &&
|
||||
focusElement(returnFocus)
|
||||
) {
|
||||
returnFocus.focus({ preventScroll: true })
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isRecord } from '@opencode-manager/shared/utils'
|
||||
import type { KeyboardShortcutAction } from '@/api/types/settings'
|
||||
import { parseJsonc } from '@/lib/jsonc'
|
||||
import { normalizeShortcut } from '@/lib/keyboardShortcuts'
|
||||
@@ -104,10 +105,6 @@ const KEY_LABELS = new Map<string, string>([
|
||||
['insert', 'Insert'],
|
||||
])
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function isKeyStroke(value: unknown): value is KeyStroke {
|
||||
return isRecord(value) && typeof value.name === 'string'
|
||||
}
|
||||
|
||||
@@ -99,19 +99,6 @@ export function GlobalSchedules() {
|
||||
selectRun(nextUnreadRun.id)
|
||||
}, [nextUnreadRun, selectRun])
|
||||
|
||||
useEffect(() => {
|
||||
if (scheduleTab !== 'runs' && runId === null) return
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'u' || event.metaKey || event.ctrlKey || event.altKey) return
|
||||
const target = event.target as HTMLElement | null
|
||||
if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)) return
|
||||
event.preventDefault()
|
||||
handleNextUnread()
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [scheduleTab, runId, handleNextUnread])
|
||||
|
||||
const createMutation = useCreateRepoSchedule()
|
||||
const deleteMutation = useDeleteRepoSchedule()
|
||||
const runMutation = useRunRepoSchedule()
|
||||
|
||||
@@ -249,7 +249,7 @@ export function SessionDetail() {
|
||||
|
||||
const messagesContentVersion = useMemo(() => getMessagesContentVersion(messages), [messages]);
|
||||
|
||||
const { scrollToBottom } = useAutoScroll({
|
||||
const { scrollToBottom, scrollByUser } = useAutoScroll({
|
||||
containerRef: messageContainerRef,
|
||||
messages,
|
||||
sessionId,
|
||||
@@ -590,8 +590,8 @@ export function SessionDetail() {
|
||||
const scrollMessagesByHalfPage = useCallback((direction: 1 | -1) => {
|
||||
const container = messageContainerRef.current;
|
||||
if (!container) return;
|
||||
container.scrollBy({ top: direction * container.clientHeight / 2 });
|
||||
}, []);
|
||||
scrollByUser((direction * container.clientHeight) / 2);
|
||||
}, [scrollByUser]);
|
||||
|
||||
useShortcutActions({
|
||||
selectModel: handleOpenModelDialog,
|
||||
|
||||
@@ -63,30 +63,26 @@ export type STTConfig = {
|
||||
lastModelsFetch?: number;
|
||||
};
|
||||
|
||||
const isBrowser = typeof navigator !== 'undefined';
|
||||
const isMac = isBrowser && navigator.platform.toUpperCase().indexOf('MAC') >= 0;
|
||||
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl';
|
||||
|
||||
export const DEFAULT_LEADER_KEY = `${CMD_KEY}+O`;
|
||||
export const DEFAULT_LEADER_KEY = 'Ctrl+X';
|
||||
|
||||
export const DEFAULT_KEYBOARD_SHORTCUTS = {
|
||||
submit: `${CMD_KEY}+Enter`,
|
||||
submit: 'Cmd+Enter',
|
||||
abort: 'Escape',
|
||||
clearPrompt: isMac ? 'Ctrl+C' : '',
|
||||
toggleMode: 'T',
|
||||
undo: 'Z',
|
||||
redo: 'Shift+Z',
|
||||
compact: 'K',
|
||||
fork: 'F',
|
||||
settings: ',',
|
||||
sessions: 'S',
|
||||
clearPrompt: '',
|
||||
toggleMode: 'Shift+Tab',
|
||||
undo: 'U',
|
||||
redo: 'R',
|
||||
compact: 'C',
|
||||
fork: '',
|
||||
settings: '',
|
||||
sessions: 'L',
|
||||
newSession: 'N',
|
||||
closeSession: 'W',
|
||||
toggleSidebar: 'B',
|
||||
selectModel: 'M',
|
||||
variantCycle: 'Ctrl+T',
|
||||
toggleTerminal: 'Ctrl+`',
|
||||
toggleSourceControl: 'D',
|
||||
toggleTerminal: 'T',
|
||||
toggleSourceControl: '',
|
||||
timeline: 'G',
|
||||
exportSession: 'X',
|
||||
halfPageUp: 'Ctrl+U',
|
||||
@@ -95,7 +91,7 @@ export const DEFAULT_KEYBOARD_SHORTCUTS = {
|
||||
|
||||
export type KeyboardShortcutAction = keyof typeof DEFAULT_KEYBOARD_SHORTCUTS;
|
||||
|
||||
export const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort', 'clearPrompt', 'variantCycle', 'toggleTerminal', 'halfPageUp', 'halfPageDown'];
|
||||
export const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort', 'clearPrompt', 'toggleMode', 'variantCycle', 'halfPageUp', 'halfPageDown'];
|
||||
|
||||
export const GitCredentialSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
@@ -243,9 +239,7 @@ export const DEFAULT_USER_PREFERENCES = {
|
||||
groupToolCalls: true,
|
||||
showReasoning: false,
|
||||
simpleChatMode: false,
|
||||
leaderKey: DEFAULT_LEADER_KEY,
|
||||
directShortcuts: DEFAULT_DIRECT_SHORTCUTS,
|
||||
keyboardShortcuts: DEFAULT_KEYBOARD_SHORTCUTS,
|
||||
keyboardShortcuts: {} as Record<string, string>,
|
||||
customCommands: [],
|
||||
customAgents: [],
|
||||
gitCredentials: [] as GitCredential[],
|
||||
|
||||
Reference in new issue
Block a user