focus.dart 11 KB
Newer Older
Eric Seidel's avatar
Eric Seidel committed
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7
import 'dart:async';

import 'basic.dart';
8
import 'framework.dart';
9 10
import 'media_query.dart';
import 'scrollable.dart';
Eric Seidel's avatar
Eric Seidel committed
11

12 13 14 15 16
// _noFocusedScope is used by Focus to track the case where none of the Focus
// component's subscopes (e.g. dialogs) are focused. This is distinct from the
// focused scope being null, which means that we haven't yet decided which scope
// is focused and whichever is the first scope to ask for focus will get it.
final GlobalKey _noFocusedScope = new GlobalKey();
Eric Seidel's avatar
Eric Seidel committed
17

18
class _FocusScope extends InheritedWidget {
19 20
  _FocusScope({
    Key key,
21
    this.focusState,
22 23 24
    this.scopeFocused: true, // are we focused in our ancestor scope?
    this.focusedScope, // which of our descendant scopes is focused, if any?
    this.focusedWidget,
Eric Seidel's avatar
Eric Seidel committed
25 26 27
    Widget child
  }) : super(key: key, child: child);

28
  final _FocusState focusState;
Hixie's avatar
Hixie committed
29
  final bool scopeFocused;
30

31
  // These are mutable because we implicitly change them when they're null in
32 33 34 35 36
  // certain cases, basically pretending retroactively that we were constructed
  // with the right keys.
  GlobalKey focusedScope;
  GlobalKey focusedWidget;

37 38 39
  // The _setFocusedWidgetIfUnset() methodsdon't need to notify descendants
  // because by definition they are only going to make a change the very first
  // time that our state is checked.
40 41

  void _setFocusedWidgetIfUnset(GlobalKey key) {
42 43 44
    focusState._setFocusedWidgetIfUnset(key);
    focusedWidget = focusState._focusedWidget;
    focusedScope = focusState._focusedScope == _noFocusedScope ? null : focusState._focusedScope;
45 46
  }

47 48
  bool updateShouldNotify(_FocusScope oldWidget) {
    if (scopeFocused != oldWidget.scopeFocused)
49 50 51
      return true;
    if (!scopeFocused)
      return false;
52
    if (focusedScope != oldWidget.focusedScope)
53 54 55
      return true;
    if (focusedScope != null)
      return false;
56
    if (focusedWidget != oldWidget.focusedWidget)
57 58 59 60
      return true;
    return false;
  }

Hixie's avatar
Hixie committed
61 62 63 64 65 66 67 68 69
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    if (scopeFocused)
      description.add('this scope has focus');
    if (focusedScope != null)
      description.add('focused subscope: $focusedScope');
    if (focusedWidget != null)
      description.add('focused widget: $focusedWidget');
  }
