triggerFocus function

Future triggerFocus(
  1. Element target, {
  2. Duration timeout = _defaultTriggerTimeout,
})

Focuses the target and returns a Future when that focus event is fired.

Verifies that the target element is not a detached node.

This is necessary because IE 11 focus events are async.

See: connect.microsoft.com/IE/feedback/details/2238257/ie11-focus-change-delayed-when-using-the-focus-method.

Implementation

Future triggerFocus(Element target, {Duration timeout = _defaultTriggerTimeout}) {
  if (!document.documentElement!.contains(target)) {
    throw ArgumentError.value(target, 'target', 'Target should be attached to the document.');
  }

  var completer = Completer()
    ..complete(target.onFocus.first);

  target.focus();

  return completer.future.timeout(timeout,
      onTimeout: () => Future.error('Failed to focus; try ensuring that your browser window is at the foreground'));
}