From 994a8b82e830a2f819638188b2ac759fd5a589aa Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Thu, 8 Oct 2026 12:40:04 -0400 Subject: [PATCH] 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. --- backend/src/services/assistant-mode.ts | 14 ++- .../message/PromptInput.command.test.tsx | 17 +++ .../src/components/message/PromptInput.tsx | 40 +++---- .../model/ModelQuickSelect.test.tsx | 109 ++++++++++++++++++ .../src/components/model/ModelQuickSelect.tsx | 23 +++- .../components/navigation/ToolSidePanel.tsx | 4 +- .../components/navigation/moreDrawerItems.ts | 5 + .../components/session/FormPrompt.test.tsx | 35 +++++- .../src/components/session/FormPrompt.tsx | 6 + .../settings/KeyboardShortcuts.test.tsx | 2 +- .../components/settings/KeyboardShortcuts.tsx | 13 +-- .../src/components/ui/bottom-sheet.test.tsx | 56 +++++++++ frontend/src/components/ui/bottom-sheet.tsx | 15 +-- .../src/components/ui/side-drawer.test.tsx | 27 +++++ frontend/src/components/ui/side-drawer.tsx | 15 +-- .../KeyboardShortcutsContext.test.tsx | 71 ++++++++++-- .../src/contexts/KeyboardShortcutsContext.tsx | 22 ++-- frontend/src/hooks/useAutoScroll.test.tsx | 46 ++++++++ frontend/src/hooks/useAutoScroll.ts | 40 ++++--- frontend/src/hooks/useDialogParam.ts | 15 ++- .../hooks/useGlobalShortcutActions.test.tsx | 15 ++- .../src/hooks/useGlobalShortcutActions.ts | 11 +- frontend/src/hooks/useRestoreFocusOnClose.ts | 27 +++++ frontend/src/hooks/useToolPanel.ts | 4 +- frontend/src/lib/domTargets.ts | 25 ++++ frontend/src/lib/keyboardShortcuts.test.ts | 57 ++++++++- frontend/src/lib/keyboardShortcuts.ts | 58 +++++++--- frontend/src/lib/overlayFocus.test.ts | 99 +++++++++++++++- frontend/src/lib/overlayFocus.ts | 50 ++++---- frontend/src/lib/tuiKeybindImport.ts | 5 +- frontend/src/pages/GlobalSchedules.tsx | 13 --- frontend/src/pages/SessionDetail.tsx | 6 +- shared/src/schemas/settings.ts | 34 +++--- 33 files changed, 784 insertions(+), 195 deletions(-) create mode 100644 frontend/src/hooks/useRestoreFocusOnClose.ts create mode 100644 frontend/src/lib/domTargets.ts diff --git a/backend/src/services/assistant-mode.ts b/backend/src/services/assistant-mode.ts index fdde614e..8f44f38e 100644 --- a/backend/src/services/assistant-mode.ts +++ b/backend/src/services/assistant-mode.ts @@ -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. diff --git a/frontend/src/components/message/PromptInput.command.test.tsx b/frontend/src/components/message/PromptInput.command.test.tsx index 806e376c..7a9c8723 100644 --- a/frontend/src/components/message/PromptInput.command.test.tsx +++ b/frontend/src/components/message/PromptInput.command.test.tsx @@ -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() diff --git a/frontend/src/components/message/PromptInput.tsx b/frontend/src/components/message/PromptInput.tsx index a8cb2538..034e1228 100644 --- a/frontend/src/components/message/PromptInput.tsx +++ b/frontend/src/components/message/PromptInput.tsx @@ -988,8 +988,7 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) const handleKeyDown = (e: KeyboardEvent) => { 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( () => ({ diff --git a/frontend/src/components/model/ModelQuickSelect.test.tsx b/frontend/src/components/model/ModelQuickSelect.test.tsx index d32d3be1..56a1867d 100644 --- a/frontend/src/components/model/ModelQuickSelect.test.tsx +++ b/frontend/src/components/model/ModelQuickSelect.test.tsx @@ -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() + 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('.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() + 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() + 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() + + 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() + 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() + 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!) + } + }) }) diff --git a/frontend/src/components/model/ModelQuickSelect.tsx b/frontend/src/components/model/ModelQuickSelect.tsx index e381a7c3..3c9343a7 100644 --- a/frontend/src/components/model/ModelQuickSelect.tsx +++ b/frontend/src/components/model/ModelQuickSelect.tsx @@ -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(null) const [activeIndex, setActiveIndex] = useState(0) const quickListRef = useRef(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() @@ -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} /> ) : (
diff --git a/frontend/src/components/navigation/ToolSidePanel.tsx b/frontend/src/components/navigation/ToolSidePanel.tsx index 5ef0ba2a..1c4bd2b9 100644 --- a/frontend/src/components/navigation/ToolSidePanel.tsx +++ b/frontend/src/components/navigation/ToolSidePanel.tsx @@ -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) } diff --git a/frontend/src/components/navigation/moreDrawerItems.ts b/frontend/src/components/navigation/moreDrawerItems.ts index cd366f52..bbed2aa4 100644 --- a/frontend/src/components/navigation/moreDrawerItems.ts +++ b/frontend/src/components/navigation/moreDrawerItems.ts @@ -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() diff --git a/frontend/src/components/session/FormPrompt.test.tsx b/frontend/src/components/session/FormPrompt.test.tsx index 0a976055..45c42320 100644 --- a/frontend/src/components/session/FormPrompt.test.tsx +++ b/frontend/src/components/session/FormPrompt.test.tsx @@ -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( + <> + + + + ) + + await userEvent.keyboard('{Escape}') + + expect(onMinimize).toHaveBeenCalledTimes(1) + expect(sessionAbort).not.toHaveBeenCalled() + }) + }) }) diff --git a/frontend/src/components/session/FormPrompt.tsx b/frontend/src/components/session/FormPrompt.tsx index b6648068..cde00e1f 100644 --- a/frontend/src/components/session/FormPrompt.tsx +++ b/frontend/src/components/session/FormPrompt.tsx @@ -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 @@ -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?.() diff --git a/frontend/src/components/settings/KeyboardShortcuts.test.tsx b/frontend/src/components/settings/KeyboardShortcuts.test.tsx index 20190e91..da4e65aa 100644 --- a/frontend/src/components/settings/KeyboardShortcuts.test.tsx +++ b/frontend/src/components/settings/KeyboardShortcuts.test.tsx @@ -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} → `) diff --git a/frontend/src/components/settings/KeyboardShortcuts.tsx b/frontend/src/components/settings/KeyboardShortcuts.tsx index 6c43f0f9..57cd4487 100644 --- a/frontend/src/components/settings/KeyboardShortcuts.tsx +++ b/frontend/src/components/settings/KeyboardShortcuts.tsx @@ -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(null) const [currentKeys, setCurrentKeys] = useState('') - 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>(() => ({ - ...DEFAULT_KEYBOARD_SHORTCUTS, - ...preferences?.keyboardShortcuts, + ...bindings.shortcuts, ...tempShortcuts - }), [preferences?.keyboardShortcuts, tempShortcuts]) + }), [bindings.shortcuts, tempShortcuts]) const shortcutGroups = useMemo(() => buildShortcutGroups(shortcuts), [shortcuts]) diff --git a/frontend/src/components/ui/bottom-sheet.test.tsx b/frontend/src/components/ui/bottom-sheet.test.tsx index 52dca097..77e94f03 100644 --- a/frontend/src/components/ui/bottom-sheet.test.tsx +++ b/frontend/src/components/ui/bottom-sheet.test.tsx @@ -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 ( + <> + + setOpen(false)} ariaLabel="Auto focus sheet"> + + + + ) +} + 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() + 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( + , + ) + const opener = screen.getByRole('button', { name: 'opener' }) + opener.focus() + + rerender( + <> + + {}} ariaLabel="Mounted open sheet"> + + + , + ) + + rerender( + <> + + {}} ariaLabel="Mounted open sheet"> + + + , + ) + + expect(opener).toHaveFocus() + }) }) describe('BottomSheetHeader', () => { diff --git a/frontend/src/components/ui/bottom-sheet.tsx b/frontend/src/components/ui/bottom-sheet.tsx index 67a9f178..14b7fa6f 100644 --- a/frontend/src/components/ui/bottom-sheet.tsx +++ b/frontend/src/components/ui/bottom-sheet.tsx @@ -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(null) - const returnFocusRef = useRef(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) { diff --git a/frontend/src/components/ui/side-drawer.test.tsx b/frontend/src/components/ui/side-drawer.test.tsx index 358df0eb..4b667af3 100644 --- a/frontend/src/components/ui/side-drawer.test.tsx +++ b/frontend/src/components/ui/side-drawer.test.tsx @@ -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 ( + <> + + setOpen(false)} ariaLabel="Auto focus drawer"> + + + + ) +} + 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() + 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', () => { diff --git a/frontend/src/components/ui/side-drawer.tsx b/frontend/src/components/ui/side-drawer.tsx index 081578eb..3e88f88c 100644 --- a/frontend/src/components/ui/side-drawer.tsx +++ b/frontend/src/components/ui/side-drawer.tsx @@ -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(null) - const returnFocusRef = useRef(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 diff --git a/frontend/src/contexts/KeyboardShortcutsContext.test.tsx b/frontend/src/contexts/KeyboardShortcutsContext.test.tsx index cd66a203..b772ebc5 100644 --- a/frontend/src/contexts/KeyboardShortcutsContext.test.tsx +++ b/frontend/src/contexts/KeyboardShortcutsContext.test.tsx @@ -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, directShortcuts: ['submit', 'abort'], }, @@ -66,21 +66,21 @@ describe('KeyboardShortcutsProvider', () => { renderProvider() 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() + it('applies new default direct actions for users with stored preferences that predate them', () => { + const variantCycle = vi.fn() + renderProvider() 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() + 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() + 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() + 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() + 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() @@ -296,7 +347,7 @@ describe('KeyboardShortcutsProvider', () => { const newSession = vi.fn() renderProvider() - 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' }) diff --git a/frontend/src/contexts/KeyboardShortcutsContext.tsx b/frontend/src/contexts/KeyboardShortcutsContext.tsx index 4deec6ac..8a7a48a9 100644 --- a/frontend/src/contexts/KeyboardShortcutsContext.tsx +++ b/frontend/src/contexts/KeyboardShortcutsContext.tsx @@ -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(null) -function isTextInput(target: HTMLElement): boolean { - return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable -} - const PROMPT_ONLY_DIRECT_ACTIONS: ReadonlySet = new Set(['toggleMode', 'clearPrompt']) -function isPromptInput(target: HTMLElement): boolean { - return target.hasAttribute('data-prompt-input') -} +const HALF_PAGE_DIRECT_ACTIONS: ReadonlySet = 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) } diff --git a/frontend/src/hooks/useAutoScroll.test.tsx b/frontend/src/hooks/useAutoScroll.test.tsx index 914b4622..b3d3370b 100644 --- a/frontend/src/hooks/useAutoScroll.test.tsx +++ b/frontend/src/hooks/useAutoScroll.test.tsx @@ -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) diff --git a/frontend/src/hooks/useAutoScroll.ts b/frontend/src/hooks/useAutoScroll.ts index 11df6fb1..e801256e 100644 --- a/frontend/src/hooks/useAutoScroll.ts +++ b/frontend/src/hooks/useAutoScroll.ts @@ -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 } } diff --git a/frontend/src/hooks/useDialogParam.ts b/frontend/src/hooks/useDialogParam.ts index de40cce0..63b3aaf2 100644 --- a/frontend/src/hooks/useDialogParam.ts +++ b/frontend/src/hooks/useDialogParam.ts @@ -20,14 +20,25 @@ export function dialogSearch(name: string, extraParams?: Record) 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, +): void { + setDialogParams(params, name, extraParams) + params.delete('mobileTab') +} + export function openDialogParam( updateParams: ReturnType['updateParams'], name: string, extraParams?: Record, ): void { updateParams((p) => { - setDialogParams(p, name, extraParams) - p.delete('mobileTab') + openDialogParams(p, name, extraParams) }, 'push') } diff --git a/frontend/src/hooks/useGlobalShortcutActions.test.tsx b/frontend/src/hooks/useGlobalShortcutActions.test.tsx index 12574939..b166cfc1 100644 --- a/frontend/src/hooks/useGlobalShortcutActions.test.tsx +++ b/frontend/src/hooks/useGlobalShortcutActions.test.tsx @@ -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')) }) diff --git a/frontend/src/hooks/useGlobalShortcutActions.ts b/frontend/src/hooks/useGlobalShortcutActions.ts index abac29bc..56befd1f 100644 --- a/frontend/src/hooks/useGlobalShortcutActions.ts +++ b/frontend/src/hooks/useGlobalShortcutActions.ts @@ -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({}) diff --git a/frontend/src/hooks/useRestoreFocusOnClose.ts b/frontend/src/hooks/useRestoreFocusOnClose.ts new file mode 100644 index 00000000..34e6b320 --- /dev/null +++ b/frontend/src/hooks/useRestoreFocusOnClose.ts @@ -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, +): void { + const returnFocusRef = useRef(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]) +} diff --git a/frontend/src/hooks/useToolPanel.ts b/frontend/src/hooks/useToolPanel.ts index 413892be..d51987b0 100644 --- a/frontend/src/hooks/useToolPanel.ts +++ b/frontend/src/hooks/useToolPanel.ts @@ -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) } diff --git a/frontend/src/lib/domTargets.ts b/frontend/src/lib/domTargets.ts new file mode 100644 index 00000000..23e1f6e1 --- /dev/null +++ b/frontend/src/lib/domTargets.ts @@ -0,0 +1,25 @@ +const CONTENT_EDITABLE_VALUES = new Set(['', 'true', 'plaintext-only']) + +/** + * Returns true for free-text entry targets: ``, `