feat: add AskUserDialog for UI component of AskUser tool (#17344)

Co-authored-by: jacob314 <jacob314@gmail.com>
This commit is contained in:
Jack Wotherspoon
2026-01-23 15:42:48 -05:00
committed by GitHub
parent 25c0802b52
commit 2c0cc7b9a5
10 changed files with 3009 additions and 1 deletions

View File

@@ -13,6 +13,7 @@ export interface SelectionListItem<T> {
key: string;
value: T;
disabled?: boolean;
hideNumber?: boolean;
}
interface BaseSelectionItem {
@@ -28,6 +29,7 @@ export interface UseSelectionListOptions<T> {
isFocused?: boolean;
showNumbers?: boolean;
wrapAround?: boolean;
focusKey?: string;
}
export interface UseSelectionListResult {
@@ -285,6 +287,7 @@ export function useSelectionList<T>({
isFocused = true,
showNumbers = false,
wrapAround = true,
focusKey,
}: UseSelectionListOptions<T>): UseSelectionListResult {
const baseItems = toBaseItems(items);
@@ -302,6 +305,25 @@ export function useSelectionList<T>({
const prevBaseItemsRef = useRef(baseItems);
const prevInitialIndexRef = useRef(initialIndex);
const prevWrapAroundRef = useRef(wrapAround);
const lastProcessedFocusKeyRef = useRef<string | undefined>(undefined);
// Handle programmatic focus changes via focusKey
useEffect(() => {
if (focusKey === undefined) {
lastProcessedFocusKeyRef.current = undefined;
return;
}
if (focusKey === lastProcessedFocusKeyRef.current) return;
const index = items.findIndex(
(item) => item.key === focusKey && !item.disabled,
);
if (index !== -1) {
lastProcessedFocusKeyRef.current = focusKey;
dispatch({ type: 'SET_ACTIVE_INDEX', payload: { index } });
}
}, [focusKey, items]);
// Initialize/synchronize state when initialIndex or items change
useEffect(() => {

View File

@@ -0,0 +1,276 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { act } from 'react';
import { renderHook } from '../../test-utils/render.js';
import { useTabbedNavigation } from './useTabbedNavigation.js';
vi.mock('./useKeypress.js', () => ({
useKeypress: vi.fn(),
}));
vi.mock('../keyMatchers.js', () => ({
keyMatchers: {
'cursor.left': vi.fn((key) => key.name === 'left'),
'cursor.right': vi.fn((key) => key.name === 'right'),
},
Command: {
MOVE_LEFT: 'cursor.left',
MOVE_RIGHT: 'cursor.right',
},
}));
describe('useTabbedNavigation', () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe('initialization', () => {
it('returns initial index of 0 by default', () => {
const { result } = renderHook(() => useTabbedNavigation({ tabCount: 3 }));
expect(result.current.currentIndex).toBe(0);
});
it('returns specified initial index', () => {
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 2 }),
);
expect(result.current.currentIndex).toBe(2);
});
it('clamps initial index to valid range', () => {
const { result: high } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 10 }),
);
expect(high.current.currentIndex).toBe(2);
const { result: negative } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: -1 }),
);
expect(negative.current.currentIndex).toBe(0);
});
});
describe('goToNextTab', () => {
it('advances to next tab', () => {
const { result } = renderHook(() => useTabbedNavigation({ tabCount: 3 }));
act(() => {
result.current.goToNextTab();
});
expect(result.current.currentIndex).toBe(1);
});
it('stops at last tab when wrapAround is false', () => {
const { result } = renderHook(() =>
useTabbedNavigation({
tabCount: 3,
initialIndex: 2,
wrapAround: false,
}),
);
act(() => {
result.current.goToNextTab();
});
expect(result.current.currentIndex).toBe(2);
});
it('wraps to first tab when wrapAround is true', () => {
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 2, wrapAround: true }),
);
act(() => {
result.current.goToNextTab();
});
expect(result.current.currentIndex).toBe(0);
});
});
describe('goToPrevTab', () => {
it('moves to previous tab', () => {
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 2 }),
);
act(() => {
result.current.goToPrevTab();
});
expect(result.current.currentIndex).toBe(1);
});
it('stops at first tab when wrapAround is false', () => {
const { result } = renderHook(() =>
useTabbedNavigation({
tabCount: 3,
initialIndex: 0,
wrapAround: false,
}),
);
act(() => {
result.current.goToPrevTab();
});
expect(result.current.currentIndex).toBe(0);
});
it('wraps to last tab when wrapAround is true', () => {
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 0, wrapAround: true }),
);
act(() => {
result.current.goToPrevTab();
});
expect(result.current.currentIndex).toBe(2);
});
});
describe('setCurrentIndex', () => {
it('sets index directly', () => {
const { result } = renderHook(() => useTabbedNavigation({ tabCount: 3 }));
act(() => {
result.current.setCurrentIndex(2);
});
expect(result.current.currentIndex).toBe(2);
});
it('ignores out-of-bounds index', () => {
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 1 }),
);
act(() => {
result.current.setCurrentIndex(10);
});
expect(result.current.currentIndex).toBe(1);
act(() => {
result.current.setCurrentIndex(-1);
});
expect(result.current.currentIndex).toBe(1);
});
});
describe('isNavigationBlocked', () => {
it('blocks navigation when callback returns true', () => {
const isNavigationBlocked = vi.fn(() => true);
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, isNavigationBlocked }),
);
act(() => {
result.current.goToNextTab();
});
expect(result.current.currentIndex).toBe(0);
expect(isNavigationBlocked).toHaveBeenCalled();
});
it('allows navigation when callback returns false', () => {
const isNavigationBlocked = vi.fn(() => false);
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, isNavigationBlocked }),
);
act(() => {
result.current.goToNextTab();
});
expect(result.current.currentIndex).toBe(1);
});
});
describe('onTabChange callback', () => {
it('calls onTabChange when tab changes via goToNextTab', () => {
const onTabChange = vi.fn();
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, onTabChange }),
);
act(() => {
result.current.goToNextTab();
});
expect(onTabChange).toHaveBeenCalledWith(1);
});
it('calls onTabChange when tab changes via setCurrentIndex', () => {
const onTabChange = vi.fn();
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, onTabChange }),
);
act(() => {
result.current.setCurrentIndex(2);
});
expect(onTabChange).toHaveBeenCalledWith(2);
});
it('does not call onTabChange when tab does not change', () => {
const onTabChange = vi.fn();
const { result } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, onTabChange }),
);
act(() => {
result.current.setCurrentIndex(0);
});
expect(onTabChange).not.toHaveBeenCalled();
});
});
describe('isFirstTab and isLastTab', () => {
it('returns correct boundary flags based on position', () => {
const { result: first } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 0 }),
);
expect(first.current.isFirstTab).toBe(true);
expect(first.current.isLastTab).toBe(false);
const { result: last } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 2 }),
);
expect(last.current.isFirstTab).toBe(false);
expect(last.current.isLastTab).toBe(true);
const { result: middle } = renderHook(() =>
useTabbedNavigation({ tabCount: 3, initialIndex: 1 }),
);
expect(middle.current.isFirstTab).toBe(false);
expect(middle.current.isLastTab).toBe(false);
});
});
describe('tabCount changes', () => {
it('reinitializes when tabCount changes', () => {
let tabCount = 5;
const { result, rerender } = renderHook(() =>
useTabbedNavigation({ tabCount, initialIndex: 4 }),
);
expect(result.current.currentIndex).toBe(4);
tabCount = 3;
rerender();
// Should clamp to valid range
expect(result.current.currentIndex).toBe(2);
});
});
});