70 71
}

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
/// A scope for managing the focus state of descendant widgets.
///
/// The focus represents where the user's attention is directed. If the use
/// interacts with the system in a way that isn't visually directed at a
/// particular widget (e.g., by typing on a keyboard), the interaction is
/// directed to the currently focused widget.
///
/// The focus system consists of a tree of Focus widgets, which is embedded in
/// the widget tree. Focus widgets themselves can be focused in their enclosing
/// Focus widget, which means that their subtree is the one that has the current
/// focus. For example, a dialog creates a Focus widget to maintain focus
/// within the dialog.  When the dialog closes, its Focus widget is removed from
/// the tree and focus is restored to whichever other part of the Focus tree
/// previously had focus.
///
/// In addition to tracking which enclosed Focus widget has focus, each Focus
/// widget also tracks a GlobalKey, which represents the currently focused
/// widget in this part of the focus tree. If this Focus widget is the currently
/// focused subtree of the focus system (i.e., the path from it to the root is
/// focused at each level and it hasn't focused any of its enclosed Focus
/// widgets), then the widget this this global key actually has the focus in the
/// entire system.
94 95
class Focus extends StatefulComponent {
  Focus({
96
    GlobalKey key,
97 98
    this.child
  }) : super(key: key) {
99
    assert(key != null);
100 101
  }

102
  final Widget child;
103

104 105 106
  /// The key that currently has focus globally in the entire focus tree.
  ///
  /// This field is always null except in checked mode.
107 108
  static GlobalKey debugOnlyFocusedKey;

109 110 111 112
  /// Whether the focus is current at the given context.
  ///
  /// If autofocus is true, the given context will become focused if no other
  /// widget is already focused.
113
  static bool at(BuildContext context, { bool autofocus: false }) {
114 115 116 117
    assert(context != null);
    assert(context.widget != null);
    assert(context.widget.key != null);
    assert(context.widget.key is GlobalKey);
Ian Hickson's avatar
Ian Hickson committed
118
    _FocusScope focusScope = context.inheritFromWidgetOfExactType(_FocusScope);
Hixie's avatar
Hixie committed
119 120
    if (focusScope != null) {
      if (autofocus)
121
        focusScope._setFocusedWidgetIfUnset(context.widget.key);
Hixie's avatar
Hixie committed
122 123
      return focusScope.scopeFocused &&
             focusScope.focusedScope == null &&
124
             focusScope.focusedWidget == context.widget.key;
Hixie's avatar
Hixie committed
125
    }
126 127 128 129 130 131 132 133 134
    assert(() {
      if (debugOnlyFocusedKey?.currentContext == null)
        debugOnlyFocusedKey = context.widget.key;
      if (debugOnlyFocusedKey != context.widget.key) {
        debugPrint('Tried to focus widgets with two different keys: $debugOnlyFocusedKey and ${context.widget.key}');
        assert('If you have more than one focusable widget, then you should put them inside a Focus.' == true);
      }
      return true;
    });
Hixie's avatar
Hixie committed
135 136 137
    return true;
  }

138
  static bool _atScope(BuildContext context) {
139 140 141
    assert(context != null);
    assert(context.widget != null);
    assert(context.widget is Focus);
142
    assert(context.widget.key != null);
Ian Hickson's avatar
Ian Hickson committed
143
    _FocusScope focusScope = context.inheritFromWidgetOfExactType(_FocusScope);
Hixie's avatar
Hixie committed
144 145
    if (focusScope != null) {
      return focusScope.scopeFocused &&
146
             focusScope.focusedScope == context.widget.key;
Hixie's avatar
Hixie committed
147 148 149 150
    }
    return true;
  }

151 152
  /// Focuses a particular widget, identified by its GlobalKey.
  /// The widget must be in the widget tree.
153
  ///
154 155 156
  /// Don't call moveTo() from your build() functions, it's intended to be
  /// called from event listeners, e.g. in response to a finger tap or tab key.
  static void moveTo(GlobalKey key) {
157 158
    BuildContext focusedContext = key.currentContext;
    assert(focusedContext != null);
Ian Hickson's avatar
Ian Hickson committed
159
    _FocusScope focusScope = key.currentContext.ancestorWidgetOfExactType(_FocusScope);
160
    if (focusScope != null) {
161
      focusScope.focusState._setFocusedWidget(key);
162 163
      Scrollable.ensureVisible(focusedContext);
    }
164 165
  }

166 167
  /// Unfocuses the currently focused widget (if any) in the Focus that most
  /// tightly encloses the given context.
168 169 170 171 172 173
  static void clear(BuildContext context) {
    _FocusScope focusScope = context.ancestorWidgetOfExactType(_FocusScope);
    if (focusScope != null)
      focusScope.focusState._clearFocusedWidget();
  }

174
  /// Focuses a particular focus scope, identified by its GlobalKey.
175
  ///
176 177
  /// Don't call moveScopeTo() from your build() functions, it's intended to be
  /// called from event listeners, e.g. in response to a finger tap or tab key.
178 179 180 181 182 183 184 185 186 187
  static void moveScopeTo(GlobalKey key, { BuildContext context }) {
    _FocusScope focusScope;
    BuildContext searchContext = key.currentContext;
    if (searchContext != null) {
      assert(key.currentWidget is Focus);
      focusScope = searchContext.ancestorWidgetOfExactType(_FocusScope);
      assert(context == null || focusScope == context.ancestorWidgetOfExactType(_FocusScope));
    } else {
      focusScope = context.ancestorWidgetOfExactType(_FocusScope);
    }
Hixie's avatar
Hixie committed
188
    if (focusScope != null)
189
      focusScope.focusState._setFocusedScope(key);
Hixie's avatar
Hixie committed
190 191
  }

192
  _FocusState createState() => new _FocusState();
193
}
194

195
class _FocusState extends State<Focus> {
196 197 198 199 200 201 202 203 204 205 206 207
  void initState() {
    super.initState();
    _updateWidgetRemovalListener(_focusedWidget);
    _updateScopeRemovalListener(_focusedScope);
  }

