container_manager.dart 9.99 KB
Newer Older
Jidong Chen's avatar
init  
Jidong Chen committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * The MIT License (MIT)
 * 
 * Copyright (c) 2019 Alibaba Group
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
26 27 28 29
import 'boost_container.dart';
import 'container_coordinator.dart';
import '../flutter_boost.dart';
import '../support/logger.dart';
Jidong Chen's avatar
init  
Jidong Chen committed
30 31 32 33 34 35 36 37 38

enum ContainerOperation { Push, Onstage, Pop, Remove }

typedef BoostContainerObserver = void Function(
    ContainerOperation operation, BoostContainerSettings settings);

@immutable
class BoostContainerManager extends StatefulWidget {
  final Navigator initNavigator;
39 40 41 42 43
  final PrePushRoute prePushRoute;
  final PostPushRoute postPushRoute;
  const BoostContainerManager(
      {Key key, this.initNavigator, this.prePushRoute, this.postPushRoute})
      : super(key: key);
Jidong Chen's avatar
init  
Jidong Chen committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

  @override
  ContainerManagerState createState() => ContainerManagerState();

  static ContainerManagerState tryOf(BuildContext context) {
    final ContainerManagerState manager =
        context.ancestorStateOfType(const TypeMatcher<ContainerManagerState>());
    return manager;
  }

  static ContainerManagerState of(BuildContext context) {
    final ContainerManagerState manager =
        context.ancestorStateOfType(const TypeMatcher<ContainerManagerState>());
    assert(manager != null, 'not in flutter boost');
    return manager;
  }
}

class ContainerManagerState extends State<BoostContainerManager> {
  final GlobalKey<OverlayState> _overlayKey = GlobalKey<OverlayState>();
  final List<BoostContainer> _offstage = <BoostContainer>[];

  List<_ContainerOverlayEntry> _leastEntries;

  BoostContainer _onstage;
  bool _foreground = true;

  String _lastShownContainer;

73 74 75 76
  PrePushRoute get prePushRoute => widget.prePushRoute;

  PostPushRoute get postPushRoute => widget.postPushRoute;

Jidong Chen's avatar
init  
Jidong Chen committed
77 78 79 80 81 82
  bool get foreground => _foreground;


  //Number of containers.
  int get containerCounts => _offstage.length;

tuoli's avatar
tuoli committed
83 84
  List<BoostContainer> get offstage => _offstage;

Jidong Chen's avatar
init  
Jidong Chen committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  //Setting for current visible container.
  BoostContainerSettings get onstageSettings => _onstage.settings;

  //Current visible container.
  BoostContainerState get onstageContainer => _stateOf(_onstage);

  BoostContainerState get subContainer =>
      _offstage.isEmpty ? null : _stateOf(_offstage.last);

  @override
  void initState() {
    super.initState();

    assert(widget.initNavigator != null);
    _onstage = BoostContainer.copy(widget.initNavigator);
100 101 102 103

    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {});
    });
