# misc/focusnavigator (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/misc/focusnavigator/

Directional focus navigator.

## FocusNavigator extends Object

Directional focus navigator.
- When moving between UI items with the gamepad D-pad / keyboard arrows,
  moves focus to the item with the smallest "distance among items ahead in the move direction,
  penalized by how far they deviate from the axis". (the standard approach for console UI navigation)
- Items are registered as { id, rect }. A pure coordinate algorithm independent of the rendering method.

Example: Move between menu items by direction

```js
import { FocusNavigator, Rect } from "./build/vanilla.js";

const focusNavigator = new FocusNavigator({ crossAxisPenalty: 2.5 });
focusNavigator.addItem("start", Rect.create(100, 100, 200, 60));
focusNavigator.addItem("options", Rect.create(100, 180, 200, 60));
focusNavigator.addItem("credits", Rect.create(320, 180, 200, 60));
console.log(focusNavigator.moveFocus(0, 1));
console.log(focusNavigator.moveFocus(0, 1));
console.log(focusNavigator.moveFocus(1, 0));
console.log(focusNavigator.moveFocus(1, 0));
console.log(focusNavigator.getFocusedId());
```

- `constructor(options = {})` (constructor, since 0.3.0): Constructor.
  - `options` object: { crossAxisPenalty = 2.5 }
- `addItem(id, rect)` (method, since 0.3.0): Registers an item.
  - `id` string: Item identifier.
  - `rect` Rect: Item rectangle. (distances are measured between centers)
- `clear()` (method, since 0.3.0): Removes all items.
- `setFocusedId(id)` (method, since 0.3.0): Sets the focus.
  - `id` string | null: Identifier of the item to focus. (no focus if null)
- `getFocusedId()` (method, since 0.3.0): Returns the current focus.
  - returns string | null: Identifier of the currently focused item. (null if none)
- `moveFocus(directionX, directionY)` (method, since 0.3.0): Moves in a direction.
  - directionX / directionY are -1, 0, 1. (e.g. right = (1, 0))
  - If nothing is focused, picks the top-left item regardless of direction.
  - If there is nowhere to move, keeps the focus and returns null.
  - `directionX` number: Horizontal direction. (-1, 0, 1)
  - `directionY` number: Vertical direction. (-1, 0, 1)
  - returns string | null: id of the newly focused item.