  void dispose() {
    _updateWidgetRemovalListener(null);
    _updateScopeRemovalListener(null);
    super.dispose();
  }

208 209
  GlobalKey _focusedWidget; // when null, the first component to ask if it's focused will get the focus
  GlobalKey _currentlyRegisteredWidgetRemovalListenerKey;
Eric Seidel's avatar
Eric Seidel committed
210

211 212 213 214 215 216 217
  void _setFocusedWidget(GlobalKey key) {
    setState(() {
      _focusedWidget = key;
      if (_focusedScope == null)
        _focusedScope = _noFocusedScope;
    });
    _updateWidgetRemovalListener(key);
Eric Seidel's avatar
Eric Seidel committed
218
  }
219 220 221 222 223 224

  void _setFocusedWidgetIfUnset(GlobalKey key) {
    if (_focusedWidget == null && (_focusedScope == null || _focusedScope == _noFocusedScope)) {
      _focusedWidget = key;
      _focusedScope = _noFocusedScope;
      _updateWidgetRemovalListener(key);
Eric Seidel's avatar
Eric Seidel committed
225 226 227
    }
  }

228 229 230 231 232 233 234 235 236
  void _clearFocusedWidget() {
    if (_focusedWidget != null) {
      _updateWidgetRemovalListener(null);
      setState(() {
        _focusedWidget = null;
      });
    }
  }

237
  void _handleWidgetRemoved(GlobalKey key) {
238
    assert(key != null);
239
    assert(_focusedWidget == key);
240
    _clearFocusedWidget();
241 242 243 244 245
  }

  void _updateWidgetRemovalListener(GlobalKey key) {
    if (_currentlyRegisteredWidgetRemovalListenerKey != key) {
      if (_currentlyRegisteredWidgetRemovalListenerKey != null)
246
        GlobalKey.unregisterRemoveListener(_currentlyRegisteredWidgetRemovalListenerKey, _handleWidgetRemoved);
247
      if (key != null)
248
        GlobalKey.registerRemoveListener(key, _handleWidgetRemoved);
249 250 251 252 253 254 255 256 257 258 259 260 261
      _currentlyRegisteredWidgetRemovalListenerKey = key;
    }
  }

  GlobalKey _focusedScope; // when null, the first scope to ask if it's focused will get the focus
  GlobalKey _currentlyRegisteredScopeRemovalListenerKey;

  void _setFocusedScope(GlobalKey key) {
    setState(() {
      _focusedScope = key;
    });
    _updateScopeRemovalListener(key);
  }
Eric Seidel's avatar
Eric Seidel committed
262

263 264
  void _scopeRemoved(GlobalKey key) {
    assert(_focusedScope == key);
265
    GlobalKey.unregisterRemoveListener(_currentlyRegisteredScopeRemovalListenerKey, _scopeRemoved);
266 267 268 269 270 271 272 273 274
    _currentlyRegisteredScopeRemovalListenerKey = null;
    setState(() {
      _focusedScope = null;
    });
  }

  void _updateScopeRemovalListener(GlobalKey key) {
    if (_currentlyRegisteredScopeRemovalListenerKey != key) {
      if (_currentlyRegisteredScopeRemovalListenerKey != null)
275
        GlobalKey.unregisterRemoveListener(_currentlyRegisteredScopeRemovalListenerKey, _scopeRemoved);
276
      if (key != null)
277
        GlobalKey.registerRemoveListener(key, _scopeRemoved);
278 279 280 281
      _currentlyRegisteredScopeRemovalListenerKey = key;
    }
  }

282 283 284 285 286 287 288 289 290 291 292 293
  Size _mediaSize;
  EdgeDims _mediaPadding;

  void _ensureVisibleIfFocused() {
    if (!Focus._atScope(context))
      return;
    BuildContext focusedContext = _focusedWidget?.currentContext;
    if (focusedContext == null)
      return;
    Scrollable.ensureVisible(focusedContext);
  }

294
  Widget build(BuildContext context) {
295 296 297 298 299 300 301 302 303 304
    MediaQueryData data = MediaQuery.of(context);
    if (data != null) {
      Size newMediaSize = data.size;
      EdgeDims newMediaPadding = data.padding;
      if (newMediaSize != _mediaSize || newMediaPadding != _mediaPadding) {
        _mediaSize = newMediaSize;
        _mediaPadding = newMediaPadding;
        scheduleMicrotask(_ensureVisibleIfFocused);
      }
    }
Hixie's avatar
Hixie committed
305 306 307 308 309 310 311 312 313
    return new Semantics(
      container: true,
      child: new _FocusScope(
        focusState: this,
        scopeFocused: Focus._atScope(context),
        focusedScope: _focusedScope == _noFocusedScope ? null : _focusedScope,
        focusedWidget: _focusedWidget,
        child: config.child
      )
314 315
    );
  }
Eric Seidel's avatar
Eric Seidel committed
316
}