Unify list and edit-mode handler flows in input helpers

This commit is contained in:
Jage9
2026-02-22 16:58:57 -05:00
parent ab26ceaafc
commit ccc7d1e525
3 changed files with 154 additions and 220 deletions

View File

@@ -0,0 +1,7 @@
export type EditSessionAction = 'submit' | 'cancel' | null;
export function getEditSessionAction(code: string): EditSessionAction {
if (code === 'Enter') return 'submit';
if (code === 'Escape') return 'cancel';
return null;
}

View File

@@ -0,0 +1,34 @@
import { cycleIndex, findNextIndexByInitial } from './listNavigation';
export type ListControlResult =
| { type: 'move'; index: number; reason: 'arrow' | 'initial' }
| { type: 'select' }
| { type: 'cancel' }
| { type: 'none' };
export function handleListControlKey<T>(
code: string,
key: string,
entries: readonly T[],
currentIndex: number,
labelFor: (entry: T) => string,
): ListControlResult {
if (entries.length === 0) return { type: 'none' };
if (code === 'ArrowDown' || code === 'ArrowUp') {
return {
type: 'move',
index: cycleIndex(currentIndex, entries.length, code === 'ArrowDown' ? 'next' : 'prev'),
reason: 'arrow',
};
}
const nextByInitial = findNextIndexByInitial(entries, currentIndex, key, labelFor);
if (nextByInitial >= 0) {
return { type: 'move', index: nextByInitial, reason: 'initial' };
}
if (code === 'Enter') return { type: 'select' };
if (code === 'Escape') return { type: 'cancel' };
return { type: 'none' };
}