Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/core/src/events/FocusManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,4 +264,21 @@ describe('FocusManager Re-entrancy', () => {
// After re-entrant focusNext, should end up on 'c'
expect(fm.currentId).toBe('c');
});

it('registering a new focusable that sorts before current does not change current focus', () => {
const fm = new FocusManager();
// A (10), B (20)
fm.register(makeWidget('a', 10, true));
fm.register(makeWidget('b', 20, true));

// Focus B
fm.focusWidget('b');
expect(fm.currentId).toBe('b');

// Register C with lower tabIndex that sorts before existing items
fm.register(makeWidget('c', 5, true));

// Observable behavior: focused id must remain 'b'
expect(fm.currentId).toBe('b');
});
});
11 changes: 11 additions & 0 deletions packages/core/src/events/FocusManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,20 @@ export class FocusManager {
* they are not lost when App has not yet subscribed to them.
*/
register(focusable: Focusable): void {
// Preserve currently focused id so that sorting the master list
// does not accidentally change which widget is focused.
const prevFocusedId = this.currentId;

this._focusables.push(focusable);
this._focusables.sort((a, b) => a.tabIndex - b.tabIndex);

// If there was a previously focused widget, relocate _currentIndex
// to point to the same widget after the sort.
if (prevFocusedId) {
const newIdx = this._focusables.findIndex(f => f.id === prevFocusedId);
if (newIdx >= 0) this._currentIndex = newIdx;
}

// Auto-focus the first widget if nothing is focused
if (this._currentIndex < 0 && focusable.focusable) {
this._currentIndex = this._focusables.indexOf(focusable);
Expand Down
Loading