diff --git a/config/react-compiler-bailout-baseline.txt b/config/react-compiler-bailout-baseline.txt index 06b3aed8c79..b2c752cee6c 100644 --- a/config/react-compiler-bailout-baseline.txt +++ b/config/react-compiler-bailout-baseline.txt @@ -703,6 +703,7 @@ 6 src/renderer/src/hooks/useVirtualizedScrollAnchor.ts 1 src/renderer/src/lib/agent-session/launch/inventory/host-chat-program-acquisition.ts 1 src/renderer/src/lib/files/search/quick-open-file-history.ts +1 src/renderer/src/lib/list-interaction/use-windowed-command-virtualizer.ts 2 src/renderer/src/runtime/agent-orchestration/worker-auto-close.ts 1 src/renderer/src/runtime/native-chat/naming/structured-chat-name-observation.ts 1 src/renderer/src/store/plugins/appearance/plugin-icon-themes.ts diff --git a/config/react-compiler-uncompiled-files.txt b/config/react-compiler-uncompiled-files.txt index c1570bdeeab..fcb82cc9f86 100644 --- a/config/react-compiler-uncompiled-files.txt +++ b/config/react-compiler-uncompiled-files.txt @@ -33,6 +33,8 @@ src/renderer/src/components/native-chat/tools/runs/use-native-chat-tool-run-wind src/renderer/src/components/right-sidebar/file-explorer/panel/FileExplorerVirtualRows.tsx src/renderer/src/components/right-sidebar/file-explorer/tree/FileExplorerFilesTreePane.tsx src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx +src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx +src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx # The workbench subtree relies on the shell re-rendering on every app render. src/renderer/src/app-shell/AppWorkspaceShell.tsx diff --git a/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx b/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx index a6126592095..10a7a1dfe98 100644 --- a/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx +++ b/src/renderer/src/components/automations/authoring/WorkspaceCombobox.tsx @@ -1,18 +1,164 @@ import React from 'react' +import { defaultFilter } from 'cmdk' import { Check, ChevronsUpDown } from 'lucide-react' import { Button } from '@/components/ui/button' -import { - Command, - CommandEmpty, - CommandInput, - CommandItem, - CommandList -} from '@/components/ui/command' +import { Command, CommandInput, CommandList, CommandOption } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { cn } from '@/lib/class-names' +import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' +import { + getWindowedCommandNavigation, + useCommandInputActiveDescendant +} from '@/lib/list-interaction/windowed-command-navigation' +import { useWindowedCommandVirtualizer } from '@/lib/list-interaction/use-windowed-command-virtualizer' import type { Worktree } from '../../../../../shared/worktree/types' import { useTranslate } from '@/i18n/use-translate' +// Why: `py-1.5` around a 20px text line; fixed so rows never need measuring. +const WORKSPACE_OPTION_HEIGHT = 32 +const WORKSPACE_OPTION_OVERSCAN = 8 +// Why: matches `max-h-72`; seeds the first paint before the popover measures. +const WORKSPACE_LIST_MAX_HEIGHT = 288 + +function estimateWorkspaceOptionSize(): number { + return WORKSPACE_OPTION_HEIGHT +} + +/** cmdk's own ranking, run over every worktree so windowing never drops a match. */ +function filterWorkspaces(worktrees: readonly Worktree[], query: string): readonly Worktree[] { + if (!query) { + return worktrees + } + return worktrees + .map((worktree) => ({ worktree, score: defaultFilter(worktree.displayName.trim(), query, []) })) + .filter((scored) => scored.score > 0) + .sort((a, b) => b.score - a.score) + .map((scored) => scored.worktree) +} + +function WorkspaceComboboxList({ + worktrees, + value, + setInputNode, + onSelect +}: { + worktrees: Worktree[] + value: string + setInputNode: (node: HTMLInputElement | null) => void + onSelect: (workspaceId: string) => void +}): React.JSX.Element { + const t = useTranslate() + const listRef = React.useRef(null) + const inputRef = React.useRef(null) + const optionIdPrefix = `${React.useId()}option` + const [query, setQuery] = React.useState('') + const [highlightedId, setHighlightedId] = React.useState(null) + + const filtered = React.useMemo(() => filterWorkspaces(worktrees, query), [worktrees, query]) + const itemIds = React.useMemo(() => filtered.map((worktree) => worktree.id), [filtered]) + const indexById = React.useMemo(() => new Map(itemIds.map((id, index) => [id, index])), [itemIds]) + // A highlight that left the results falls back to the first match, as cmdk does. + const activeId = + highlightedId !== null && indexById.has(highlightedId) ? highlightedId : (itemIds[0] ?? null) + const activeIndex = activeId === null ? -1 : (indexById.get(activeId) ?? -1) + + const virtualizer = useWindowedCommandVirtualizer({ + itemKeys: itemIds, + scrollElement: () => listRef.current, + estimateSize: estimateWorkspaceOptionSize, + activeIndex, + overscan: WORKSPACE_OPTION_OVERSCAN, + initialRect: { width: 0, height: WORKSPACE_LIST_MAX_HEIGHT } + }) + + const setInputRef = React.useCallback( + (node: HTMLInputElement | null) => { + inputRef.current = node + setInputNode(node) + }, + [setInputNode] + ) + useCommandInputActiveDescendant( + inputRef, + activeIndex >= 0 ? `${optionIdPrefix}-${activeIndex}` : null + ) + + const handleQueryChange = (nextQuery: string): void => { + setQuery(nextQuery) + setHighlightedId(null) + virtualizer.scrollToOffset(0) + } + + const handleKeyDown = (event: React.KeyboardEvent): void => { + const navigation = getWindowedCommandNavigation(event, itemIds, activeId) + if (navigation) { + event.preventDefault() + if (navigation.targetId !== null) { + setHighlightedId(navigation.targetId) + virtualizer.scrollToIndex(indexById.get(navigation.targetId) ?? 0, { align: 'auto' }) + } + return + } + if (event.key === 'Enter' && !isImeOwnedKeyboardEvent(event) && activeId !== null) { + event.preventDefault() + onSelect(activeId) + } + } + + return ( + + + + {filtered.length === 0 ? ( +
+ {t('auto.components.automations.WorkspaceCombobox.ee5b280eba', 'No workspaces found.')} +
+ ) : ( +
+ {virtualizer.getVirtualItems().map((virtualRow) => { + const worktree = filtered[virtualRow.index] + if (!worktree) { + return null + } + return ( + setHighlightedId(worktree.id)} + onSelect={() => onSelect(worktree.id)} + className="absolute left-0 top-0 w-full" + style={{ + height: virtualRow.size, + transform: `translateY(${virtualRow.start}px)` + }} + > + + {worktree.displayName} + + ) + })} +
+ )} +
+
+ ) +} + export function WorkspaceCombobox({ worktrees, value, @@ -65,6 +211,14 @@ export function WorkspaceCombobox({ [cancelFocusFrame] ) + const handleSelect = React.useCallback( + (workspaceId: string) => { + onValueChange(workspaceId) + setOpen(false) + }, + [onValueChange] + ) + return ( @@ -90,38 +244,12 @@ export function WorkspaceCombobox({ focusSearchInput() }} > - - - - - {t( - 'auto.components.automations.WorkspaceCombobox.ee5b280eba', - 'No workspaces found.' - )} - - {worktrees.map((worktree) => ( - { - onValueChange(worktree.id) - setOpen(false) - }} - > - - {worktree.displayName} - - ))} - - + ) diff --git a/src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx b/src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx index 43dc6c919ec..516c93c1e4e 100644 --- a/src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx +++ b/src/renderer/src/components/skills/installation/SkillInstallWorkspaceCombobox.tsx @@ -1,20 +1,26 @@ -import React, { useCallback, useMemo, useRef, useState } from 'react' +import React, { useCallback, useId, useLayoutEffect, useMemo, useRef, useState } from 'react' import { Check, ChevronsUpDown } from 'lucide-react' import { Button } from '@/components/ui/button' -import { - Command, - CommandEmpty, - CommandInput, - CommandItem, - CommandList -} from '@/components/ui/command' +import { Command, CommandInput, CommandList, CommandOption } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { TooltipProvider } from '@/components/ui/tooltip' import { FilePathCursorTooltip } from '@/components/file-path-cursor-tooltip' import { cn } from '@/lib/class-names' import { useTranslate } from '@/i18n/use-translate' +import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' +import { + getWindowedCommandNavigation, + useCommandInputActiveDescendant +} from '@/lib/list-interaction/windowed-command-navigation' +import { useWindowedCommandVirtualizer } from '@/lib/list-interaction/use-windowed-command-virtualizer' import type { SkillInstallWorkspaceChoice } from './skill-install-workspace-choices' +// Why: `py-2` around a 20px text line; fixed so rows never need measuring. +const CHOICE_OPTION_HEIGHT = 36 +const CHOICE_OPTION_OVERSCAN = 8 +// Why: matches `max-h-72`; seeds the first paint before the popover measures. +const CHOICE_LIST_MAX_HEIGHT = 288 + export type SkillInstallWorkspaceComboboxProps = { id?: string value: string @@ -25,6 +31,18 @@ export type SkillInstallWorkspaceComboboxProps = { triggerClassName?: string } +/** Opening on the current choice highlights it (nothing when it is gone, the first choice when none is set); typing highlights the first match. */ +type ChoiceHighlight = { kind: 'choice'; key: string } | { kind: 'none' } | { kind: 'first-match' } + +function estimateChoiceOptionSize(): number { + return CHOICE_OPTION_HEIGHT +} + +// Worktree and folder ids are separate namespaces; the kind keeps option keys injective. +function choiceKey(choice: SkillInstallWorkspaceChoice): string { + return `${choice.kind}:${choice.id}` +} + function searchChoices( choices: readonly SkillInstallWorkspaceChoice[], query: string @@ -41,6 +59,180 @@ function searchChoices( }) } +function SkillInstallWorkspaceChoiceList({ + choices, + value, + query, + highlight, + setInputNode, + onQueryChange, + onHighlightChange, + onSelect +}: { + choices: readonly SkillInstallWorkspaceChoice[] + value: string + query: string + highlight: ChoiceHighlight + setInputNode: (node: HTMLInputElement | null) => void + onQueryChange: (query: string) => void + onHighlightChange: (highlight: ChoiceHighlight) => void + onSelect: (choiceId: string) => void +}): React.JSX.Element { + const t = useTranslate() + const inputRef = useRef(null) + const listRef = useRef(null) + const optionIdPrefix = `${useId()}option` + + const filteredChoices = useMemo(() => searchChoices(choices, query), [choices, query]) + const choiceKeys = useMemo(() => filteredChoices.map(choiceKey), [filteredChoices]) + const indexByKey = useMemo( + () => new Map(choiceKeys.map((key, index) => [key, index])), + [choiceKeys] + ) + // A highlighted choice that left the results falls back to the first match, as cmdk does. + const activeKey = + highlight.kind === 'none' + ? null + : highlight.kind === 'choice' && indexByKey.has(highlight.key) + ? highlight.key + : (choiceKeys[0] ?? null) + const activeIndex = activeKey === null ? -1 : (indexByKey.get(activeKey) ?? -1) + + const virtualizer = useWindowedCommandVirtualizer({ + itemKeys: choiceKeys, + scrollElement: () => listRef.current, + estimateSize: estimateChoiceOptionSize, + activeIndex, + overscan: CHOICE_OPTION_OVERSCAN, + initialRect: { width: 0, height: CHOICE_LIST_MAX_HEIGHT } + }) + + // Content mounts per open; reveal the choice it opened on once. + const [openedOnIndex] = useState(activeIndex) + useLayoutEffect(() => { + if (openedOnIndex > 0) { + virtualizer.scrollToIndex(openedOnIndex, { align: 'auto' }) + } + }, [openedOnIndex, virtualizer]) + + const setInputRef = useCallback( + (node: HTMLInputElement | null) => { + inputRef.current = node + setInputNode(node) + }, + [setInputNode] + ) + useCommandInputActiveDescendant( + inputRef, + activeIndex >= 0 ? `${optionIdPrefix}-${activeIndex}` : null + ) + + const handleQueryChange = (nextQuery: string): void => { + onQueryChange(nextQuery) + virtualizer.scrollToOffset(0) + } + + const handleKeyDown = (event: React.KeyboardEvent): void => { + const navigation = getWindowedCommandNavigation(event, choiceKeys, activeKey) + if (navigation) { + event.preventDefault() + if (navigation.targetId !== null) { + onHighlightChange({ kind: 'choice', key: navigation.targetId }) + virtualizer.scrollToIndex(indexByKey.get(navigation.targetId) ?? 0, { align: 'auto' }) + } + return + } + const activeChoice = activeIndex >= 0 ? filteredChoices[activeIndex] : undefined + if (event.key === 'Enter' && !isImeOwnedKeyboardEvent(event) && activeChoice) { + event.preventDefault() + onSelect(activeChoice.id) + } + } + + return ( + + + + + {filteredChoices.length === 0 ? ( +
+ {t( + 'auto.components.skills.SkillInstallWorkspaceCombobox.empty', + 'No workspaces found.' + )} +
+ ) : ( +
+ {virtualizer.getVirtualItems().map((virtualRow) => { + const choice = filteredChoices[virtualRow.index] + if (!choice) { + return null + } + const key = choiceKey(choice) + const isSelected = choice.id === value + const kindLabel = + choice.kind === 'worktree' + ? t( + 'auto.components.skills.SkillInstallTargetFields.d628c416a2', + 'Git worktree' + ) + : t('auto.components.skills.SkillInstallTargetFields.7a366323e7', 'Folder') + const fullLabel = `${choice.label} · ${kindLabel}` + + return ( + onHighlightChange({ kind: 'choice', key })} + onSelect={() => onSelect(choice.id)} + density="flush" + className="absolute left-0 top-0 w-full min-w-0 cursor-pointer" + style={{ + height: virtualRow.size, + transform: `translateY(${virtualRow.start}px)` + }} + > + +
+ + + {choice.label} ·{' '} + {kindLabel} + +
+
+
+ ) + })} +
+ )} +
+
+
+ ) +} + export function SkillInstallWorkspaceCombobox({ id, value, @@ -53,7 +245,7 @@ export function SkillInstallWorkspaceCombobox({ const t = useTranslate() const [open, setOpen] = useState(false) const [query, setQuery] = useState('') - const [commandValue, setCommandValue] = useState(value) + const [highlight, setHighlight] = useState({ kind: 'none' }) const inputRef = useRef(null) const focusFrameRef = useRef(null) @@ -62,8 +254,6 @@ export function SkillInstallWorkspaceCombobox({ [choices, value] ) - const filteredChoices = useMemo(() => searchChoices(choices, query), [choices, query]) - const cancelFocusFrame = useCallback((): void => { if (focusFrameRef.current !== null) { cancelAnimationFrame(focusFrameRef.current) @@ -95,19 +285,35 @@ export function SkillInstallWorkspaceCombobox({ }) }, [cancelFocusFrame]) + // With no choice yet the first one is armed, as cmdk did; a stale choice highlights nothing. + const highlightCurrentChoice = useCallback(() => { + setHighlight( + selectedChoice + ? { kind: 'choice', key: choiceKey(selectedChoice) } + : value === '' + ? { kind: 'first-match' } + : { kind: 'none' } + ) + }, [selectedChoice, value]) + const handleOpenChange = useCallback( (nextOpen: boolean) => { setOpen(nextOpen) if (nextOpen) { - setCommandValue(value) + highlightCurrentChoice() return } cancelFocusFrame() setQuery('') }, - [cancelFocusFrame, value] + [cancelFocusFrame, highlightCurrentChoice] ) + const handleQueryChange = useCallback((nextQuery: string) => { + setQuery(nextQuery) + setHighlight({ kind: 'first-match' }) + }, []) + const handleSelect = useCallback( (choiceId: string) => { onValueChange(choiceId) @@ -124,7 +330,7 @@ export function SkillInstallWorkspaceCombobox({ } if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault() - setCommandValue(value) + highlightCurrentChoice() setOpen(true) return } @@ -133,12 +339,12 @@ export function SkillInstallWorkspaceCombobox({ } if (event.key.length === 1 && /\S/.test(event.key)) { event.preventDefault() - setCommandValue(value) + setHighlight({ kind: 'first-match' }) setQuery(event.key) setOpen(true) } }, - [open, value] + [highlightCurrentChoice, open] ) const defaultPlaceholder = t( @@ -192,65 +398,16 @@ export function SkillInstallWorkspaceCombobox({ focusSearchInput() }} > - - - - - - {t( - 'auto.components.skills.SkillInstallWorkspaceCombobox.empty', - 'No workspaces found.' - )} - - {filteredChoices.map((choice) => { - const isSelected = choice.id === value - const kindLabel = - choice.kind === 'worktree' - ? t( - 'auto.components.skills.SkillInstallTargetFields.d628c416a2', - 'Git worktree' - ) - : t('auto.components.skills.SkillInstallTargetFields.7a366323e7', 'Folder') - const fullLabel = `${choice.label} · ${kindLabel}` - - return ( - handleSelect(choice.id)} - className="min-w-0 !p-0 cursor-pointer" - > - -
- - - {choice.label} ·{' '} - {kindLabel} - -
-
-
- ) - })} -
-
-
+ ) diff --git a/src/renderer/src/components/ui/command.tsx b/src/renderer/src/components/ui/command.tsx index 56381a08f30..705ef7026da 100644 --- a/src/renderer/src/components/ui/command.tsx +++ b/src/renderer/src/components/ui/command.tsx @@ -268,10 +268,13 @@ function CommandGroup({ ) } +const COMMAND_ITEM_BASE_CLASS = + 'relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4' + const commandItemVariants = cva('', { variants: { selection: { default: '', palette: 'jump-palette-item' }, - density: { default: '', workspace: 'px-3 py-2 text-xs' }, + density: { default: '', workspace: 'px-3 py-2 text-xs', flush: 'p-0' }, // Cmd+J's workspace row box: titles share one column across row kinds. shape: { default: '', @@ -297,7 +300,53 @@ function CommandItem({ ref={ref} data-slot="command-item" className={cn( - 'relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*="size-"])]:size-4', + COMMAND_ITEM_BASE_CLASS, + commandItemVariants({ selection, density, emphasis, shape }), + className + )} + {...props} + /> + ) +} + +type CommandOptionProps = Omit, 'onSelect'> & + VariantProps & { + selected: boolean + /** Rendered as `data-value`, the identity automation reads from command rows. */ + value?: string + disabled?: boolean + onHighlight?: () => void + onSelect?: () => void + } + +/** A listbox option cmdk never sees, for windowed lists that own selection; omitting `cmdk-item` keeps cmdk's DOM queries off it. */ +function CommandOption({ + className, + selection, + density, + emphasis, + shape, + selected, + value, + disabled = false, + onHighlight, + onSelect, + ...props +}: CommandOptionProps): React.JSX.Element { + return ( +
HTMLDivElement | null + estimateSize: (index: number) => number + activeIndex: number + overscan: number + initialRect: Rect +}): Virtualizer { + const keys = useRetainedKeySequence(itemKeys) + const count = keys.length + const getItemKey = useCallback((index: number) => keys[index] ?? index, [keys]) + const rangeExtractor = useCallback( + (range: Range) => { + const indexes = defaultRangeExtractor(range) + if (activeIndex >= 0 && activeIndex < count && !indexes.includes(activeIndex)) { + indexes.push(activeIndex) + indexes.sort((a, b) => a - b) + } + return indexes + }, + [activeIndex, count] + ) + return useVirtualizer({ + count, + getScrollElement: scrollElement, + estimateSize, + getItemKey, + overscan, + rangeExtractor, + initialRect, + scrollPaddingStart: COMMAND_LIST_SCROLL_PADDING, + scrollPaddingEnd: COMMAND_LIST_SCROLL_PADDING + }) +} diff --git a/src/renderer/src/lib/list-interaction/windowed-command-navigation.test.ts b/src/renderer/src/lib/list-interaction/windowed-command-navigation.test.ts new file mode 100644 index 00000000000..9bc04378d3f --- /dev/null +++ b/src/renderer/src/lib/list-interaction/windowed-command-navigation.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import { getWindowedCommandNavigation } from './windowed-command-navigation' + +const ids = ['a', 'b', 'c', 'd'] + +function key( + keyName: string, + modifiers: Partial<{ ctrlKey: boolean; metaKey: boolean; isComposing: boolean }> = {} +) { + return { + key: keyName, + ctrlKey: modifiers.ctrlKey ?? false, + metaKey: modifiers.metaKey ?? false, + defaultPrevented: false, + nativeEvent: { isComposing: modifiers.isComposing ?? false } + } +} + +describe('getWindowedCommandNavigation', () => { + it('steps through the full list and stops at the ends', () => { + expect(getWindowedCommandNavigation(key('ArrowDown'), ids, 'b')).toEqual({ targetId: 'c' }) + expect(getWindowedCommandNavigation(key('ArrowUp'), ids, 'b')).toEqual({ targetId: 'a' }) + expect(getWindowedCommandNavigation(key('ArrowDown'), ids, 'd')).toEqual({ targetId: null }) + }) + + it('matches cmdk when nothing is highlighted: down goes first, up goes nowhere', () => { + expect(getWindowedCommandNavigation(key('ArrowDown'), ids, null)).toEqual({ targetId: 'a' }) + expect(getWindowedCommandNavigation(key('ArrowUp'), ids, null)).toEqual({ targetId: null }) + }) + + it('jumps to the ends with Home/End and Meta+Arrow', () => { + expect(getWindowedCommandNavigation(key('End'), ids, 'a')).toEqual({ targetId: 'd' }) + expect(getWindowedCommandNavigation(key('Home'), ids, 'c')).toEqual({ targetId: 'a' }) + expect(getWindowedCommandNavigation(key('ArrowDown', { metaKey: true }), ids, 'a')).toEqual({ + targetId: 'd' + }) + expect(getWindowedCommandNavigation(key('ArrowUp', { metaKey: true }), ids, 'c')).toEqual({ + targetId: 'a' + }) + }) + + it('treats Ctrl+N/J and Ctrl+P/K as movement, plain letters as typing', () => { + expect(getWindowedCommandNavigation(key('n', { ctrlKey: true }), ids, 'a')).toEqual({ + targetId: 'b' + }) + expect(getWindowedCommandNavigation(key('j', { ctrlKey: true }), ids, 'a')).toEqual({ + targetId: 'b' + }) + expect(getWindowedCommandNavigation(key('p', { ctrlKey: true }), ids, 'c')).toEqual({ + targetId: 'b' + }) + expect(getWindowedCommandNavigation(key('k', { ctrlKey: true }), ids, 'c')).toEqual({ + targetId: 'b' + }) + expect(getWindowedCommandNavigation(key('n'), ids, 'a')).toBeNull() + }) + + it('leaves composition, handled and non-movement keys alone', () => { + expect( + getWindowedCommandNavigation(key('ArrowDown', { isComposing: true }), ids, 'a') + ).toBeNull() + expect( + getWindowedCommandNavigation({ ...key('ArrowDown'), defaultPrevented: true }, ids, 'a') + ).toBeNull() + expect(getWindowedCommandNavigation(key('Enter'), ids, 'a')).toBeNull() + }) + + it('claims movement keys on an empty list without a target', () => { + expect(getWindowedCommandNavigation(key('End'), [], null)).toEqual({ targetId: null }) + expect(getWindowedCommandNavigation(key('ArrowDown'), [], null)).toEqual({ targetId: null }) + }) +}) diff --git a/src/renderer/src/lib/list-interaction/windowed-command-navigation.ts b/src/renderer/src/lib/list-interaction/windowed-command-navigation.ts new file mode 100644 index 00000000000..595171089a1 --- /dev/null +++ b/src/renderer/src/lib/list-interaction/windowed-command-navigation.ts @@ -0,0 +1,82 @@ +import { useEffect, type RefObject } from 'react' +import { isImeOwnedKeyboardEvent } from '@/lib/text-input/ime/ime-composition-keyboard-event' + +type CommandNavigationKeyEvent = { + key: string + ctrlKey: boolean + metaKey: boolean + defaultPrevented: boolean + keyCode?: number + nativeEvent?: { isComposing?: boolean; keyCode?: number } +} + +/** Resolves cmdk's movement keys over the full logical list, because cmdk only sees a windowed list's mounted rows. + * Returns null for keys cmdk would not treat as movement; `targetId` null means movement with nowhere to go. */ +export function getWindowedCommandNavigation( + event: CommandNavigationKeyEvent, + itemIds: readonly string[], + activeItemId: string | null | undefined +): { targetId: string | null } | null { + if (event.defaultPrevented || isImeOwnedKeyboardEvent(event)) { + return null + } + const last = itemIds.length - 1 + const move = (delta: 1 | -1): number | null => { + if (event.metaKey) { + return delta === 1 ? last : 0 + } + const currentIndex = activeItemId ? itemIds.indexOf(activeItemId) : -1 + const next = currentIndex + delta + return next < 0 || next > last ? null : next + } + let targetIndex: number | null + switch (event.key) { + case 'ArrowDown': + targetIndex = move(1) + break + case 'ArrowUp': + targetIndex = move(-1) + break + case 'n': + case 'j': + if (!event.ctrlKey) { + return null + } + targetIndex = move(1) + break + case 'p': + case 'k': + if (!event.ctrlKey) { + return null + } + targetIndex = move(-1) + break + case 'Home': + targetIndex = 0 + break + case 'End': + targetIndex = last + break + default: + return null + } + return { targetId: targetIndex === null ? null : (itemIds[targetIndex] ?? null) } +} + +/** cmdk derives `aria-activedescendant` from its own item registry; point it at the surface-owned active option after each commit. */ +export function useCommandInputActiveDescendant( + inputRef: RefObject, + activeOptionId: string | null +): void { + useEffect(() => { + const input = inputRef.current + if (!input) { + return + } + if (activeOptionId) { + input.setAttribute('aria-activedescendant', activeOptionId) + } else { + input.removeAttribute('aria-activedescendant') + } + }) +}