perf(pickers): window the Automations and Skill install workspace pickers (#41396)

* perf(pickers): window workspace comboboxes and the Cmd+J result list

The Automations and Skill install workspace comboboxes mounted one cmdk row
per workspace while open, and the Cmd+J result list mounted every capped
section row plus each See more page. cmdk moves the highlight, runs Enter and
publishes aria-activedescendant by querying mounted rows, so these lists could
not be windowed while cmdk owned selection.

Each surface now owns its highlight over the full ordered result list:
movement keys follow cmdk's bindings over every result, Enter and click share
one activation path, and the input's aria-activedescendant names the
highlighted option, which stays mounted. Rows render as plain listbox options
outside cmdk's registry and only the visible window mounts (TanStack
virtualizer; Cmd+J keeps natural layout below 50 rows). Filtering, ranking,
section caps and See more are unchanged.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(pickers): share the windowed command virtualizer and keep the compiler gate

Move the active-option pin and command-list reveal padding into one hook used
by all three surfaces, keep virtualizer consumers out of React Compiler like
the other TanStack lists, and express the dialog row styles and the flush skill
rows as command variants.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(pickers): record the windowed command virtualizer hook's compiler bailout

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(pickers): keep virtualizer geometry across scrolls and match prior highlight/IME behavior

- Stable per-list key/size getters so scrolling and hovering no longer rebuild
  every row's virtual geometry.
- Moving the pointer over the already-highlighted option does no work.
- Jump to… numbers every rendered option, disabled ones included.
- The task Cmd/Ctrl+Enter shortcut ignores IME composition keys.
- The skill install workspace picker opened with nothing chosen highlights the
  first workspace again.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(pickers): let the shared virtualizer own row key identity

Callers now pass their ordered row keys; the shared hook keeps one key array
per ordered sequence and derives the key getter from it, so a list rebuilt
with the same rows (for example after an unrelated workspace metadata update)
no longer forces a full geometry rebuild, while real reorder, insert, remove
and filter changes still do.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(pickers): keep the row See more selects in view when Jump to… starts windowing

Crossing 50 rows through See more switches the list to windowed rendering;
reveal the newly highlighted row after that commit so it stays on screen as
it did before.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* perf(pickers): keep Jump to… on its original list; window only the two workspace pickers

