# FocusCycler

class

A utility class that helps cycling over [focusable views](module_ui_focuscycler-FocusableView.md) in a [`ViewCollection`](module_ui_viewcollection-ViewCollection.md) when the focus is tracked by the [`FocusTracker`](module_utils_focustracker-FocusTracker.md) instance. It helps implementing keyboard navigation in HTML forms, toolbars, lists and the like.

To work properly it requires:

* a collection of focusable (HTML `tabindex` attribute) views that implement the `focus()` method,
* an associated focus tracker to determine which view is focused.

A simple cycler setup can look like this:

```typescript
const focusables = new ViewCollection<FocusableView>();
const focusTracker = new FocusTracker();

// Add focusable views to the focus tracker.
focusTracker.add( ... );
```

Then, the cycler can be used manually:

```typescript
const cycler = new FocusCycler( { focusables, focusTracker } );

// Will focus the first focusable view in #focusables.
cycler.focusFirst();

// Will log the next focusable item in #focusables.
console.log( cycler.next );
```

Alternatively, it can work side by side with the [`KeystrokeHandler`](module_utils_keystrokehandler-KeystrokeHandler.md):

```typescript
const keystrokeHandler = new KeystrokeHandler();

// Activate the keystroke handler.
keystrokeHandler.listenTo( sourceOfEvents );

const cycler = new FocusCycler( {
	focusables, focusTracker, keystrokeHandler,
	actions: {
		// When arrowup of arrowleft is detected by the #keystrokeHandler,
		// focusPrevious() will be called on the cycler.
		focusPrevious: [ 'arrowup', 'arrowleft' ],
	}
} );
```

Check out the ["Deep dive into focus tracking"](../framework/deep-dive/ui/focus-tracking.md) guide to learn more.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L77)

<a id="properties">

## Properties

<a id="member-actions">

### `actions?: FocusCyclerActions` _(readonly)_

Actions that the cycler can take when a keystroke is pressed. Requires `options.keystrokeHandler` to be passed and working. When an action is performed, `preventDefault` and `stopPropagation` will be called on the event the keystroke fired in the DOM.

