diff --git a/README.md b/README.md index 5235ee0..4b7ded4 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Move focus around a HTML document using Left, Right, Up, Down keys. ## API
-getNextFocus(currentFocus, keyCode, [scope])
+getNextFocus(currentFocus, keyOrKeyCode, [scope])
 
### Parameters @@ -16,8 +16,9 @@ getNextFocus(currentFocus, keyCode, [scope]) [`HTMLElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) that you want LRUD spatial to consider as the element you are navigating _from_. In simple applications, this can just be a reference to `document.activeElement`. -- `keyCode` should be a - [`keyCode`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) +- `keyOrKeyCode` should be a + [`key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key) string or + a [`keyCode`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) decimal representing the directional key pressed. - `scope` is an optional `HTMLElement` that you only want to look for focusable candidates inside of. Defaults to the whole page if not provided. diff --git a/lib/lrud.js b/lib/lrud.js index 0adce96..9e6c763 100644 --- a/lib/lrud.js +++ b/lib/lrud.js @@ -242,6 +242,14 @@ const isValidCandidate = (entryRect, exitDir, exitPoint, entryWeighting) => { return false; }; +/** + * Get the closest spatial candidate + * + * @param {HTMLElement} elem The search origin + * @param {HTMLElement[]} candidates An set of candidate elements to assess + * @param {string} exitDir The direction in which we exited the elem (left, right, up, down) + * @return {HTMLElement|null} The element that was spatially closest elem in candidates + */ const getBestCandidate = (elem, candidates, exitDir) => { let bestCandidate = null; let bestDistance = Infinity; @@ -272,13 +280,14 @@ const getBestCandidate = (elem, candidates, exitDir) => { * Get the next focus candidate * * @param {HTMLElement} elem The search origin - * @param {string} exitDir The direction in which we exited the elem (left, right, up, down) + * @param {string|number} keyOrKeyCode The key or keyCode value (from KeyboardEvent) of the pressed key + * @param {HTMLElement} scope The element LRUD spatial is scoped to operate within * @return {HTMLElement} The element that should receive focus next */ -export const getNextFocus = (elem, keyCode, scope) => { +export const getNextFocus = (elem, keyOrKeyCode, scope) => { if (!scope || !scope.querySelector) scope = document.body; if (!elem) return getFocusables(scope)?.[0]; - const exitDir = _keyMap[keyCode]; + const exitDir = _keyMap[keyOrKeyCode]; // Get parent focus container const parentContainer = getParentContainer(elem); @@ -353,4 +362,8 @@ const _keyMap = { 212: _down, 204: _down, 216: _down, + "ArrowLeft": _left, + "ArrowRight": _right, + "ArrowUp": _up, + "ArrowDown": _down };