The real-app benchmark showed no meaningful gain for the Jump to… results
(they rarely reach 50 rows), and windowing them changed the See more
behaviour at the threshold. Restore Jump to… exactly as on main and keep the
windowed list, model-owned selection and option primitive for the Automations
and Skill install workspace pickers, which measured clear wins.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Brennan Benson
2026-11-13 17:03:58 -08:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 6a0d446ccf
commit e5e4f6f4c9
8 changed files with 690 additions and 116 deletions
@@ -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
@@ -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
@@ -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<HTMLDivElement | null>(null)
const inputRef = React.useRef<HTMLInputElement | null>(null)
const optionIdPrefix = `${React.useId()}option`
const [query, setQuery] = React.useState('')
const [highlightedId, setHighlightedId] = React.useState<string | null>(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<HTMLInputElement>): 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 (
<Command shouldFilter={false}>
<CommandInput
ref={setInputRef}
value={query}
onValueChange={handleQueryChange}
onKeyDown={handleKeyDown}
placeholder={t(
'auto.components.automations.WorkspaceCombobox.8e9c8cc6b5',
'Search workspaces...'
)}
/>
<CommandList ref={listRef} className="max-h-72">
{filtered.length === 0 ? (
<div className="py-6 text-center text-sm text-muted-foreground">
{t('auto.components.automations.WorkspaceCombobox.ee5b280eba', 'No workspaces found.')}
</div>
) : (
<div className="relative w-full" style={{ height: virtualizer.getTotalSize() }}>
{virtualizer.getVirtualItems().map((virtualRow) => {
const worktree = filtered[virtualRow.index]
if (!worktree) {
return null
}
return (
<CommandOption
key={worktree.id}
value={worktree.id}
id={`${optionIdPrefix}-${virtualRow.index}`}
aria-posinset={virtualRow.index + 1}
aria-setsize={filtered.length}
selected={worktree.id === activeId}
onHighlight={() => setHighlightedId(worktree.id)}
onSelect={() => onSelect(worktree.id)}
className="absolute left-0 top-0 w-full"
style={{
height: virtualRow.size,
transform: `translateY(${virtualRow.start}px)`
}}
>
<Check
className={cn('size-4', value === worktree.id ? 'opacity-100' : 'opacity-0')}
/>
<span className="truncate">{worktree.displayName}</span>
</CommandOption>
)
})}
</div>
)}
</CommandList>
</Command>
)
}
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 (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
@@ -90,38 +244,12 @@ export function WorkspaceCombobox({
focusSearchInput()
}}
>
<Command>
<CommandInput
ref={setInputNode}
placeholder={t(
'auto.components.automations.WorkspaceCombobox.8e9c8cc6b5',
'Search workspaces...'
)}
/>
<CommandList className="max-h-72">
<CommandEmpty>
{t(
'auto.components.automations.WorkspaceCombobox.ee5b280eba',
'No workspaces found.'
)}
</CommandEmpty>
{worktrees.map((worktree) => (
<CommandItem
key={worktree.id}
value={worktree.displayName}
onSelect={() => {
onValueChange(worktree.id)
setOpen(false)
}}
>
<Check
className={cn('size-4', value === worktree.id ? 'opacity-100' : 'opacity-0')}
/>
<span className="truncate">{worktree.displayName}</span>
</CommandItem>
))}
</CommandList>
</Command>
<WorkspaceComboboxList
worktrees={worktrees}
value={value}
setInputNode={setInputNode}
onSelect={handleSelect}
/>
</PopoverContent>
</Popover>
)
@@ -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<HTMLInputElement | null>(null)
const listRef = useRef<HTMLDivElement | null>(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<HTMLInputElement>): 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 (
<Command shouldFilter={false}>
<CommandInput
ref={setInputRef}
placeholder={t(
'auto.components.skills.SkillInstallWorkspaceCombobox.search',
'Search workspaces...'
)}
value={query}
onValueChange={handleQueryChange}
onKeyDown={handleKeyDown}
/>
<TooltipProvider>
<CommandList ref={listRef} className="max-h-72">
{filteredChoices.length === 0 ? (
<div className="py-6 text-center text-sm text-muted-foreground">
{t(
'auto.components.skills.SkillInstallWorkspaceCombobox.empty',
'No workspaces found.'
)}
</div>
) : (
<div className="relative w-full" style={{ height: virtualizer.getTotalSize() }}>
{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 (
<CommandOption
key={key}
value={choice.id}
id={`${optionIdPrefix}-${virtualRow.index}`}
aria-posinset={virtualRow.index + 1}
aria-setsize={filteredChoices.length}
selected={key === activeKey}
onHighlight={() => 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)`
}}
>
<FilePathCursorTooltip path={fullLabel}>
<div
title={fullLabel}
className="flex w-full min-w-0 items-center gap-2 px-3 py-2"
>
<Check
className={cn(
'size-4 shrink-0 text-foreground',
isSelected ? 'opacity-100' : 'opacity-0'
)}
/>
<span className="truncate flex-1">
{choice.label} ·{' '}
<span className="text-muted-foreground">{kindLabel}</span>
</span>
</div>
</FilePathCursorTooltip>
</CommandOption>
)
})}
</div>
)}
</CommandList>
</TooltipProvider>
</Command>
)
}
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<ChoiceHighlight>({ kind: 'none' })
const inputRef = useRef<HTMLInputElement | null>(null)
const focusFrameRef = useRef<number | null>(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()
}}
>
<Command shouldFilter={false} value={commandValue} onValueChange={setCommandValue}>
<CommandInput
ref={setInputNode}
placeholder={t(
'auto.components.skills.SkillInstallWorkspaceCombobox.search',
'Search workspaces...'
)}
value={query}
onValueChange={setQuery}
/>
<TooltipProvider>
<CommandList className="max-h-72">
<CommandEmpty>
{t(
'auto.components.skills.SkillInstallWorkspaceCombobox.empty',
'No workspaces found.'
)}
</CommandEmpty>
{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 (
<CommandItem
key={`${choice.kind}:${choice.id}`}
value={choice.id}
onSelect={() => handleSelect(choice.id)}
className="min-w-0 !p-0 cursor-pointer"
>
<FilePathCursorTooltip path={fullLabel}>
<div
title={fullLabel}
className="flex w-full min-w-0 items-center gap-2 px-3 py-2"
>
<Check
className={cn(
'size-4 shrink-0 text-foreground',
isSelected ? 'opacity-100' : 'opacity-0'
)}
/>
<span className="truncate flex-1">
{choice.label} ·{' '}
<span className="text-muted-foreground">{kindLabel}</span>
</span>
</div>
</FilePathCursorTooltip>
</CommandItem>
)
})}
</CommandList>
</TooltipProvider>
</Command>
<SkillInstallWorkspaceChoiceList
choices={choices}
value={value}
query={query}
highlight={highlight}
setInputNode={setInputNode}
onQueryChange={handleQueryChange}
onHighlightChange={setHighlight}
onSelect={handleSelect}
/>
</PopoverContent>
</Popover>
)
+52 -2
View File
@@ -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<React.ComponentProps<'div'>, 'onSelect'> &
VariantProps<typeof commandItemVariants> & {
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 (
<div
data-slot="command-item"
data-value={value}
role="option"
aria-selected={selected}
data-selected={selected}
aria-disabled={disabled}
data-disabled={disabled}
// Like cmdk, moving over the already-highlighted option does no work.
onPointerMove={disabled || selected ? undefined : onHighlight}
onClick={disabled ? undefined : onSelect}
className={cn(
COMMAND_ITEM_BASE_CLASS,
commandItemVariants({ selection, density, emphasis, shape }),
className
)}
@@ -327,5 +376,6 @@ export {
CommandInput,
CommandItem,
CommandList,
CommandOption,
CommandSeparator
}
@@ -0,0 +1,82 @@
import { useCallback, useState } from 'react'
import {
defaultRangeExtractor,
useVirtualizer,
type Range,
type Rect,
type Virtualizer
} from '@tanstack/react-virtual'
// Why: matches CommandList's `scroll-pt-4 scroll-pb-4`, which cmdk's native reveal honoured.
const COMMAND_LIST_SCROLL_PADDING = 16
function isSameKeySequence(a: readonly string[], b: readonly string[]): boolean {
if (a === b) {
return true
}
if (a.length !== b.length) {
return false
}
for (let index = 0; index < a.length; index += 1) {
if (a[index] !== b[index]) {
return false
}
}
return true
}
/** Keeps one key array per ordered sequence: TanStack rebuilds every row's geometry whenever its key getter changes. */
function useRetainedKeySequence(itemKeys: readonly string[]): readonly string[] {
const [retained, setRetained] = useState({ input: itemKeys, keys: itemKeys })
if (retained.input === itemKeys) {
return retained.keys
}
// Compare each newly supplied array once; equal content keeps the previous identity.
const keys = isSameKeySequence(retained.keys, itemKeys) ? retained.keys : itemKeys
setRetained({ input: itemKeys, keys })
return keys
}
/** Windows a command list whose surface owns selection; the active option stays mounted so aria-activedescendant names a real element. */
export function useWindowedCommandVirtualizer({
itemKeys,
scrollElement,
estimateSize,
activeIndex,
overscan,
initialRect
}: {
/** One unique key per row, in order; the row count is its length. */
itemKeys: readonly string[]
scrollElement: () => HTMLDivElement | null
estimateSize: (index: number) => number
activeIndex: number
overscan: number
initialRect: Rect
}): Virtualizer<HTMLDivElement, Element> {
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
})
}
@@ -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 })
})
})
@@ -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<HTMLInputElement | null>,
activeOptionId: string | null
): void {
useEffect(() => {
const input = inputRef.current
if (!input) {
return
}
if (activeOptionId) {
input.setAttribute('aria-activedescendant', activeOptionId)
} else {
input.removeAttribute('aria-activedescendant')
}
})
}