Skip to content

Commit

Permalink
correctly detect next and prev focusable items
Browse files Browse the repository at this point in the history
  • Loading branch information
edoardocavazza committed Apr 18, 2023
1 parent a07b9b1 commit eb8015d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/fuzzy-fireants-reflect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chialab/loock": minor
---

Correctly detect prev and next focusable item.
43 changes: 24 additions & 19 deletions src/Context.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dispatchAsyncEvent } from '@chialab/dna';
import { Node, dispatchAsyncEvent } from '@chialab/dna';

/**
* Default focusable selectors.
Expand Down Expand Up @@ -146,11 +146,12 @@ export class Context {
if (this.disabled) {
return;
}
const elements = this.findFocusableChildren();
const activeElement = /** @type {HTMLElement} */ (this.parent.root.document.activeElement);
if (activeElement && elements.indexOf(activeElement) !== -1) {
if (activeElement && (element === activeElement || element.contains(activeElement))) {
return;
}

const elements = this.findFocusableChildren();
let target = event.target;
while (element.contains(target) || target === element) {
if (elements.indexOf(target) !== -1) {
Expand Down Expand Up @@ -244,15 +245,17 @@ export class Context {
this.restore();
return;
}
let io = children.indexOf(this._currentElement);
if (io === 0) {
io = children.length - 1;
} else if (io !== -1) {
io = io - 1;
} else {
io = children.length - 1;

const current = this._currentElement;
if (!current) {
this.setCurrentElement(children[children.length - 1]);
return;
}
this.setCurrentElement(children[io]);

const nearest = children.filter((child) =>
current.compareDocumentPosition(child) & Node.DOCUMENT_POSITION_PRECEDING
).pop();
this.setCurrentElement(nearest || children[children.length - 1]);
}

/**
Expand All @@ -269,15 +272,17 @@ export class Context {
this.restore();
return;
}
let io = children.indexOf(this._currentElement);
if (io === children.length - 1) {
io = 0;
} else if (io !== -1) {
io = io + 1;
} else {
io = 0;

const current = this._currentElement;
if (!current) {
this.setCurrentElement(children[0]);
return;
}
this.setCurrentElement(children[io]);

const nearest = children.filter((child) =>
current.compareDocumentPosition(child) & Node.DOCUMENT_POSITION_FOLLOWING
).shift();
this.setCurrentElement(nearest || children[0]);
}

/**
Expand Down

0 comments on commit eb8015d

Please sign in to comment.