```typescript
actions: {
	// Will call #focusPrevious() when arrowleft or arrowup is pressed.
	focusPrevious: [ 'arrowleft', 'arrowup' ],

	// Will call #focusNext() when arrowdown is pressed.
	focusNext: 'arrowdown'
}
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L111)

<a id="member-current">

### `current: number | null` _(readonly)_

An index of the view in the [`focusables`](#member-focusables) which is focused according to [`focusTracker`](#member-focusTracker). Returns `null` when there is no such view.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L197)

<a id="member-first">

### `first: FocusableView | null` _(readonly)_

Returns the first focusable view in [`focusables`](#member-focusables). Returns `null` if there is none.

**Note**: Hidden views (e.g. with `display: none`) are ignored.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L159)

<a id="member-focusTracker">

### `focusTracker: FocusTracker` _(readonly)_

A focus tracker instance that the cycler uses to determine the current focus state in [`focusables`](#member-focusables).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L87)

<a id="member-focusables">

### `focusables: ViewCollection<FocusableView>` _(readonly)_

A [focusable views](module_ui_focuscycler-FocusableView.md) collection that the cycler operates on.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L81)

<a id="member-keystrokeHandler">

### `keystrokeHandler?: KeystrokeHandler` _(readonly)_

An instance of the [`KeystrokeHandler`](module_utils_keystrokehandler-KeystrokeHandler.md) which can respond to certain keystrokes and cycle the focus.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L93)

<a id="member-last">

### `last: FocusableView | null` _(readonly)_

Returns the last focusable view in [`focusables`](#member-focusables). Returns `null` if there is none.

**Note**: Hidden views (e.g. with `display: none`) are ignored.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L169)

<a id="member-next">

### `next: FocusableView | null` _(readonly)_

Returns the next focusable view in [`focusables`](#member-focusables) based on [`current`](#member-current). Returns `null` if there is none.

**Note**: Hidden views (e.g. with `display: none`) are ignored.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L179)

<a id="member-previous">

### `previous: FocusableView | null` _(readonly)_

Returns the previous focusable view in [`focusables`](#member-focusables) based on [`current`](#member-current). Returns `null` if there is none.

**Note**: Hidden views (e.g. with `display: none`) are ignored.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L189)

<a id="methods">

## Methods

<a id="function-constructor">

### `constructor( options = { options.actions?, options.focusables, options.focusTracker, options.keystrokeHandler?, options.keystrokeHandlerOptions? } )`

Creates an instance of the focus cycler utility.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L118)

#### Parameters

* `options: object`

  Configuration options.

  Properties

  * `options.actions?: FocusCyclerActions`
  * `options.focusables: ViewCollection<FocusableView>`
  * `options.focusTracker: FocusTracker`
  * `options.keystrokeHandler?: KeystrokeHandler`
  * `options.keystrokeHandlerOptions?: KeystrokeHandlerOptions`

<a id="function-chain">

### `chain( chainedFocusCycler ) → void`

Allows for creating continuous focus cycling across multiple focus cyclers and their collections of [`focusables`](#member-focusables).

It starts listening to the [`FocusCyclerForwardCycleEvent`](module_ui_focuscycler-FocusCyclerForwardCycleEvent.md) and [`FocusCyclerBackwardCycleEvent`](module_ui_focuscycler-FocusCyclerBackwardCycleEvent.md) events of the chained focus cycler and engages, whenever the user reaches the last (forwards navigation) or first (backwards navigation) focusable view and would normally start over. Instead, the navigation continues on the higher level (flattens).

For instance, for the following nested focus navigation structure, the focus would get stuck the moment the AB gets focused and its focus cycler starts managing it:

```
   ┌────────────┐   ┌──────────────────────────────────┐   ┌────────────┐
   │ AA         │   │ AB                               │   │ AC         │
   │            │   │                                  │   │            │
   │            │   │    ┌─────┐  ┌─────┐  ┌─────┐     │   │            │
   │            │   │ ┌──► ABA ├──► ABB ├──► ABC ├───┐ │   │            │
   │            ├───► │  └─────┘  └─────┘  └─────┘   │ │   │            │
   │            │   │ │                              │ │   │            │
   │            │   │ │                              │ │   │            │
   │            │   │ └──────────────────────────────┘ │   │            │
   │            │   │                                  │   │            │
   └────────────┘   └──────────────────────────────────┘   └────────────┘
```

Chaining a focus tracker that manages AA, AB, and AC with the focus tracker that manages ABA, ABB, and ABC creates a seamless navigation experience instead:

```
   ┌────────────┐   ┌──────────────────────────────────┐   ┌────────────┐
   │ AA         │   │ AB                               │   │ AC         │
   │            │   │                                  │   │            │
   │            │   │    ┌─────┐  ┌─────┐  ┌─────┐     │   │            │
   │            │   │ ┌──► ABA ├──► ABB ├──► ABC ├──┐  │   │            │
