Skip to content

Commit

Permalink
Always update focus on moving inside a container (#37)
Browse files Browse the repository at this point in the history
* New test

* Add data-focus early
  • Loading branch information
Murreey authored Jan 11, 2024
1 parent 1878117 commit 3c38434
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
5 changes: 3 additions & 2 deletions lib/lrud.js
Original file line number Diff line number Diff line change
Expand Up @@ -317,22 +317,23 @@ export const getNextFocus = (elem, keyOrKeyCode, scope) => {
const isNestedContainer = parentContainer?.contains(candidateContainer);
const isAnscestorContainer = candidateContainer?.contains(parentContainer);

if (elem.id) parentContainer?.setAttribute('data-focus', elem.id);

if (!isCurrentContainer && (!isNestedContainer || isBestCandidateAContainer)) {
const blockedExitDirs = getBlockedExitDirs(parentContainer, candidateContainer);
if (blockedExitDirs.indexOf(exitDir) > -1) return;

if (candidateContainer && !isAnscestorContainer) {
// Ignore active child behaviour when moving into a container that we
// are already nested in
if (elem.id) parentContainer?.setAttribute('data-focus', elem.id);

const lastActiveChild = document.getElementById(candidateContainer.getAttribute('data-focus'));

return lastActiveChild || getFocusables(candidateContainer)?.[0];
}
}
}

if (bestCandidate?.id) parentContainer?.setAttribute('data-focus', bestCandidate.id);
return bestCandidate;
};

Expand Down
11 changes: 11 additions & 0 deletions test/lrud.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -667,5 +667,16 @@ describe('LRUD spatial', () => {
await page.keyboard.press('ArrowUp');
expect(await page.evaluate(() => document.activeElement.id)).toEqual('item-1');
});

it('should still remember last active child if focus is manually moved from a container', async () => {
await page.evaluate(() => document.getElementById('item-1').focus());
await page.keyboard.press('ArrowDown');
await page.keyboard.press('ArrowRight');
expect(await page.evaluate(() => document.activeElement.id)).toEqual('item-6');
await page.evaluate(() => document.getElementById('item-8').focus());

await page.keyboard.press('ArrowUp');
expect(await page.evaluate(() => document.activeElement.id)).toEqual('item-6');
});
});
});

0 comments on commit 3c38434

Please sign in to comment.