Jidong Chen's avatar
init  
Jidong Chen committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  }

  void updateFocuse() {
    final BoostContainerState now = _stateOf(_onstage);
    if (now != null) {
      FocusScope.of(context).setFirstFocus(now.focusScopeNode);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Overlay(
      key: _overlayKey,
      initialEntries: const <OverlayEntry>[],
    );
  }

  BoostContainerState _stateOf(BoostContainer container) {
    if (container.key != null &&
        container.key is GlobalKey<BoostContainerState>) {
      final GlobalKey<BoostContainerState> globalKey =
          container.key as GlobalKey<BoostContainerState>;
      return globalKey.currentState;
    }

    assert(
        false, 'key of BoostContainer must be GlobalKey<BoostContainerState>');
    return null;
  }

  void _onShownContainerChanged(String old, String now) {
    Logger.log('onShownContainerChanged old:$old now:$now');
Yacumima's avatar
Yacumima committed
136 137 138 139 140 141

    Map<String, dynamic> properties = new Map<String, dynamic>();
    properties['newName'] = now;
    properties['oldName'] = old;

    FlutterBoost.singleton.channel.invokeMethod('onShownContainerChanged',properties);
Jidong Chen's avatar
init  
Jidong Chen committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
  }

  void _refreshOverlayEntries() {
    final OverlayState overlayState = _overlayKey.currentState;

    if (overlayState == null) {
      return;
    }

    if (_leastEntries != null && _leastEntries.isNotEmpty) {
      for (_ContainerOverlayEntry entry in _leastEntries) {
        entry.remove();
      }
    }

    final List<BoostContainer> containers = <BoostContainer>[];
    containers.addAll(_offstage);

    assert(_onstage != null, 'Should have a least one BoostContainer');
    containers.add(_onstage);

    _leastEntries = containers
        .map<_ContainerOverlayEntry>(
            (BoostContainer container) => _ContainerOverlayEntry(container))
        .toList(growable: false);

    overlayState.insertAll(_leastEntries);

    SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
      final String now = _onstage.settings.uniqueId;
      if (_lastShownContainer != now) {
        final String old = _lastShownContainer;
        _lastShownContainer = now;
        _onShownContainerChanged(old, now);
      }
      updateFocuse();
    });
  }

  @override
  void setState(VoidCallback fn) {
    if (SchedulerBinding.instance.schedulerPhase ==
        SchedulerPhase.persistentCallbacks) {
      SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
        _refreshOverlayEntries();
      });
    } else {
      _refreshOverlayEntries();
    }

    fn();
    //return super.setState(fn);
  }

  void setForeground() {
    _foreground = true;
    ContainerCoordinator.performContainerLifeCycle(
        _onstage.settings, ContainerLifeCycle.Foreground);
  }

  void setBackground() {
    _foreground = false;
    ContainerCoordinator.performContainerLifeCycle(
        _onstage.settings, ContainerLifeCycle.Background);
  }

  //If container exists bring it to front else
  //create a container.
  void showContainer(BoostContainerSettings settings) {
    if (settings.uniqueId == _onstage.settings.uniqueId) {
      _onShownContainerChanged(null, settings.uniqueId);
      return;
    }

    final int index = _offstage.indexWhere((BoostContainer container) =>
        container.settings.uniqueId == settings.uniqueId);
    if (index > -1) {
      _offstage.add(_onstage);
      _onstage = _offstage.removeAt(index);

      setState(() {});

      for (BoostContainerObserver observer in FlutterBoost
          .singleton.observersHolder
          .observersOf<BoostContainerObserver>()) {
        observer(ContainerOperation.Onstage, _onstage.settings);
      }
余玠's avatar
余玠 committed
229
      Logger.log('ContainerObserver#2 didOnstage');
Jidong Chen's avatar
init  
Jidong Chen committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    } else {
      pushContainer(settings);
    }
  }

  BoostContainerState containerStateOf(String id) {
    if (id == _onstage.settings.uniqueId) {
      return _stateOf(_onstage);
    }

    final BoostContainer container = _offstage.firstWhere(
        (BoostContainer container) => container.settings.uniqueId == id,
        orElse: () => null);

    return container == null ? null : _stateOf(container);
  }

  bool containsContainer(String id) {
    if (id == _onstage.settings.uniqueId) {
      return true;
    }

    return _offstage
        .any((BoostContainer container) => container.settings.uniqueId == id);
  }

  void pushContainer(BoostContainerSettings settings) {
    assert(settings.uniqueId != _onstage.settings.uniqueId);
    assert(_offstage.every((BoostContainer container) =>
        container.settings.uniqueId != settings.uniqueId));

    _offstage.add(_onstage);
    _onstage = BoostContainer.obtain(widget.initNavigator, settings);

    setState(() {});

    for (BoostContainerObserver observer in FlutterBoost
        .singleton.observersHolder
        .observersOf<BoostContainerObserver>()) {
      observer(ContainerOperation.Push, _onstage.settings);
    }
余玠's avatar
余玠 committed
271
    Logger.log('ContainerObserver#2 didPush');
Jidong Chen's avatar
init  
Jidong Chen committed
272 273 274 275 276
  }

  void pop() {
    assert(canPop());

Yacumima's avatar
Yacumima committed
277
    final BoostContainer old = _onstage;
Jidong Chen's avatar
init  
Jidong Chen committed
278 279 280 281 282 283
    _onstage = _offstage.removeLast();
    setState(() {});

    for (BoostContainerObserver observer in FlutterBoost
        .singleton.observersHolder
        .observersOf<BoostContainerObserver>()) {
Yacumima's avatar
Yacumima committed
284
      observer(ContainerOperation.Pop, old.settings);
Jidong Chen's avatar
init  
Jidong Chen committed
285 286
    }

余玠's avatar
余玠 committed
287
    Logger.log('ContainerObserver#2 didPop');
Jidong Chen's avatar
init  
Jidong Chen committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
  }

  void remove(String uniqueId) {
    if (_onstage.settings.uniqueId == uniqueId) {
      pop();
    } else {
      final BoostContainer container = _offstage.firstWhere(
          (BoostContainer container) => container.settings.uniqueId == uniqueId,
          orElse: () => null);

      if (container != null) {
        _offstage.remove(container);
        setState(() {});

        for (BoostContainerObserver observer in FlutterBoost
            .singleton.observersHolder
            .observersOf<BoostContainerObserver>()) {
Yacumima's avatar
Yacumima committed
305
          observer(ContainerOperation.Remove, container.settings);
Jidong Chen's avatar
init  
Jidong Chen committed
306 307
        }

余玠's avatar
余玠 committed
308
        Logger.log('ContainerObserver#2 didRemove');
Jidong Chen's avatar
init  
Jidong Chen committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
      }
    }

    return null;
  }

  bool canPop() => _offstage.isNotEmpty;

  String dump() {
    String info = 'onstage#:\n  ${_onstage?.desc()}\noffstage#:';

    for (BoostContainer container in _offstage.reversed) {
      info = '$info\n  ${container?.desc()}';
    }

    return info;
  }
}

class _ContainerOverlayEntry extends OverlayEntry {
  bool _removed = false;
  _ContainerOverlayEntry(BoostContainer container)
      : super(
            builder: (BuildContext ctx) => container,
            opaque: true,
            maintainState: true);

  @override
  void remove() {
    assert(!_removed);

    if (_removed) {
      return;
    }

    _removed = true;
    super.remove();
  }
}