┌──►            ├───┼─┘  └─────┘  └─────┘  └─────┘  └──┼───►            ├──┐
│  │            │   │                                  │   │            │  │
│  │            │   │                                  │   │            │  │
│  │            │   │                                  │   │            │  │
│  │            │   │                                  │   │            │  │
│  └────────────┘   └──────────────────────────────────┘   └────────────┘  │
│                                                                          │
│                                                                          │
└──────────────────────────────────────────────────────────────────────────┘
```

See [`unchain`](#function-unchain) to reverse the chaining.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L325)

#### Parameters

* `chainedFocusCycler: FocusCycler`

#### Returns

* `void`

<a id="function-delegate">

### `delegate( events ) → EmitterMixinDelegateChain` _(inherited)_

Delegates selected events to another [`Emitter`](module_utils_emittermixin-Emitter.md). For instance:

```typescript
emitterA.delegate( 'eventX' ).to( emitterB );
emitterA.delegate( 'eventX', 'eventY' ).to( emitterC );
```

then `eventX` is delegated (fired by) `emitterB` and `emitterC` along with `data`:

```typescript
emitterA.fire( 'eventX', data );
```

and `eventY` is delegated (fired by) `emitterC` along with `data`:

```typescript
emitterA.fire( 'eventY', data );
```

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L539)

#### Parameters

* `events: Array<string>`

  Event names that will be delegated to another emitter.

#### Returns

* `EmitterMixinDelegateChain`

<a id="function-fire">

### `fire( eventOrInfo, args ) → GetEventInfo<TEvent>[ 'return' ]` _(inherited)_

Fires an event, executing all callbacks registered for it.

The first parameter passed to callbacks is an [`EventInfo`](module_utils_eventinfo-EventInfo.md) object, followed by the optional `args` provided in the `fire()` method call.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L512)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type describing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `eventOrInfo: GetNameOrEventInfo<TEvent>`

  The name of the event or `EventInfo` object if event is delegated.

* `args: TEvent[ 'args' ]`

  Additional arguments to be passed to the callbacks.

#### Returns

* `GetEventInfo<TEvent>[ 'return' ]`

  By default the method returns `undefined`. However, the return value can be changed by listeners through modification of the [`evt.return`](module_utils_eventinfo-EventInfo.md#member-return)'s property (the event info is the first param of every callback).

<a id="function-focusFirst">

### `focusFirst() → void`

Focuses the [`first`](#member-first) item in [`focusables`](#member-focusables).

**Note**: Hidden views (e.g. with `display: none`) are ignored.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L223)

#### Returns

* `void`

<a id="function-focusLast">

### `focusLast() → void`

Focuses the [`last`](#member-last) item in [`focusables`](#member-focusables).

**Note**: Hidden views (e.g. with `display: none`) are ignored.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L232)

#### Returns

* `void`

<a id="function-focusNext">

### `focusNext() → void`

Focuses the [`next`](#member-next) item in [`focusables`](#member-focusables).

**Note**: Hidden views (e.g. with `display: none`) are ignored.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L241)

#### Returns

* `void`

<a id="function-focusPrevious">

### `focusPrevious() → void`

Focuses the [`previous`](#member-previous) item in [`focusables`](#member-focusables).

**Note**: Hidden views (e.g. with `display: none`) are ignored.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L266)

#### Returns

* `void`

<a id="function-listenTo:BASE_EMITTER">

### `listenTo( emitter, event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed when an event is fired in a specific (emitter) object.

Events can be grouped in namespaces using `:`. When namespaced event is fired, it additionally fires all callbacks for that namespace.

```typescript
// myEmitter.on( ... ) is a shorthand for myEmitter.listenTo( myEmitter, ... ).
myEmitter.on( 'myGroup', genericCallback );
myEmitter.on( 'myGroup:myEvent', specificCallback );

// genericCallback is fired.
myEmitter.fire( 'myGroup' );
// both genericCallback and specificCallback are fired.
myEmitter.fire( 'myGroup:myEvent' );
// genericCallback is fired even though there are no callbacks for "foo".
myEmitter.fire( 'myGroup:foo' );
```

An event callback can [stop the event](module_utils_eventinfo-EventInfo.md#member-stop) and set the [return value](module_utils_eventinfo-EventInfo.md#member-return) of the [`fire`](#function-fire) method.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L475)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type describing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `emitter: Emitter`

  The object that fires the event.

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-off">

### `off( event, callback ) → void` _(inherited)_

Stops executing the callback on the given event. Shorthand for [`this.stopListening( this, event, callback )`](#function-stopListening:BASE_STOP).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L444)

#### Parameters

* `event: string`

  The name of the event.

* `callback: Function`

  The function to stop being called.

#### Returns

* `void`

<a id="function-on">

### `on( event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed when an event is fired.

Shorthand for [`this.listenTo( this, event, callback, options )`](#function-listenTo:BASE_EMITTER) (it makes the emitter listen on itself).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L416)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type descibing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-once">

### `once( event, callback, options? ) → void` _(inherited)_

Registers a callback function to be executed on the next time the event is fired only. This is similar to calling [`on`](#function-on) followed by [`off`](#function-off) in the callback.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L431)

#### Type parameters

* `TEvent: extends BaseEvent`

  The type descibing the event. See [`BaseEvent`](module_utils_emittermixin-BaseEvent.md).

#### Parameters

* `event: TEvent[ 'name' ]`

  The name of the event.

* `callback: GetCallback<TEvent>`

  The function to be called on event.

* `options?: GetCallbackOptions<TEvent>`

  Additional options.

#### Returns

* `void`

<a id="function-stopDelegating">

### `stopDelegating( event?, emitter? ) → void` _(inherited)_

Stops delegating events. It can be used at different levels:

* To stop delegating all events.
* To stop delegating a specific event to all emitters.
* To stop delegating a specific event to a specific emitter.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L552)

#### Parameters

* `event?: string`

  The name of the event to stop delegating. If omitted, stops it all delegations.

* `emitter?: Emitter`

  (requires `event`) The object to stop delegating a particular event to. If omitted, stops delegation of `event` to all emitters.

#### Returns

* `void`

<a id="function-stopListening:BASE_STOP">

### `stopListening( emitter?, event?, callback? ) → void` _(inherited)_

Stops listening for events. It can be used at different levels:

* To stop listening to a specific callback.
* To stop listening to a specific event.
* To stop listening to all events fired by a specific object.
* To stop listening to all events fired by all objects.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-utils/src/emittermixin.ts#L497)

#### Parameters

* `emitter?: Emitter`

  The object to stop listening to. If omitted, stops it for all objects.

* `event?: string`

  (Requires the `emitter`) The name of the event to stop listening to. If omitted, stops it for all events from `emitter`.

* `callback?: Function`

  (Requires the `event`) The function to be removed from the call list for the given `event`.

#### Returns

* `void`

<a id="function-unchain">

### `unchain( otherFocusCycler ) → void`

Reverses a chaining made by [`chain`](#function-chain).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L367)

#### Parameters

* `otherFocusCycler: FocusCycler`

#### Returns

* `void`

<a id="function-_focus">

### `_focus( view, direction ) → void` _(private)_

Focuses the given view if it exists.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L378)

#### Parameters

* `view: FocusableView | null`

  The view to be focused

* `direction: 1 | 1`

  The direction of the focus if the view has focusable children.

#### Returns

* `void`

<a id="function-_getDomFocusableItem">

### `_getDomFocusableItem( step ) → FocusableView | null` _(private)_

Returns the next or previous focusable view in [`focusables`](#member-focusables) with respect to [`current`](#member-current).

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L394)

#### Parameters

* `step: 1 | 1`

  Either `1` for checking forward from [`current`](#member-current) or `-1` for checking backwards.

#### Returns

* `FocusableView | null`

<a id="events">

## Events

<a id="event-backwardCycle">

### `backwardCycle( eventInfo )`

Fired when the focus cycler is about to move the focus from the first focusable item to the last one.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L480)

#### Parameters

* `eventInfo: EventInfo`

  An object containing information about the fired event.

<a id="event-forwardCycle">

### `forwardCycle( eventInfo )`

Fired when the focus cycler is about to move the focus from the last focusable item to the first one.

[See source](https://github.com/ckeditor/ckeditor5/blob/master/packages/ckeditor5-ui/src/focuscycler.ts#L469)

#### Parameters

* `eventInfo: EventInfo`

  An object containing information about the fired event.

---

Full index of the CKEditor 5 API reference: [llms.txt](llms.txt)
