@@ -26,6 +26,8 @@ export interface NavPoint {
2626 group ?: string
2727 /** Index in NavGraph.flat — set by buildNavGraph for O(1) lookup */
2828 _flatIndex ?: number
29+ /** Index within its group — set by buildNavGraph for O(1) resolvePosition */
30+ _groupIndex ?: number
2931}
3032
3133// ── Navigation Graph ─────────────────────────────────────────────────────
@@ -73,9 +75,12 @@ export function buildNavGraph(points: NavPoint[]): NavGraph {
7375 arr . push ( p )
7476 }
7577
76- // Sort within each group by x then y
78+ // Sort within each group by x then y, then stamp group indices
7779 for ( const arr of byGroup . values ( ) ) {
7880 arr . sort ( ( a , b ) => a . x - b . x || a . y - b . y )
81+ for ( let i = 0 ; i < arr . length ; i ++ ) {
82+ arr [ i ] . _groupIndex = i
83+ }
7984 }
8085
8186 // Sort groups by first point's y position (top-to-bottom ordering)
@@ -110,10 +115,8 @@ export function resolvePosition(graph: NavGraph, flatIndex: number): NavPosition
110115 const clamped = Math . max ( 0 , Math . min ( flatIndex , graph . flat . length - 1 ) )
111116 const point = graph . flat [ clamped ]
112117 const group = point . group ?? "_default"
113- const groupPoints = graph . byGroup . get ( group ) ?? [ ]
114- // Use _flatIndex equality for O(1) lookup within group
115- const idx = groupPoints . findIndex ( p => p . _flatIndex === clamped )
116- return { flatIndex : clamped , group, indexInGroup : idx >= 0 ? idx : 0 }
118+ // O(1) via stamped _groupIndex
119+ return { flatIndex : clamped , group, indexInGroup : point . _groupIndex ?? 0 }
117120}
118121
119122/**
@@ -414,9 +417,14 @@ export function nextNetworkIndex(
414417 return pos . flatIndex
415418 }
416419
417- default :
418- // PageUp/Down, Home/End, Escape handled by generic handler
419- return nextGraphIndex ( key , pos , graph )
420+ default : {
421+ // PageUp/Down, Home/End, Escape move focus away — reset neighbor cycling
422+ const result = nextGraphIndex ( key , pos , graph )
423+ if ( result !== null && result !== pos . flatIndex ) {
424+ neighborIndexRef . current = - 1
425+ }
426+ return result
427+ }
420428 }
421429}
422430
0 commit comments