View File

@@ -0,0 +1,240 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { useReducer, useCallback, useEffect, useRef } from 'react';
import { useKeypress, type Key } from './useKeypress.js';
import { keyMatchers, Command } from '../keyMatchers.js';
/**
* Options for the useTabbedNavigation hook.
*/
export interface UseTabbedNavigationOptions {
/** Total number of tabs */
tabCount: number;
/** Initial tab index (default: 0) */
initialIndex?: number;
/** Allow wrapping from last to first and vice versa (default: false) */
wrapAround?: boolean;
/** Whether left/right arrows navigate tabs (default: true) */
enableArrowNavigation?: boolean;
/** Whether Tab key advances to next tab (default: true) */
enableTabKey?: boolean;
/** Callback to determine if navigation is blocked (e.g., during text input) */
isNavigationBlocked?: () => boolean;
/** Whether the hook is active and should respond to keyboard input */
isActive?: boolean;
/** Callback when the active tab changes */
onTabChange?: (index: number) => void;
}
/**
* Result of the useTabbedNavigation hook.
*/
export interface UseTabbedNavigationResult {
/** Current tab index */
currentIndex: number;
/** Set the current tab index directly */
setCurrentIndex: (index: number) => void;
/** Move to the next tab (respecting bounds) */
goToNextTab: () => void;
/** Move to the previous tab (respecting bounds) */
goToPrevTab: () => void;
/** Whether currently at first tab */
isFirstTab: boolean;
/** Whether currently at last tab */
isLastTab: boolean;
}
interface TabbedNavigationState {
currentIndex: number;
tabCount: number;
wrapAround: boolean;
pendingTabChange: boolean;
}
type TabbedNavigationAction =
| { type: 'NEXT_TAB' }
| { type: 'PREV_TAB' }
| { type: 'SET_INDEX'; payload: { index: number } }
| {
type: 'INITIALIZE';
payload: { tabCount: number; initialIndex: number; wrapAround: boolean };
}
| { type: 'CLEAR_PENDING' };
function tabbedNavigationReducer(
state: TabbedNavigationState,
action: TabbedNavigationAction,
): TabbedNavigationState {
switch (action.type) {
case 'NEXT_TAB': {
const { tabCount, wrapAround, currentIndex } = state;
if (tabCount === 0) return state;
let nextIndex = currentIndex + 1;
if (nextIndex >= tabCount) {
nextIndex = wrapAround ? 0 : tabCount - 1;
}
if (nextIndex === currentIndex) return state;
return { ...state, currentIndex: nextIndex, pendingTabChange: true };
}
case 'PREV_TAB': {
const { tabCount, wrapAround, currentIndex } = state;
if (tabCount === 0) return state;
let nextIndex = currentIndex - 1;
if (nextIndex < 0) {
nextIndex = wrapAround ? tabCount - 1 : 0;
}
if (nextIndex === currentIndex) return state;
return { ...state, currentIndex: nextIndex, pendingTabChange: true };
}
case 'SET_INDEX': {
const { index } = action.payload;
const { tabCount, currentIndex } = state;
if (index === currentIndex) return state;
if (index < 0 || index >= tabCount) return state;
return { ...state, currentIndex: index, pendingTabChange: true };
}
case 'INITIALIZE': {
const { tabCount, initialIndex, wrapAround } = action.payload;
const validIndex = Math.max(0, Math.min(initialIndex, tabCount - 1));
return {
...state,
tabCount,
wrapAround,
currentIndex: tabCount > 0 ? validIndex : 0,
pendingTabChange: false,
};
}
case 'CLEAR_PENDING': {
return { ...state, pendingTabChange: false };
}
default: {
return state;
}
}
}
/**
* A headless hook that provides keyboard navigation for tabbed interfaces.
*
* Features:
* - Keyboard navigation with left/right arrows
* - Optional Tab key navigation
* - Optional wrap-around navigation
* - Navigation blocking callback (for text input scenarios)
*/
export function useTabbedNavigation({
tabCount,
initialIndex = 0,
wrapAround = false,
enableArrowNavigation = true,
enableTabKey = true,
isNavigationBlocked,
isActive = true,
onTabChange,
}: UseTabbedNavigationOptions): UseTabbedNavigationResult {
const [state, dispatch] = useReducer(tabbedNavigationReducer, {
currentIndex: Math.max(0, Math.min(initialIndex, tabCount - 1)),
tabCount,
wrapAround,
pendingTabChange: false,
});
const prevTabCountRef = useRef(tabCount);
const prevInitialIndexRef = useRef(initialIndex);
const prevWrapAroundRef = useRef(wrapAround);
useEffect(() => {
const tabCountChanged = prevTabCountRef.current !== tabCount;
const initialIndexChanged = prevInitialIndexRef.current !== initialIndex;
const wrapAroundChanged = prevWrapAroundRef.current !== wrapAround;
if (tabCountChanged || initialIndexChanged || wrapAroundChanged) {
dispatch({
type: 'INITIALIZE',
payload: { tabCount, initialIndex, wrapAround },
});
prevTabCountRef.current = tabCount;
prevInitialIndexRef.current = initialIndex;
prevWrapAroundRef.current = wrapAround;
}
}, [tabCount, initialIndex, wrapAround]);
useEffect(() => {
if (state.pendingTabChange) {
onTabChange?.(state.currentIndex);
dispatch({ type: 'CLEAR_PENDING' });
}
}, [state.pendingTabChange, state.currentIndex, onTabChange]);
const goToNextTab = useCallback(() => {
if (isNavigationBlocked?.()) return;
dispatch({ type: 'NEXT_TAB' });
}, [isNavigationBlocked]);
const goToPrevTab = useCallback(() => {
if (isNavigationBlocked?.()) return;
dispatch({ type: 'PREV_TAB' });
}, [isNavigationBlocked]);
const setCurrentIndex = useCallback(
(index: number) => {
if (isNavigationBlocked?.()) return;
dispatch({ type: 'SET_INDEX', payload: { index } });
},
[isNavigationBlocked],
);
const handleKeypress = useCallback(
(key: Key) => {
if (isNavigationBlocked?.()) return;
if (enableArrowNavigation) {
if (keyMatchers[Command.MOVE_RIGHT](key)) {
goToNextTab();
return;
}
if (keyMatchers[Command.MOVE_LEFT](key)) {
goToPrevTab();
return;
}
}
if (enableTabKey && key.name === 'tab' && !key.shift) {
goToNextTab();
}
},
[
enableArrowNavigation,
enableTabKey,
goToNextTab,
goToPrevTab,
isNavigationBlocked,
],
);
useKeypress(handleKeypress, { isActive: isActive && tabCount > 1 });
return {
currentIndex: state.currentIndex,
setCurrentIndex,
goToNextTab,
goToPrevTab,
isFirstTab: state.currentIndex === 0,
isLastTab: state.currentIndex === tabCount - 1,
};
}