Skip to content

Commit

Permalink
fix: correct behavior for focusable-less targets. Implements #41
Browse files Browse the repository at this point in the history
  • Loading branch information
theKashey committed Nov 24, 2022
1 parent 0a9b123 commit 9466d49
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 4 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules/
npm-debug.log
/dist/
.DS_Store
.DS_Store
coverage
10 changes: 10 additions & 0 deletions __tests__/focusMerge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,15 @@ describe('FocusMerge', () => {

expect(focusMerge(querySelector('#d1'), null)!.node.innerHTML).toBe('1');
});

it('autofocus - nothing to focus', () => {
document.body.innerHTML = `
<div id="d1">
<button disabled>1</button>
</div>
`;

expect(focusMerge(querySelector('#d1'), null)!).toBe(undefined);
});
});
});
10 changes: 9 additions & 1 deletion src/focusMerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,15 @@ export const getFocusMerge = (
const newId = newFocus(innerNodes, outerNodes, activeElement, lastNode as HTMLElement);

if (newId === NEW_FOCUS) {
return { node: pickAutofocus(anyFocusable, innerNodes, allParentAutofocusables(entries, visibilityCache)) };
const focusNode = pickAutofocus(anyFocusable, innerNodes, allParentAutofocusables(entries, visibilityCache));

if (focusNode) {
return { node: focusNode };
} else {
console.warn('focus-lock: cannot find any node to move focus into');

return undefined;
}
}

if (newId === undefined) {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/auto-focus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const pickAutofocus = (
nodesIndexes: NodeIndex[],
orderedNodes: HTMLElement[],
groups: Element[]
): HTMLElement => {
): HTMLElement | undefined => {
const nodes = nodesIndexes.map(({ node }) => node);

const autoFocusable = filterAutoFocusable(nodes.filter(findAutoFocused(groups)));
Expand Down
2 changes: 1 addition & 1 deletion src/utils/firstFocus.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { correctNode } from './correctFocus';

export const pickFirstFocus = (nodes: HTMLElement[]): HTMLElement => {
export const pickFirstFocus = (nodes: HTMLElement[]): HTMLElement | undefined => {
if (nodes[0] && nodes.length > 1) {
return correctNode(nodes[0], nodes);
}
Expand Down

0 comments on commit 9466d49

Please sign in to comment.